repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
apache/geode
37,365
geode-wan/src/distributedTest/java/org/apache/geode/internal/cache/wan/concurrent/ConcurrentParallelGatewaySenderOperation_1_DUnitTest.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.geode.internal.cache.wan.concurrent; import static org.junit.Assert.fail; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.wan.GatewaySender.OrderPolicy; import org.apache.geode.internal.cache.wan.WANTestBase; import org.apache.geode.test.dunit.AsyncInvocation; import org.apache.geode.test.dunit.IgnoredException; import org.apache.geode.test.dunit.LogWriterUtils; import org.apache.geode.test.dunit.Wait; import org.apache.geode.test.junit.categories.WanTest; @Category({WanTest.class}) public class ConcurrentParallelGatewaySenderOperation_1_DUnitTest extends WANTestBase { private static final long serialVersionUID = 1L; public ConcurrentParallelGatewaySenderOperation_1_DUnitTest() { super(); } @Override protected final void postSetUpWANTestBase() throws Exception { IgnoredException.addIgnoredException("Broken pipe"); IgnoredException.addIgnoredException("Connection reset"); IgnoredException.addIgnoredException("Unexpected IOException"); } @Test public void testParallelGatewaySenderWithoutStarting() { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 6, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 6, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 6, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 6, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); vm4.invoke(() -> WANTestBase.verifySenderStoppedState("ln")); vm5.invoke(() -> WANTestBase.verifySenderStoppedState("ln")); vm6.invoke(() -> WANTestBase.verifySenderStoppedState("ln")); vm7.invoke(() -> WANTestBase.verifySenderStoppedState("ln")); vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 0)); vm3.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 0)); } /** * Defect 44323 (ParallelGatewaySender should not be started on Accessor node) */ @Test public void testParallelGatewaySenderStartOnAccessorNode() { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegionAsAccessor(getTestMethodName() + "_PR", "ln", 1, 100)); vm7.invoke(() -> WANTestBase.createPartitionedRegionAsAccessor(getTestMethodName() + "_PR", "ln", 1, 100)); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); // start the senders startSenderInVMs("ln", vm4, vm5, vm6, vm7); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); vm4.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm5.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 1000)); vm3.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 1000)); } /** * Normal scenario in which the sender is paused in between. * */ @Test public void testParallelPropagationSenderPause() throws Exception { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); startSenderInVMs("ln", vm4, vm5, vm6, vm7); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); // make sure all the senders are running before doing any puts vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // FIRST RUN: now, the senders are started. So, start the puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 100)); // now, pause all of the senders vm4.invoke(() -> WANTestBase.pauseSender("ln")); vm5.invoke(() -> WANTestBase.pauseSender("ln")); vm6.invoke(() -> WANTestBase.pauseSender("ln")); vm7.invoke(() -> WANTestBase.pauseSender("ln")); Wait.pause(2000); // SECOND RUN: keep one thread doing puts to the region vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); // verify region size remains on remote vm and is restricted below a specified limit (i.e. // number of puts in the first run) vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 100)); } /** * Normal scenario in which a paused sender is resumed. * */ @Test public void testParallelPropagationSenderResume() throws Exception { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 8, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 8, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 8, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 8, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); startSenderInVMs("ln", vm4, vm5, vm6, vm7); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); // make sure all the senders are running before doing any puts vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // now, the senders are started. So, start the puts vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); // now, pause all of the senders vm4.invoke(() -> WANTestBase.pauseSender("ln")); vm5.invoke(() -> WANTestBase.pauseSender("ln")); vm6.invoke(() -> WANTestBase.pauseSender("ln")); vm7.invoke(() -> WANTestBase.pauseSender("ln")); // sleep for a second or two Wait.pause(2000); // resume the senders vm4.invoke(() -> WANTestBase.resumeSender("ln")); vm5.invoke(() -> WANTestBase.resumeSender("ln")); vm6.invoke(() -> WANTestBase.resumeSender("ln")); vm7.invoke(() -> WANTestBase.resumeSender("ln")); Wait.pause(2000); vm4.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm5.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm6.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm7.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); // find the region size on remote vm vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 1000)); } /** * Negative scenario in which a sender that is stopped (and not paused) is resumed. Expected: * resume is only valid for pause. If a sender which is stopped is resumed, it will not be started * again. * */ @Test public void testParallelPropagationSenderResumeNegativeScenario() throws Exception { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createReceiverInVMs(vm2, vm3); createCacheInVMs(nyPort, vm4, vm5); vm4.invoke(() -> WANTestBase.createCache(lnPort)); vm5.invoke(() -> WANTestBase.createCache(lnPort)); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); startSenderInVMs("ln", vm4, vm5); // wait till the senders are running vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // start the puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 100)); // let the queue drain completely vm4.invoke(() -> WANTestBase.validateQueueContents("ln", 0)); // stop the senders vm4.invoke(() -> WANTestBase.stopSender("ln")); vm5.invoke(() -> WANTestBase.stopSender("ln")); // now, try to resume a stopped sender vm4.invoke(() -> WANTestBase.resumeSender("ln")); vm5.invoke(() -> WANTestBase.resumeSender("ln")); // do more puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); // validate region size on remote vm to contain only the events put in local site // before the senders are stopped. vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 100)); } /** * Normal scenario in which a sender is stopped. * */ @Test public void testParallelPropagationSenderStop() throws Exception { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 3, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 3, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 3, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 3, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); startSenderInVMs("ln", vm4, vm5, vm6, vm7); // make sure all the senders are running before doing any puts vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // FIRST RUN: now, the senders are started. So, do some of the puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 100)); // now, stop all of the senders vm4.invoke(() -> WANTestBase.stopSender("ln")); vm5.invoke(() -> WANTestBase.stopSender("ln")); vm6.invoke(() -> WANTestBase.stopSender("ln")); vm7.invoke(() -> WANTestBase.stopSender("ln")); // SECOND RUN: keep one thread doing puts vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); // verify region size remains on remote vm and is restricted below a specified limit (number of // puts in the first run) vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 100)); } /** * Normal scenario in which a sender is stopped and then started again. */ @Test public void testParallelPropagationSenderStartAfterStop() throws Throwable { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); startSenderInVMs("ln", vm4, vm5, vm6, vm7); // make sure all the senders are running before doing any puts vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // FIRST RUN: now, the senders are started. So, do some of the puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 200)); // now, stop all of the senders vm4.invoke(() -> WANTestBase.stopSender("ln")); vm5.invoke(() -> WANTestBase.stopSender("ln")); vm6.invoke(() -> WANTestBase.stopSender("ln")); vm7.invoke(() -> WANTestBase.stopSender("ln")); Wait.pause(2000); // SECOND RUN: do some of the puts after the senders are stopped vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); // Region size on remote site should remain same and below the number of puts done in the FIRST // RUN vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 200)); // start the senders again AsyncInvocation<Void> vm4start = vm4.invokeAsync(() -> WANTestBase.startSender("ln")); AsyncInvocation<Void> vm5start = vm5.invokeAsync(() -> WANTestBase.startSender("ln")); AsyncInvocation<Void> vm6start = vm6.invokeAsync(() -> WANTestBase.startSender("ln")); AsyncInvocation<Void> vm7start = vm7.invokeAsync(() -> WANTestBase.startSender("ln")); int START_TIMEOUT = 30000; vm4start.getResult(START_TIMEOUT); vm5start.getResult(START_TIMEOUT); vm6start.getResult(START_TIMEOUT); vm7start.getResult(START_TIMEOUT); // make sure all the senders are running before doing any puts vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // Region size on remote site should remain same and below the number of puts done in the FIRST // RUN vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 200)); // SECOND RUN: do some more puts AsyncInvocation<Void> async = vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); async.join(); // verify all the buckets on all the sender nodes are drained vm4.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm5.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm6.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm7.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); // verify the events propagate to remote site vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 1000)); vm4.invoke(() -> WANTestBase.validateQueueSizeStat("ln", 0)); vm5.invoke(() -> WANTestBase.validateQueueSizeStat("ln", 0)); vm6.invoke(() -> WANTestBase.validateQueueSizeStat("ln", 0)); vm7.invoke(() -> WANTestBase.validateQueueSizeStat("ln", 0)); } /** * Normal scenario in which a sender is stopped and then started again. Differs from above test * case in the way that when the sender is starting from stopped state, puts are simultaneously * happening on the region by another thread. * */ @Ignore("Bug47553") @Test public void testParallelPropagationSenderStartAfterStop_Scenario2() throws Exception { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 7, OrderPolicy.KEY)); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); startSenderInVMs("ln", vm4, vm5, vm6, vm7); // make sure all the senders are running before doing any puts vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); LogWriterUtils.getLogWriter().info("All the senders are now started"); // FIRST RUN: now, the senders are started. So, do some of the puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 200)); LogWriterUtils.getLogWriter().info("Done few puts"); // now, stop all of the senders vm4.invoke(() -> WANTestBase.stopSender("ln")); vm5.invoke(() -> WANTestBase.stopSender("ln")); vm6.invoke(() -> WANTestBase.stopSender("ln")); vm7.invoke(() -> WANTestBase.stopSender("ln")); LogWriterUtils.getLogWriter().info("All the senders are stopped"); Wait.pause(2000); // SECOND RUN: do some of the puts after the senders are stopped vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); LogWriterUtils.getLogWriter().info("Done some more puts in second run"); // Region size on remote site should remain same and below the number of puts done in the FIRST // RUN vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 200)); // SECOND RUN: start async puts on region AsyncInvocation<Void> async = vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 5000)); LogWriterUtils.getLogWriter().info("Started high number of puts by async thread"); LogWriterUtils.getLogWriter().info("Starting the senders at the same time"); // when puts are happening by another thread, start the senders startSenderInVMsAsync("ln", vm4, vm5, vm6, vm7); LogWriterUtils.getLogWriter().info("All the senders are started"); async.join(); Wait.pause(2000); // verify all the buckets on all the sender nodes are drained vm4.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm5.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm6.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm7.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); // verify that the queue size ultimately becomes zero. That means all the events propagate to // remote site. vm4.invoke(() -> WANTestBase.validateQueueContents("ln", 0)); } /** * Normal scenario in which a sender is stopped and then started again on accessor node. * */ @Test public void testParallelPropagationSenderStartAfterStopOnAccessorNode() throws Throwable { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegionAsAccessor(getTestMethodName() + "_PR", "ln", 1, 100)); vm7.invoke(() -> WANTestBase.createPartitionedRegionAsAccessor(getTestMethodName() + "_PR", "ln", 1, 100)); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 4, OrderPolicy.KEY)); startSenderInVMs("ln", vm4, vm5, vm6, vm7); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); createReceiverInVMs(vm2, vm3); // make sure all the senders are not running on accessor nodes and running on non-accessor nodes vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // FIRST RUN: now, the senders are started. So, do some of the puts vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 200)); // now, stop all of the senders vm4.invoke(() -> WANTestBase.stopSender("ln")); vm5.invoke(() -> WANTestBase.stopSender("ln")); vm6.invoke(() -> WANTestBase.stopSender("ln")); vm7.invoke(() -> WANTestBase.stopSender("ln")); // SECOND RUN: do some of the puts after the senders are stopped vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); // Region size on remote site should remain same and below the number of puts done in the FIRST // RUN vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 200)); // start the senders again AsyncInvocation<Void> vm4start = vm4.invokeAsync(() -> WANTestBase.startSender("ln")); AsyncInvocation<Void> vm5start = vm5.invokeAsync(() -> WANTestBase.startSender("ln")); AsyncInvocation<Void> vm6start = vm6.invokeAsync(() -> WANTestBase.startSender("ln")); AsyncInvocation<Void> vm7start = vm7.invokeAsync(() -> WANTestBase.startSender("ln")); vm4start.join(); vm5start.join(); vm6start.join(); vm7start.join(); vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); // Region size on remote site should remain same and below the number of puts done in the FIRST // RUN vm2.invoke(() -> WANTestBase.validateRegionSizeRemainsSame(getTestMethodName() + "_PR", 200)); // SECOND RUN: do some more puts AsyncInvocation<Void> async = vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); async.join(); vm4.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 1000)); // verify all buckets drained only on non-accessor nodes. vm4.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm5.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); // verify the events propagate to remote site vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 1000)); } /** * Normal scenario in which a combinations of start, pause, resume operations is tested */ @Test public void testStartPauseResumeParallelGatewaySender() throws Exception { Integer lnPort = vm0.invoke(() -> WANTestBase.createFirstLocatorWithDSId(1)); Integer nyPort = vm1.invoke(() -> WANTestBase.createFirstRemoteLocator(2, lnPort)); createCacheInVMs(nyPort, vm2, vm3); createReceiverInVMs(vm2, vm3); createCacheInVMs(lnPort, vm4, vm5, vm6, vm7); LogWriterUtils.getLogWriter().info("Created cache on local site"); vm4.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm5.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm6.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); vm7.invoke(() -> WANTestBase.createConcurrentSender("ln", 2, true, 100, 10, false, false, null, true, 5, OrderPolicy.KEY)); LogWriterUtils.getLogWriter().info("Created senders on local site"); vm4.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm5.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm6.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); vm7.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", "ln", 1, 100, isOffHeap())); LogWriterUtils.getLogWriter().info("Created PRs on local site"); vm2.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); vm3.invoke(() -> WANTestBase.createPartitionedRegion(getTestMethodName() + "_PR", null, 1, 100, isOffHeap())); LogWriterUtils.getLogWriter().info("Created PRs on remote site"); vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); LogWriterUtils.getLogWriter().info("Done 1000 puts on local site"); // Since puts are already done on userPR, it will have the buckets created. // During sender start, it will wait until those buckets are created for shadowPR as well. // Start the senders in async threads, so colocation of shadowPR will be complete and // missing buckets will be created in PRHARedundancyProvider.createMissingBuckets(). startSenderInVMsAsync("ln", vm4, vm5, vm6, vm7); vm4.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm5.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm6.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); vm7.invoke(() -> WANTestBase.waitForSenderRunningState("ln")); LogWriterUtils.getLogWriter().info("Started senders on local site"); vm4.invoke(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 5000)); LogWriterUtils.getLogWriter().info("Done 5000 puts on local site"); vm4.invoke(() -> WANTestBase.pauseSender("ln")); vm5.invoke(() -> WANTestBase.pauseSender("ln")); vm6.invoke(() -> WANTestBase.pauseSender("ln")); vm7.invoke(() -> WANTestBase.pauseSender("ln")); LogWriterUtils.getLogWriter().info("Paused senders on local site"); vm4.invoke(() -> WANTestBase.verifySenderPausedState("ln")); vm5.invoke(() -> WANTestBase.verifySenderPausedState("ln")); vm6.invoke(() -> WANTestBase.verifySenderPausedState("ln")); vm7.invoke(() -> WANTestBase.verifySenderPausedState("ln")); AsyncInvocation<Void> inv1 = vm4.invokeAsync(() -> WANTestBase.doPuts(getTestMethodName() + "_PR", 1000)); LogWriterUtils.getLogWriter().info("Started 1000 async puts on local site"); vm4.invoke(() -> WANTestBase.resumeSender("ln")); vm5.invoke(() -> WANTestBase.resumeSender("ln")); vm6.invoke(() -> WANTestBase.resumeSender("ln")); vm7.invoke(() -> WANTestBase.resumeSender("ln")); LogWriterUtils.getLogWriter().info("Resumed senders on local site"); vm4.invoke(() -> WANTestBase.verifySenderResumedState("ln")); vm5.invoke(() -> WANTestBase.verifySenderResumedState("ln")); vm6.invoke(() -> WANTestBase.verifySenderResumedState("ln")); vm7.invoke(() -> WANTestBase.verifySenderResumedState("ln")); try { inv1.join(); } catch (InterruptedException e) { e.printStackTrace(); fail("Interrupted the async invocation."); } // verify all buckets drained on all sender nodes. vm4.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm5.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm6.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm7.invoke(() -> WANTestBase.validateParallelSenderQueueAllBucketsDrained("ln")); vm2.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 5000)); vm3.invoke(() -> WANTestBase.validateRegionSize(getTestMethodName() + "_PR", 5000)); } }
googleapis/google-cloud-java
37,602
java-dataform/proto-google-cloud-dataform-v1/src/main/java/com/google/cloud/dataform/v1/QueryCompilationResultActionsRequest.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/dataform/v1/dataform.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataform.v1; /** * * * <pre> * `QueryCompilationResultActions` request message. * </pre> * * Protobuf type {@code google.cloud.dataform.v1.QueryCompilationResultActionsRequest} */ public final class QueryCompilationResultActionsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataform.v1.QueryCompilationResultActionsRequest) QueryCompilationResultActionsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use QueryCompilationResultActionsRequest.newBuilder() to construct. private QueryCompilationResultActionsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private QueryCompilationResultActionsRequest() { name_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new QueryCompilationResultActionsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_QueryCompilationResultActionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_QueryCompilationResultActionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.class, com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. Maximum number of compilation results to return. The server may * return fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (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(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } 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.cloud.dataform.v1.QueryCompilationResultActionsRequest)) { return super.equals(obj); } com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest other = (com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest) obj; if (!getName().equals(other.getName())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest 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.dataform.v1.QueryCompilationResultActionsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest 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.dataform.v1.QueryCompilationResultActionsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest 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.dataform.v1.QueryCompilationResultActionsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest 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.dataform.v1.QueryCompilationResultActionsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest 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.dataform.v1.QueryCompilationResultActionsRequest 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> * `QueryCompilationResultActions` request message. * </pre> * * Protobuf type {@code google.cloud.dataform.v1.QueryCompilationResultActionsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataform.v1.QueryCompilationResultActionsRequest) com.google.cloud.dataform.v1.QueryCompilationResultActionsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_QueryCompilationResultActionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_QueryCompilationResultActionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.class, com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.Builder.class); } // Construct using // com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataform.v1.DataformProto .internal_static_google_cloud_dataform_v1_QueryCompilationResultActionsRequest_descriptor; } @java.lang.Override public com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest getDefaultInstanceForType() { return com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest build() { com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest buildPartial() { com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest result = new com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @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.dataform.v1.QueryCompilationResultActionsRequest) { return mergeFrom((com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest other) { if (other == com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The compilation result's name. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Maximum number of compilation results to return. The server may * return fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Maximum number of compilation results to return. The server may * return fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Maximum number of compilation results to return. The server may * return fewer items than requested. If unspecified, the server will pick an * appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. Page token received from a previous * `QueryCompilationResultActions` call. Provide this to retrieve the * subsequent page. * * When paginating, all other parameters provided to * `QueryCompilationResultActions`, with the exception of `page_size`, must * match the call that provided the page token. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. Optional filter for the returned list. Filtering is only * currently supported on the `file_path` field. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 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.dataform.v1.QueryCompilationResultActionsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dataform.v1.QueryCompilationResultActionsRequest) private static final com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest(); } public static com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<QueryCompilationResultActionsRequest> PARSER = new com.google.protobuf.AbstractParser<QueryCompilationResultActionsRequest>() { @java.lang.Override public QueryCompilationResultActionsRequest 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<QueryCompilationResultActionsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<QueryCompilationResultActionsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataform.v1.QueryCompilationResultActionsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
37,900
jdk/test/java/time/test/java/time/chrono/TestUmmAlQuraChronology.java
/* * Copyright (c) 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 test.java.time.chrono; import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_YEAR; import static java.time.temporal.ChronoField.MONTH_OF_YEAR; import static java.time.temporal.ChronoField.YEAR; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.time.DateTimeException; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.chrono.ChronoLocalDate; import java.time.chrono.ChronoLocalDateTime; import java.time.chrono.ChronoPeriod; import java.time.chrono.ChronoZonedDateTime; import java.time.chrono.Chronology; import java.time.chrono.HijrahChronology; import java.time.chrono.HijrahDate; import java.time.chrono.JapaneseChronology; import java.time.chrono.JapaneseDate; import java.time.chrono.MinguoChronology; import java.time.chrono.MinguoDate; import java.time.chrono.ThaiBuddhistChronology; import java.time.chrono.ThaiBuddhistDate; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjusters; import java.time.temporal.ValueRange; import java.time.temporal.WeekFields; import java.util.Locale; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Tests for the Umm alQura chronology and data. * Note: The dates used for testing are just a sample of calendar data. */ @Test public class TestUmmAlQuraChronology { private static final ZoneOffset OFFSET_PTWO = ZoneOffset.ofHours(2); private static final ZoneId ZONE_RIYADH = ZoneId.of("Asia/Riyadh"); // Test for HijrahChronology Aliases @Test public void test_aliases() { HijrahChronology hc = (HijrahChronology) Chronology.of("Hijrah"); assertEquals(hc, HijrahChronology.INSTANCE, "Alias for Hijrah-umalqura"); hc = (HijrahChronology) Chronology.of("islamic"); assertEquals(hc, HijrahChronology.INSTANCE, "Alias for Hijrah-umalqura"); } // Test to check if the exception is thrown for an incorrect chronology id @Test(expectedExceptions=DateTimeException.class) public void test_badChronology() { Chronology test = Chronology.of("Hijrah-ummalqura"); } //-------------------------------------------------------------------------- // regular data factory for Umm alQura dates and the corresponding ISO dates //-------------------------------------------------------------------------- @DataProvider(name = "UmmAlQuraVsISODates") Object[][] data_UmmAlQuraVsISODates() { return new Object[][] { {HijrahDate.of(1318, 1, 1), LocalDate.of(1900, 04, 30)}, {HijrahDate.of(1318, 12, 29), LocalDate.of(1901, 04, 19)}, {HijrahDate.of(1319, 01, 01), LocalDate.of(1901, 04, 20)}, {HijrahDate.of(1433, 12, 29), LocalDate.of(2012, 11, 14)}, {HijrahDate.of(1434, 01, 01), LocalDate.of(2012, 11, 15)}, {HijrahDate.of(1434, 02, 18), LocalDate.of(2012, 12, 31)}, {HijrahDate.of(1502, 12, 29), LocalDate.of(2079, 10, 25)}, }; } // Test to verify the epoch days for given Hijrah & ISO date instances @Test(dataProvider="UmmAlQuraVsISODates") public void Test_UmmAlQuraVsISODates(HijrahDate hd, LocalDate ld) { assertEquals(hd.toEpochDay(), ld.toEpochDay(), "Umm alQura date and ISO date should have same epochDay"); } // UmmAlQura chronology ranges for year, month and days for the HijrahChronology @Test public void Test_UmmAlQuraChronoRange() { HijrahChronology chrono = HijrahChronology.INSTANCE; ValueRange year = chrono.range(YEAR); assertEquals(year.getMinimum(), 1300, "Minimum year"); assertEquals(year.getLargestMinimum(), 1300, "Largest minimum year"); assertEquals(year.getMaximum(), 1600, "Largest year"); assertEquals(year.getSmallestMaximum(), 1600, "Smallest Maximum year"); ValueRange month = chrono.range(MONTH_OF_YEAR); assertEquals(month.getMinimum(), 1, "Minimum month"); assertEquals(month.getLargestMinimum(), 1, "Largest minimum month"); assertEquals(month.getMaximum(), 12, "Largest month"); assertEquals(month.getSmallestMaximum(), 12, "Smallest Maximum month"); ValueRange day = chrono.range(DAY_OF_MONTH); assertEquals(day.getMinimum(), 1, "Minimum day"); assertEquals(day.getLargestMinimum(), 1, "Largest minimum day"); assertEquals(day.getMaximum(), 30, "Largest day"); assertEquals(day.getSmallestMaximum(), 29, "Smallest Maximum day"); } //----------------------------------------------------------------------- // regular data factory for dates and the corresponding range values //----------------------------------------------------------------------- @DataProvider(name = "dates") Object[][] data_dates() { return new Object[][]{ {HijrahDate.of(1300, 5, 1), 1300, 1600, 1, 12, 1, 30, 30}, {HijrahDate.of(1300, 6, 1), 1300, 1600, 1, 12, 1, 29, 30}, {HijrahDate.of(1434, 12, 1), 1300, 1600, 1, 12, 1, 29, 30}, {HijrahDate.of(1500, 4, 1), 1300, 1600, 1, 12, 1, 30, 30}, {HijrahDate.of(1600, 6, 1), 1300, 1600, 1, 12, 1, 29, 30}, }; } // Test to verify the min/max field ranges for given dates @Test(dataProvider="dates") public void Test_UmmAlQuraRanges(HijrahDate date, int minYear, int maxYear, int minMonth, int maxMonth, int minDay, int maxDay, int maxChronoDay) { // Check the chronology ranges HijrahChronology chrono = date.getChronology(); ValueRange yearRange = chrono.range(YEAR); assertEquals(yearRange.getMinimum(), minYear, "Minimum year for Hijrah chronology"); assertEquals(yearRange.getLargestMinimum(), minYear, "Largest minimum year for Hijrah chronology"); assertEquals(yearRange.getMaximum(), maxYear, "Maximum year for Hijrah chronology"); assertEquals(yearRange.getSmallestMaximum(), maxYear, "Smallest Maximum year for Hijrah chronology"); ValueRange monthRange = chrono.range(MONTH_OF_YEAR); assertEquals(monthRange.getMinimum(), minMonth, "Minimum month for Hijrah chronology"); assertEquals(monthRange.getMaximum(), maxMonth, "Maximum month for Hijrah chronology"); ValueRange daysRange = chrono.range(DAY_OF_MONTH); assertEquals(daysRange.getMinimum(), minDay, "Minimum day for chronology"); assertEquals(daysRange.getMaximum(), maxChronoDay, "Maximum day for Hijrah chronology"); // Check the date ranges yearRange = date.range(YEAR); assertEquals(yearRange.getMinimum(), minYear, "Minimum year for Hijrah date"); assertEquals(yearRange.getLargestMinimum(), minYear, "Largest minimum year for Hijrah date"); assertEquals(yearRange.getMaximum(), maxYear, "Maximum year for Hijrah date"); assertEquals(yearRange.getSmallestMaximum(), maxYear, "Smallest maximum year for Hijrah date"); monthRange = date.range(MONTH_OF_YEAR); assertEquals(monthRange.getMinimum(), minMonth, "Minimum month for HijrahDate"); assertEquals(monthRange.getMaximum(), maxMonth, "Maximum month for HijrahDate"); daysRange = date.range(DAY_OF_MONTH); assertEquals(daysRange.getMinimum(), minDay, "Minimum day for HijrahDate"); assertEquals(daysRange.getMaximum(), maxDay, "Maximum day for HijrahDate"); } // Check the date limits @Test public void test_hijrahDateLimits() { HijrahChronology chrono = HijrahChronology.INSTANCE; ValueRange yearRange = chrono.range(YEAR); ValueRange monthRange = chrono.range(MONTH_OF_YEAR); ValueRange dayRange = chrono.range(DAY_OF_MONTH); HijrahDate xx = chrono.date(1434, 1, 1); HijrahDate minDate = chrono.date((int)yearRange.getLargestMinimum(), (int)monthRange.getMinimum(), (int)dayRange.getMinimum()); try { HijrahDate before = minDate.minus(1, ChronoUnit.DAYS); fail("Exception did not occur, minDate: " + minDate + ".minus(1, DAYS) = " + before); } catch (DateTimeException ex) { // ignore, this exception was expected } HijrahDate maxDate = chrono.date((int)yearRange.getSmallestMaximum(), (int)monthRange.getMaximum(), 1); int monthLen = maxDate.lengthOfMonth(); maxDate = maxDate.with(DAY_OF_MONTH, monthLen); try { HijrahDate after = maxDate.plus(1, ChronoUnit.DAYS); fail("Exception did not occur, maxDate: " + maxDate + ".plus(1, DAYS) = " + after); } catch (DateTimeException ex) { // ignore, this exception was expected } } // Data provider to verify the dateYearDay() method @DataProvider(name="dateYearDay") Object[][] data_dateYearDay() { return new Object[][] { {HijrahChronology.INSTANCE.dateYearDay(1434, 42), HijrahChronology.INSTANCE.date(1434, 02, 13)}, {HijrahChronology.INSTANCE.dateYearDay(1330, 354), HijrahChronology.INSTANCE.date(1330, 12, 29)}, {HijrahChronology.INSTANCE.dateYearDay(1600, 1), HijrahChronology.INSTANCE.date(1600, 1, 1)}, {HijrahChronology.INSTANCE.dateYearDay(1400, 175), HijrahChronology.INSTANCE.date(1400, 6, 28)}, {HijrahChronology.INSTANCE.dateYearDay(1520, 190), HijrahChronology.INSTANCE.date(1520, 7, 13)}, {HijrahChronology.INSTANCE.dateYearDay(1521, 112), HijrahChronology.INSTANCE.date(1521, 4, 25)}, }; } // Test to verify the dateYearDay() method @Test(dataProvider="dateYearDay") public void test_DateYearDay(ChronoLocalDate date1, ChronoLocalDate date2) { assertEquals(date1, date2); } //----------------------------------------------------------------------- // HijrahDate.with(DAY_OF_YEAR, n) //----------------------------------------------------------------------- @Test public void test_getDayOfYear() { HijrahDate hd1 = HijrahChronology.INSTANCE.dateYearDay(1434, 1); for (int i = 1; i <= hd1.lengthOfYear(); i++) { HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1434, i); int doy = hd.get(DAY_OF_YEAR); assertEquals(doy, i, "get(DAY_OF_YEAR) incorrect for " + i); } } @Test public void test_withDayOfYear() { HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1434, 1); for (int i = 1; i <= hd.lengthOfYear(); i++) { HijrahDate hd2 = hd.with(DAY_OF_YEAR, i); int doy = hd2.get(DAY_OF_YEAR); assertEquals(doy, i, "with(DAY_OF_YEAR) incorrect for " + i + " " + hd2); } } @Test(expectedExceptions=java.time.DateTimeException.class) public void test_withDayOfYearTooSmall() { HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1435, 1); HijrahDate hd2 = hd.with(DAY_OF_YEAR, 0); } @Test(expectedExceptions=java.time.DateTimeException.class) public void test_withDayOfYearTooLarge() { HijrahDate hd = HijrahChronology.INSTANCE.dateYearDay(1435, 1); HijrahDate hd2 = hd.with(DAY_OF_YEAR, hd.lengthOfYear() + 1); } // Test to verify the with() method with ChronoField is set to DAY_OF_WEEK @Test public void test_adjustWithDayOfWeek() { assertEquals(HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_WEEK, 4), HijrahDate.of(1320, 1, 15)); assertEquals(HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_WEEK, 1), HijrahDate.of(1421, 11, 11)); assertEquals(HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_WEEK, 6), HijrahDate.of(1529, 7, 20)); assertEquals(HijrahChronology.INSTANCE.date(1534, 2, 10).with(ChronoField.DAY_OF_WEEK, 5), HijrahDate.of(1534, 2, 12)); assertEquals(HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_WEEK, 2), HijrahDate.of(1552, 3, 26)); } // Test to verify the with() method with ChronoField is set to DAY_OF_MONTH @Test public void test_adjustWithDayOfMonth() { assertEquals(HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_MONTH, 2), HijrahDate.of(1320, 1, 2)); assertEquals(HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_MONTH, 9), HijrahDate.of(1421, 11, 9)); assertEquals(HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_MONTH, 13), HijrahDate.of(1529, 7, 13)); assertEquals(HijrahChronology.INSTANCE.date(1534, 12, 10).with(ChronoField.DAY_OF_MONTH, 29), HijrahDate.of(1534, 12, 29)); assertEquals(HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_MONTH, 6), HijrahDate.of(1552, 4, 6)); } // Test to verify the with() method with ChronoField is set to DAY_OF_YEAR @Test public void test_adjustWithDayOfYear() { assertEquals(HijrahChronology.INSTANCE.date(1320, 1, 15).with(ChronoField.DAY_OF_YEAR, 24), HijrahDate.of(1320, 1, 24)); assertEquals(HijrahChronology.INSTANCE.date(1421, 11, 15).with(ChronoField.DAY_OF_YEAR, 135), HijrahDate.of(1421, 5, 18)); assertEquals(HijrahChronology.INSTANCE.date(1529, 7, 18).with(ChronoField.DAY_OF_YEAR, 64), HijrahDate.of(1529, 3, 5)); assertEquals(HijrahChronology.INSTANCE.date(1534, 2, 10).with(ChronoField.DAY_OF_YEAR, 354), HijrahDate.of(1534, 12, 29)); assertEquals(HijrahChronology.INSTANCE.date(1552, 4, 1).with(ChronoField.DAY_OF_YEAR, 291), HijrahDate.of(1552, 10, 26)); } // Data provider to get the difference between two dates in terms of days, months and years @DataProvider(name="datesForDiff") Object[][] data_datesForDiffs() { return new Object[][] { {HijrahDate.of(1350, 5, 15), HijrahDate.of(1351, 12, 29), 574, 19, 1}, {HijrahDate.of(1434, 5, 1), HijrahDate.of(1434,6, 12), 40, 1, 0}, {HijrahDate.of(1436, 1, 1), HijrahDate.of(1475, 12, 29), 14173, 479, 39}, {HijrahDate.of(1500, 6, 12), HijrahDate.of(1551, 7, 12), 18102, 613, 51}, {HijrahDate.of(1550, 3, 11), HijrahDate.of(1551, 4, 11), 384, 13, 1}, }; } // Test to verify the difference between two given dates in terms of days, months and years @Test(dataProvider="datesForDiff") public void test_diffBetweenDates(ChronoLocalDate from, ChronoLocalDate to, long days, long months, long years) { assertEquals(from.until(to, ChronoUnit.DAYS), days); assertEquals(from.until(to, ChronoUnit.MONTHS), months); assertEquals(from.until(to, ChronoUnit.YEARS), years); } // Data provider to get the difference between two dates as a period @DataProvider(name="datesForPeriod") Object[][] data_Period() { return new Object[][] { {HijrahDate.of(1350, 5, 15), HijrahDate.of(1434, 7, 20), HijrahChronology.INSTANCE.period(84, 2, 5)}, {HijrahDate.of(1403, 5, 28), HijrahDate.of(1434, 7, 20), HijrahChronology.INSTANCE.period(31, 1, 22)}, {HijrahDate.of(1434, 7, 20), HijrahDate.of(1484, 2, 15), HijrahChronology.INSTANCE.period(49, 6, 24)}, {HijrahDate.of(1500, 6, 12), HijrahDate.of(1450, 4, 21), HijrahChronology.INSTANCE.period(-50, -1, -20)}, {HijrahDate.of(1549, 3, 11), HijrahDate.of(1550, 3, 10), HijrahChronology.INSTANCE.period(0, 11, 28)}, }; } // Test to get the Period between two given dates @Test(dataProvider="datesForPeriod") public void test_until(HijrahDate h1, HijrahDate h2, ChronoPeriod p) { ChronoPeriod period = h1.until(h2); assertEquals(period, p); } // Test to get the Period between dates in different chronologies @Test(dataProvider="datesForPeriod") public void test_periodUntilDiffChrono(HijrahDate h1, HijrahDate h2, ChronoPeriod p) { MinguoDate m = MinguoChronology.INSTANCE.date(h2); ChronoPeriod period = h1.until(m); assertEquals(period, p); } // Test to get the adjusted date from a given date using TemporalAdjuster methods @Test public void test_temporalDayAdjustments() { HijrahDate date = HijrahDate.of(1554, 7, 21); assertEquals(date.with(TemporalAdjusters.firstDayOfMonth()), HijrahDate.of(1554, 7, 1)); assertEquals(date.with(TemporalAdjusters.lastDayOfMonth()), HijrahDate.of(1554, 7, 29)); assertEquals(date.with(TemporalAdjusters.firstDayOfNextMonth()), HijrahDate.of(1554, 8, 1)); assertEquals(date.with(TemporalAdjusters.firstDayOfNextYear()), HijrahDate.of(1555, 1, 1)); assertEquals(date.with(TemporalAdjusters.firstDayOfYear()), HijrahDate.of(1554, 1, 1)); assertEquals(date.with(TemporalAdjusters.lastDayOfYear()), HijrahDate.of(1554, 12, 30)); } // Data provider for string representation of the date instances @DataProvider(name="toString") Object[][] data_toString() { return new Object[][] { {HijrahChronology.INSTANCE.date(1320, 1, 1), "Hijrah-umalqura AH 1320-01-01"}, {HijrahChronology.INSTANCE.date(1500, 10, 28), "Hijrah-umalqura AH 1500-10-28"}, {HijrahChronology.INSTANCE.date(1500, 10, 29), "Hijrah-umalqura AH 1500-10-29"}, {HijrahChronology.INSTANCE.date(1434, 12, 5), "Hijrah-umalqura AH 1434-12-05"}, {HijrahChronology.INSTANCE.date(1434, 12, 6), "Hijrah-umalqura AH 1434-12-06"}, }; } // Test to verify the returned string value of a given date instance @Test(dataProvider="toString") public void test_toString(ChronoLocalDate hijrahDate, String expected) { assertEquals(hijrahDate.toString(), expected); } // Data provider for maximum number of days @DataProvider(name="monthDays") Object[][] data_monthDays() { return new Object[][] { {1432, 1, 29}, {1432, 4, 30}, {1433, 12, 29}, {1434, 1, 29}, {1435, 8, 29}, {1435, 9, 30}, }; } // Test to verify the maximum number of days by adding one month to a given date @Test (dataProvider="monthDays") public void test_valueRange_monthDays(int year, int month, int maxlength) { ChronoLocalDate date = HijrahChronology.INSTANCE.date(year, month, 1); ValueRange range = null; for (int i=1; i<=12; i++) { range = date.range(ChronoField.DAY_OF_MONTH); date = date.plus(1, ChronoUnit.MONTHS); assertEquals(range.getMaximum(), month, maxlength); } } // Test to get the last day of the month by adjusting the date with lastDayOfMonth() method @Test(dataProvider="monthDays") public void test_lastDayOfMonth(int year, int month, int numDays) { HijrahDate hDate = HijrahChronology.INSTANCE.date(year, month, 1); hDate = hDate.with(TemporalAdjusters.lastDayOfMonth()); assertEquals(hDate.get(ChronoField.DAY_OF_MONTH), numDays); } // Data provider for the 12 islamic month names in a formatted date @DataProvider(name="patternMonthNames") Object[][] data_patternMonthNames() { return new Object[][] { {1434, 1, 1, "01 AH Thu Muharram 1434"}, {1434, 2, 1, "01 AH Fri Safar 1434"}, {1434, 3, 1, "01 AH Sun Rabi\u02bb I 1434"},//the actual month name is Rabi Al-Awwal, but the locale data contains short form. {1434, 4, 1, "01 AH Mon Rabi\u02bb II 1434"},//the actual month name is Rabi Al-Akhar, but the locale data contains short form. {1434, 5, 1, "01 AH Wed Jumada I 1434"},//the actual month name is Jumada Al-Awwal, but the locale data contains short form. {1434, 6, 1, "01 AH Thu Jumada II 1434"},//the actual month name is Jumada Al-Akhar, but the locale data contains short form. {1434, 7, 1, "01 AH Sat Rajab 1434"}, {1434, 8, 1, "01 AH Mon Sha\u02bbban 1434"}, {1434, 9, 1, "01 AH Tue Ramadan 1434"}, {1434, 10, 1, "01 AH Thu Shawwal 1434"}, {1434, 11, 1, "01 AH Sat Dhu\u02bbl-Qi\u02bbdah 1434"}, {1434, 12, 1, "01 AH Sun Dhu\u02bbl-Hijjah 1434"}, }; } // Test to verify the formatted dates @Test(dataProvider="patternMonthNames") public void test_ofPattern(int year, int month, int day, String expected) { DateTimeFormatter test = DateTimeFormatter.ofPattern("dd G E MMMM yyyy", Locale.US); assertEquals(test.format(HijrahDate.of(year, month, day)), expected); } // Data provider for localized dates @DataProvider(name="chronoDateTimes") Object[][] data_chronodatetimes() { return new Object[][] { {1432, 12, 29, "Safar 1, 1434 AH"}, {1433, 1, 30, "Safar 30, 1434 AH"}, {1434, 6, 30, "Rajab 30, 1435 AH"}, }; } // Test to verify the localized dates using ofLocalizedDate() method @Test(dataProvider="chronoDateTimes") public void test_formatterOfLocalizedDate(int year, int month, int day, String expected) { HijrahDate hd = HijrahChronology.INSTANCE.date(year, month, day); ChronoLocalDateTime<HijrahDate> hdt = hd.atTime(LocalTime.NOON); hdt = hdt.plus(1, ChronoUnit.YEARS); hdt = hdt.plus(1, ChronoUnit.MONTHS); hdt = hdt.plus(1, ChronoUnit.DAYS); hdt = hdt.plus(1, ChronoUnit.HOURS); hdt = hdt.plus(1, ChronoUnit.MINUTES); hdt = hdt.plus(1, ChronoUnit.SECONDS); DateTimeFormatter df = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG).withChronology(Chronology.of("Hijrah-umalqura")).withLocale(Locale.US); assertEquals(df.format(hdt), expected); } // Data provider to get the day of the week in a given date // The day of the week varies if the week starts with a saturday or sunday @DataProvider(name="dayOfWeek") Object[][] data_dayOfweek() { return new Object[][] { {HijrahDate.of(1434, 6, 24), 1, 7}, {HijrahDate.of(1432, 9, 3), 5, 4}, {HijrahDate.of(1334, 12, 29), 7, 6}, {HijrahDate.of(1354, 5, 24), 1, 7}, {HijrahDate.of(1465, 10, 2), 2, 1}, }; } // Test to get the day of the week based on a Saturday/Sunday as the first day of the week @Test(dataProvider="dayOfWeek") public void test_dayOfWeek(HijrahDate date, int satStart, int sunStart) { assertEquals(date.get(WeekFields.of(DayOfWeek.SATURDAY, 7).dayOfWeek()), satStart); assertEquals(date.get(WeekFields.of(DayOfWeek.SUNDAY, 7).dayOfWeek()), sunStart); } // Data sample to get the epoch days of a date instance @DataProvider(name="epochDays") Object[][] data_epochdays() { return new Object[][] { {1332, -20486}, {1334, -19777}, {1336, -19068}, {1432, 14950}, {1434, 15659}, {1534, 51096}, {1535, 51450}, }; } // Test to verify the number of epoch days of a date instance @Test(dataProvider="epochDays") public void test_epochDays(int y, long epoch) { HijrahDate date = HijrahDate.of(y, 1, 1); assertEquals(date.toEpochDay(), epoch); } // Data provider to verify whether a given hijrah year is a leap year or not @DataProvider(name="leapYears") Object[][] data_leapyears() { return new Object[][] { {1302, true}, {1305, false}, {1315, false}, {1534, false}, {1411, true}, {1429, false}, {1433, true}, {1443, true}, }; } // Test to verify whether a given hijrah year is a leap year or not @Test(dataProvider="leapYears") public void test_leapYears(int y, boolean leapyear) { HijrahDate date = HijrahDate.of(y, 1, 1); assertEquals(date.isLeapYear(), leapyear); } // Date samples to convert HijrahDate to LocalDate and vice versa @DataProvider(name="samples") Object[][] data_samples() { return new Object[][] { {HijrahChronology.INSTANCE.date(1319, 12, 30), LocalDate.of(1902, 4, 9)}, {HijrahChronology.INSTANCE.date(1320, 1, 1), LocalDate.of(1902, 4, 10)}, {HijrahChronology.INSTANCE.date(1321, 12, 30), LocalDate.of(1904, 3, 18)}, {HijrahChronology.INSTANCE.date(1433, 7, 29), LocalDate.of(2012, 6, 19)}, {HijrahChronology.INSTANCE.date(1434, 10, 12), LocalDate.of(2013, 8, 19)}, {HijrahChronology.INSTANCE.date(1500, 3, 3), LocalDate.of(2077, 1, 28)}, }; } // Test to get LocalDate instance from a given HijrahDate @Test(dataProvider="samples") public void test_toLocalDate(ChronoLocalDate hijrahDate, LocalDate iso) { assertEquals(LocalDate.from(hijrahDate), iso); } // Test to adjust HijrahDate with a given LocalDate @Test(dataProvider="samples") public void test_adjust_toLocalDate(ChronoLocalDate hijrahDate, LocalDate iso) { assertEquals(hijrahDate.with(iso), hijrahDate); } // Test to get a HijrahDate from a calendrical @Test(dataProvider="samples") public void test_fromCalendrical(ChronoLocalDate hijrahDate, LocalDate iso) { assertEquals(HijrahChronology.INSTANCE.date(iso), hijrahDate); } // Test to verify the day of week of a given HijrahDate and LocalDate @Test(dataProvider="samples") public void test_dayOfWeekEqualIsoDayOfWeek(ChronoLocalDate hijrahDate, LocalDate iso) { assertEquals(hijrahDate.get(ChronoField.DAY_OF_WEEK), iso.get(ChronoField.DAY_OF_WEEK), "Hijrah day of week should be same as ISO day of week"); } // Test to get the local date by applying the MIN adjustment with hijrah date @Test(dataProvider="samples") public void test_LocalDate_adjustToHijrahDate(ChronoLocalDate hijrahDate, LocalDate localDate) { LocalDate test = LocalDate.MIN.with(hijrahDate); assertEquals(test, localDate); } // Test to get the local date time by applying the MIN adjustment with hijrah date @Test(dataProvider="samples") public void test_LocalDateTime_adjustToHijrahDate(ChronoLocalDate hijrahDate, LocalDate localDate) { LocalDateTime test = LocalDateTime.MIN.with(hijrahDate); assertEquals(test, LocalDateTime.of(localDate, LocalTime.MIDNIGHT)); } // Sample dates for comparison @DataProvider(name="datesForComparison") Object[][] data_datesForComparison() { return new Object[][] { {HijrahChronology.INSTANCE.date(1434, 6, 26), LocalDate.of(2013, 5, 5), -1, 1}, {HijrahChronology.INSTANCE.date(1433, 4, 15), LocalDate.of(2012, 3, 15), 1, -1}, {HijrahChronology.INSTANCE.date(1432, 5, 21), LocalDate.of(2011, 4, 22), -1, 1}, {HijrahChronology.INSTANCE.date(1433, 7, 29), LocalDate.of(2012, 6, 2), -1, 1}, {HijrahChronology.INSTANCE.date(1434, 10, 12), LocalDate.of(2013, 8, 2), -1, 1}, }; } // Test to compare dates in both forward and reverse order @Test(dataProvider="datesForComparison") public void test_compareDates(HijrahDate hdate, LocalDate ldate, int result1, int result2) { assertEquals(ldate.compareTo(hdate), result1); assertEquals(hdate.compareTo(ldate), result2); } // Test to verify the values of various chrono fields for a given hijrah date instance @Test public void test_chronoFields() { ChronoLocalDate hdate = HijrahChronology.INSTANCE.date(1434, 6, 28); assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH), 3); assertEquals(hdate.get(ChronoField.ALIGNED_DAY_OF_WEEK_IN_YEAR), 7); assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_MONTH), 4); assertEquals(hdate.get(ChronoField.ALIGNED_WEEK_OF_YEAR), 25); assertEquals(hdate.get(ChronoField.ERA), 1); assertEquals(hdate.get(ChronoField.YEAR_OF_ERA), 1434); assertEquals(hdate.get(ChronoField.MONTH_OF_YEAR), 6); assertEquals(hdate.get(ChronoField.DAY_OF_MONTH), 28); assertEquals(hdate.get(ChronoField.DAY_OF_WEEK), 3); assertEquals(hdate.get(ChronoField.DAY_OF_YEAR), 175); } // Test to verify the returned hijrah date after adjusting the day of week as Saturday @Test public void test_adjustInto() { assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 6, 28)), HijrahDate.of(1434, 7, 1)); assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1432, 4, 13)), HijrahDate.of(1432, 4, 14)); assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1433, 11, 29)), HijrahDate.of(1433, 12, 4)); assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 5, 10)), HijrahDate.of(1434, 5, 11)); assertEquals(DayOfWeek.SATURDAY.adjustInto(HijrahDate.of(1434, 9, 11)), HijrahDate.of(1434, 9, 12)); } //----------------------------------------------------------------------- // zonedDateTime(TemporalAccessor) //----------------------------------------------------------------------- @DataProvider(name="zonedDateTime") Object[][] data_zonedDateTime() { return new Object[][] { {ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_RIYADH), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7, 1, 1), null}, {OffsetDateTime.of(2012, 2, 29, 2, 7, 1, 1, OFFSET_PTWO), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7, 1, 1), null}, {LocalDateTime.of(2012, 2, 29, 2, 7), null, null, DateTimeException.class}, {JapaneseDate.of(2012, 2, 29), null, null, DateTimeException.class}, {ThaiBuddhistDate.of(2012 + 543, 2, 29), null, null, DateTimeException.class}, {LocalDate.of(2012, 2, 29), null, null, DateTimeException.class}, {LocalTime.of(20, 30, 29, 0), null, null, DateTimeException.class}, }; } // Test to check the zoned date times @Test(dataProvider="zonedDateTime") public void test_zonedDateTime(TemporalAccessor accessor, HijrahDate expectedDate, LocalTime expectedTime, Class<?> expectedEx) { if (expectedEx == null) { ChronoZonedDateTime<HijrahDate> result = HijrahChronology.INSTANCE.zonedDateTime(accessor); assertEquals(result.toLocalDate(), expectedDate); assertEquals(HijrahDate.from(accessor), expectedDate); assertEquals(result.toLocalTime(), expectedTime); } else { try { ChronoZonedDateTime<HijrahDate> result = HijrahChronology.INSTANCE.zonedDateTime(accessor); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } } //----------------------------------------------------------------------- // zonedDateTime(Instant, ZoneId ) //----------------------------------------------------------------------- @Test public void test_Instant_zonedDateTime() { OffsetDateTime offsetDateTime = OffsetDateTime.of(2012, 2, 29, 2, 7, 1, 1, OFFSET_PTWO); ZonedDateTime zonedDateTime = ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_RIYADH); ChronoZonedDateTime<HijrahDate> result = HijrahChronology.INSTANCE.zonedDateTime(offsetDateTime.toInstant(), offsetDateTime.getOffset()); assertEquals(result.toLocalDate(), HijrahChronology.INSTANCE.date(1433, 4, 7)); assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1)); result = HijrahChronology.INSTANCE.zonedDateTime(zonedDateTime.toInstant(), zonedDateTime.getOffset()); assertEquals(result.toLocalDate(), HijrahChronology.INSTANCE.date(1433, 4, 7)); assertEquals(result.toLocalTime(), LocalTime.of(2, 7, 1, 1)); } //----------------------------------------------------------------------- // localDateTime() //----------------------------------------------------------------------- @DataProvider(name="localDateTime") Object[][] data_localDateTime() { return new Object[][] { {LocalDateTime.of(2012, 2, 29, 2, 7), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7), null}, {ZonedDateTime.of(2012, 2, 29, 2, 7, 1, 1, ZONE_RIYADH), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7, 1, 1), null}, {OffsetDateTime.of(2012, 2, 29, 2, 7, 1, 1, OFFSET_PTWO), HijrahChronology.INSTANCE.date(1433, 4, 7), LocalTime.of(2, 7, 1, 1), null}, {JapaneseDate.of(2012, 2, 29), null, null, DateTimeException.class}, {ThaiBuddhistDate.of(2012 + 543, 2, 29), null, null, DateTimeException.class}, {LocalDate.of(2012, 2, 29), null, null, DateTimeException.class}, {LocalTime.of(20, 30, 29, 0), null, null, DateTimeException.class}, }; } // Test to verify local date time values from various date instances defined in the localDateTime data provider @Test(dataProvider="localDateTime") public void test_localDateTime(TemporalAccessor accessor, HijrahDate expectedDate, LocalTime expectedTime, Class<?> expectedEx) { if (expectedEx == null) { ChronoLocalDateTime<HijrahDate> result = HijrahChronology.INSTANCE.localDateTime(accessor); assertEquals(result.toLocalDate(), expectedDate); assertEquals(HijrahDate.from(accessor), expectedDate); assertEquals(result.toLocalTime(), expectedTime); } else { try { ChronoLocalDateTime<HijrahDate> result = HijrahChronology.INSTANCE.localDateTime(accessor); fail(); } catch (Exception ex) { assertTrue(expectedEx.isInstance(ex)); } } } // Sample Hijrah & Minguo Dates @DataProvider(name="hijrahToMinguo") Object[][] data_hijrahToMinguo() { return new Object[][] { {HijrahDate.of(1350,5,15), MinguoDate.of(20,9,28)}, {HijrahDate.of(1434,5,1), MinguoDate.of(102,3,13)}, {HijrahDate.of(1436,1,1), MinguoDate.of(103,10,25)}, {HijrahDate.of(1500,6,12), MinguoDate.of(166,5,5)}, {HijrahDate.of(1550,3,11), MinguoDate.of(214,8,11)}, }; } // Test to verify the date conversion from Hijrah to Minguo chronology @Test(dataProvider="hijrahToMinguo") public void test_hijrahToMinguo(HijrahDate hijrah, MinguoDate minguo) { assertEquals(MinguoChronology.INSTANCE.date(hijrah), minguo); } // Sample Hijrah & Thai Dates @DataProvider(name="hijrahToThai") Object[][] data_hijrahToThai() { return new Object[][] { {HijrahDate.of(1350,5,15), ThaiBuddhistDate.of(2474,9,28)}, {HijrahDate.of(1434,5,1), ThaiBuddhistDate.of(2556,3,13)}, {HijrahDate.of(1436,1,1), ThaiBuddhistDate.of(2557,10,25)}, {HijrahDate.of(1500,6,12), ThaiBuddhistDate.of(2620,5,5)}, {HijrahDate.of(1550,3,11), ThaiBuddhistDate.of(2668,8,11)}, }; } // Test to verify the date conversion from Hijrah to Thai chronology @Test(dataProvider="hijrahToThai") public void test_hijrahToThai(HijrahDate hijrah, ThaiBuddhistDate thai) { assertEquals(ThaiBuddhistChronology.INSTANCE.date(hijrah), thai); } // Sample Hijrah & Japanese Dates @DataProvider(name="hijrahToJapanese") Object[][] data_hijrahToJapanese() { return new Object[][] { {HijrahDate.of(1350,5,15), "Japanese Showa 6-09-28"}, {HijrahDate.of(1434,5,1), "Japanese Heisei 25-03-13"}, {HijrahDate.of(1436,1,1), "Japanese Heisei 26-10-25"}, {HijrahDate.of(1500,6,12), "Japanese Heisei 89-05-05"}, {HijrahDate.of(1550,3,11), "Japanese Heisei 137-08-11"}, }; } // Test to verify the date conversion from Hijrah to Japanese chronology @Test(dataProvider="hijrahToJapanese") public void test_hijrahToJapanese(HijrahDate hijrah, String japanese) { assertEquals(JapaneseChronology.INSTANCE.date(hijrah).toString(), japanese); } }
apache/dubbo
37,911
dubbo-common/src/main/java/org/apache/dubbo/common/utils/PojoUtils.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.dubbo.common.utils; import org.apache.dubbo.common.config.ConfigurationUtils; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.rpc.model.ApplicationModel; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.TreeMap; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.function.Consumer; import java.util.function.Supplier; import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_REFLECTIVE_OPERATION_FAILED; import static org.apache.dubbo.common.utils.ClassUtils.isAssignableFrom; /** * PojoUtils. Travel object deeply, and convert complex type to simple type. * <p/> * Simple type below will be remained: * <ul> * <li> Primitive Type, also include <b>String</b>, <b>Number</b>(Integer, Long), <b>Date</b> * <li> Array of Primitive Type * <li> Collection, eg: List, Map, Set etc. * </ul> * <p/> * Other type will be covert to a map which contains the attributes and value pair of object. * <p> * TODO: exact PojoUtils to scope bean */ public class PojoUtils { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PojoUtils.class); private static final ConcurrentMap<String, Method> NAME_METHODS_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<Class<?>, ConcurrentMap<String, Field>> CLASS_FIELD_CACHE = new ConcurrentHashMap<>(); private static final ConcurrentMap<String, Object> CLASS_NOT_FOUND_CACHE = new ConcurrentHashMap<>(); private static final Object NOT_FOUND_VALUE = new Object(); private static final boolean GENERIC_WITH_CLZ = Boolean.parseBoolean(ConfigurationUtils.getProperty( ApplicationModel.defaultModel(), CommonConstants.GENERIC_WITH_CLZ_KEY, "true")); private static final List<Class<?>> CLASS_CAN_BE_STRING = Arrays.asList( Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Boolean.class, Character.class); public static Object[] generalize(Object[] objs) { Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = generalize(objs[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } public static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes) { if (objs.length != types.length || objs.length != gtypes.length) { throw new IllegalArgumentException("args.length != types.length"); } Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i], gtypes[i]); } return dests; } public static Object generalize(Object pojo) { return generalize(pojo, new IdentityHashMap<>()); } @SuppressWarnings("unchecked") private static Object generalize(Object pojo, Map<Object, Object> history) { if (pojo == null) { return null; } if (pojo instanceof Enum<?>) { return ((Enum<?>) pojo).name(); } if (pojo.getClass().isArray() && Enum.class.isAssignableFrom(pojo.getClass().getComponentType())) { int len = Array.getLength(pojo); String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = ((Enum<?>) Array.get(pojo, i)).name(); } return values; } if (ReflectUtils.isPrimitives(pojo.getClass())) { return pojo; } if (pojo instanceof LocalDate || pojo instanceof LocalDateTime || pojo instanceof LocalTime) { return pojo.toString(); } if (pojo instanceof Class) { return ((Class) pojo).getName(); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); if (pojo.getClass().isArray()) { int len = Array.getLength(pojo); Object[] dest = new Object[len]; history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); dest[i] = generalize(obj, history); } return dest; } if (pojo instanceof Collection<?>) { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = (pojo instanceof List<?>) ? new ArrayList<>(len) : new HashSet<>(len); history.put(pojo, dest); for (Object obj : src) { dest.add(generalize(obj, history)); } return dest; } if (pojo instanceof Map<?, ?>) { Map<Object, Object> src = (Map<Object, Object>) pojo; Map<Object, Object> dest = createMap(src); history.put(pojo, dest); for (Map.Entry<Object, Object> obj : src.entrySet()) { dest.put(generalize(obj.getKey(), history), generalize(obj.getValue(), history)); } return dest; } Map<String, Object> map = new HashMap<>(); history.put(pojo, map); if (GENERIC_WITH_CLZ) { map.put("class", pojo.getClass().getName()); } for (Method method : pojo.getClass().getMethods()) { if (ReflectUtils.isBeanPropertyReadMethod(method)) { ReflectUtils.makeAccessible(method); try { map.put( ReflectUtils.getPropertyNameFromBeanReadMethod(method), generalize(method.invoke(pojo), history)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } // public field for (Field field : pojo.getClass().getFields()) { if (ReflectUtils.isPublicInstanceField(field)) { try { Object fieldValue = field.get(pojo); if (history.containsKey(pojo)) { Object pojoGeneralizedValue = history.get(pojo); if (pojoGeneralizedValue instanceof Map && ((Map) pojoGeneralizedValue).containsKey(field.getName())) { continue; } } if (fieldValue != null) { map.put(field.getName(), generalize(fieldValue, history)); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } return map; } public static Object realize(Object pojo, Class<?> type) { return realize0(pojo, type, null, new IdentityHashMap<>()); } public static Object realize(Object pojo, Class<?> type, Type genericType) { return realize0(pojo, type, genericType, new IdentityHashMap<>()); } private static class PojoInvocationHandler implements InvocationHandler { private final Map<Object, Object> map; public PojoInvocationHandler(Map<Object, Object> map) { this.map = map; } @Override @SuppressWarnings("unchecked") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(map, args); } String methodName = method.getName(); Object value = null; if (methodName.length() > 3 && methodName.startsWith("get")) { value = map.get(methodName.substring(3, 4).toLowerCase() + methodName.substring(4)); } else if (methodName.length() > 2 && methodName.startsWith("is")) { value = map.get(methodName.substring(2, 3).toLowerCase() + methodName.substring(3)); } else { value = map.get(methodName.substring(0, 1).toLowerCase() + methodName.substring(1)); } if (value instanceof Map<?, ?> && !Map.class.isAssignableFrom(method.getReturnType())) { value = realize0(value, method.getReturnType(), null, new IdentityHashMap<>()); } return value; } } @SuppressWarnings("unchecked") private static Collection<Object> createCollection(Class<?> type, int len) { if (type.isAssignableFrom(ArrayList.class)) { return new ArrayList<>(len); } if (type.isAssignableFrom(HashSet.class)) { return new HashSet<>(len); } if (!type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { try { return (Collection<Object>) type.getDeclaredConstructor().newInstance(); } catch (Exception e) { // ignore } } return new ArrayList<>(); } private static Map createMap(Map src) { Class<? extends Map> cl = src.getClass(); Map result = null; if (HashMap.class == cl) { result = new HashMap(); } else if (Hashtable.class == cl) { result = new Hashtable(); } else if (IdentityHashMap.class == cl) { result = new IdentityHashMap(); } else if (LinkedHashMap.class == cl) { result = new LinkedHashMap(); } else if (Properties.class == cl) { result = new Properties(); } else if (TreeMap.class == cl) { result = new TreeMap(); } else if (WeakHashMap.class == cl) { return new WeakHashMap(); } else if (ConcurrentHashMap.class == cl) { result = new ConcurrentHashMap(); } else if (ConcurrentSkipListMap.class == cl) { result = new ConcurrentSkipListMap(); } else { try { result = cl.getDeclaredConstructor().newInstance(); } catch (Exception e) { /* ignore */ } if (result == null) { try { Constructor<?> constructor = cl.getConstructor(Map.class); result = (Map) constructor.newInstance(Collections.EMPTY_MAP); } catch (Exception e) { /* ignore */ } } } if (result == null) { result = new HashMap<>(); } return result; } @SuppressWarnings({"unchecked", "rawtypes"}) private static Object realize0(Object pojo, Class<?> type, Type genericType, final Map<Object, Object> history) { return realize1(pojo, type, genericType, new HashMap<>(8), history); } private static Object realize1( Object pojo, Class<?> type, Type genericType, final Map<String, Type> mapParent, final Map<Object, Object> history) { if (pojo == null) { return null; } if (type != null && type.isEnum() && pojo.getClass() == String.class) { return Enum.valueOf((Class<Enum>) type, (String) pojo); } if (ReflectUtils.isPrimitives(pojo.getClass()) && !(type != null && type.isArray() && type.getComponentType().isEnum() && pojo.getClass() == String[].class)) { return CompatibleTypeUtils.compatibleTypeConvert(pojo, type); } Object o = history.get(pojo); if (o != null) { return o; } history.put(pojo, pojo); Map<String, Type> mapGeneric = new HashMap<>(8); mapGeneric.putAll(mapParent); TypeVariable<? extends Class<?>>[] typeParameters = type.getTypeParameters(); if (genericType instanceof ParameterizedType && typeParameters.length > 0) { ParameterizedType parameterizedType = (ParameterizedType) genericType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); for (int i = 0; i < typeParameters.length; i++) { if (!(actualTypeArguments[i] instanceof TypeVariable)) { mapGeneric.put(typeParameters[i].getTypeName(), actualTypeArguments[i]); } } } if (pojo.getClass().isArray()) { if (Collection.class.isAssignableFrom(type)) { Class<?> ctype = pojo.getClass().getComponentType(); int len = Array.getLength(pojo); Collection dest = createCollection(type, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize1(obj, ctype, null, mapGeneric, history); dest.add(value); } return dest; } else { Class<?> ctype = (type != null && type.isArray() ? type.getComponentType() : pojo.getClass().getComponentType()); int len = Array.getLength(pojo); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); for (int i = 0; i < len; i++) { Object obj = Array.get(pojo, i); Object value = realize1(obj, ctype, null, mapGeneric, history); Array.set(dest, i, value); } return dest; } } if (pojo instanceof Collection<?>) { if (type.isArray()) { Class<?> ctype = type.getComponentType(); Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Object dest = Array.newInstance(ctype, len); history.put(pojo, dest); int i = 0; for (Object obj : src) { Object value = realize1(obj, ctype, null, mapGeneric, history); Array.set(dest, i, value); i++; } return dest; } else { Collection<Object> src = (Collection<Object>) pojo; int len = src.size(); Collection<Object> dest = createCollection(type, len); history.put(pojo, dest); for (Object obj : src) { Type keyType = getGenericClassByIndex(genericType, 0); Class<?> keyClazz = obj == null ? null : obj.getClass(); if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } Object value = realize1(obj, keyClazz, keyType, mapGeneric, history); dest.add(value); } return dest; } } if (pojo instanceof Map<?, ?> && type != null) { Object className = ((Map<Object, Object>) pojo).get("class"); if (className instanceof String) { if (!CLASS_NOT_FOUND_CACHE.containsKey(className)) { try { type = DefaultSerializeClassChecker.getInstance() .loadClass(ClassUtils.getClassLoader(), (String) className); } catch (ClassNotFoundException e) { CLASS_NOT_FOUND_CACHE.put((String) className, NOT_FOUND_VALUE); } } } // special logic for enum if (type.isEnum()) { Object name = ((Map<Object, Object>) pojo).get("name"); if (name != null) { if (!(name instanceof String)) { throw new IllegalArgumentException("`name` filed should be string!"); } else { return Enum.valueOf((Class<Enum>) type, (String) name); } } } Map<Object, Object> map; // when return type is not the subclass of return type from the signature and not an interface if (!type.isInterface() && !type.isAssignableFrom(pojo.getClass())) { try { map = (Map<Object, Object>) type.getDeclaredConstructor().newInstance(); Map<Object, Object> mapPojo = (Map<Object, Object>) pojo; map.putAll(mapPojo); if (GENERIC_WITH_CLZ) { map.remove("class"); } } catch (Exception e) { // ignore error map = (Map<Object, Object>) pojo; } } else { map = (Map<Object, Object>) pojo; } if (Map.class.isAssignableFrom(type) || type == Object.class) { final Map<Object, Object> result; // fix issue#5939 Type mapKeyType = getKeyTypeForMap(map.getClass()); Type typeKeyType = getGenericClassByIndex(genericType, 0); boolean typeMismatch = mapKeyType instanceof Class && typeKeyType instanceof Class && !typeKeyType.getTypeName().equals(mapKeyType.getTypeName()); if (typeMismatch) { result = createMap(new HashMap(0)); } else { result = createMap(map); } history.put(pojo, result); for (Map.Entry<Object, Object> entry : map.entrySet()) { Type keyType = getGenericClassByIndex(genericType, 0); Type valueType = getGenericClassByIndex(genericType, 1); Class<?> keyClazz; if (keyType instanceof Class) { keyClazz = (Class<?>) keyType; } else if (keyType instanceof ParameterizedType) { keyClazz = (Class<?>) ((ParameterizedType) keyType).getRawType(); } else { keyClazz = entry.getKey() == null ? null : entry.getKey().getClass(); } Class<?> valueClazz; if (valueType instanceof Class) { valueClazz = (Class<?>) valueType; } else if (valueType instanceof ParameterizedType) { valueClazz = (Class<?>) ((ParameterizedType) valueType).getRawType(); } else { valueClazz = entry.getValue() == null ? null : entry.getValue().getClass(); } Object key = keyClazz == null ? entry.getKey() : realize1(entry.getKey(), keyClazz, keyType, mapGeneric, history); Object value = valueClazz == null ? entry.getValue() : realize1(entry.getValue(), valueClazz, valueType, mapGeneric, history); result.put(key, value); } return result; } else if (type.isInterface()) { Object dest = Proxy.newProxyInstance( Thread.currentThread().getContextClassLoader(), new Class<?>[] {type}, new PojoInvocationHandler(map)); history.put(pojo, dest); return dest; } else { Object dest; if (Throwable.class.isAssignableFrom(type)) { Object message = map.get("message"); if (message instanceof String) { dest = newThrowableInstance(type, (String) message); } else { dest = newInstance(type); } } else { dest = newInstance(type); } history.put(pojo, dest); for (Map.Entry<Object, Object> entry : map.entrySet()) { Object key = entry.getKey(); if (key instanceof String) { String name = (String) key; Object value = entry.getValue(); if (value != null) { Method method = getSetterMethod(dest.getClass(), name, value.getClass()); Field field = getAndCacheField(dest.getClass(), name); if (method != null) { if (!method.isAccessible()) { method.setAccessible(true); } Type containType = Optional.ofNullable(field) .map(Field::getGenericType) .map(Type::getTypeName) .map(mapGeneric::get) .orElse(null); if (containType != null) { // is generic if (containType instanceof ParameterizedType) { value = realize1( value, (Class<?>) ((ParameterizedType) containType).getRawType(), containType, mapGeneric, history); } else if (containType instanceof Class) { value = realize1( value, (Class<?>) containType, containType, mapGeneric, history); } else { Type ptype = method.getGenericParameterTypes()[0]; value = realize1( value, method.getParameterTypes()[0], ptype, mapGeneric, history); } } else { Type ptype = method.getGenericParameterTypes()[0]; value = realize1(value, method.getParameterTypes()[0], ptype, mapGeneric, history); } try { method.invoke(dest, value); } catch (Exception e) { String exceptionDescription = "Failed to set pojo " + dest.getClass().getSimpleName() + " property " + name + " value " + value.getClass() + ", cause: " + e.getMessage(); logger.error(COMMON_REFLECTIVE_OPERATION_FAILED, "", "", exceptionDescription, e); throw new RuntimeException(exceptionDescription, e); } } else if (field != null) { value = realize1(value, field.getType(), field.getGenericType(), mapGeneric, history); try { field.set(dest, value); } catch (IllegalAccessException e) { throw new RuntimeException( "Failed to set field " + name + " of pojo " + dest.getClass().getName() + " : " + e.getMessage(), e); } } } } } return dest; } } return pojo; } /** * Get key type for {@link Map} directly implemented by {@code clazz}. * If {@code clazz} does not implement {@link Map} directly, return {@code null}. * * @param clazz {@link Class} * @return Return String.class for {@link com.alibaba.fastjson.JSONObject} */ private static Type getKeyTypeForMap(Class<?> clazz) { Type[] interfaces = clazz.getGenericInterfaces(); if (!ArrayUtils.isEmpty(interfaces)) { for (Type type : interfaces) { if (type instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) type; if ("java.util.Map".equals(t.getRawType().getTypeName())) { return t.getActualTypeArguments()[0]; } } } } return null; } /** * Get parameterized type * * @param genericType generic type * @param index index of the target parameterized type * @return Return Person.class for List<Person>, return Person.class for Map<String, Person> when index=0 */ private static Type getGenericClassByIndex(Type genericType, int index) { Type clazz = null; // find parameterized type if (genericType instanceof ParameterizedType) { ParameterizedType t = (ParameterizedType) genericType; Type[] types = t.getActualTypeArguments(); clazz = types[index]; } return clazz; } private static Object newThrowableInstance(Class<?> cls, String message) { try { Constructor<?> messagedConstructor = cls.getDeclaredConstructor(String.class); return messagedConstructor.newInstance(message); } catch (Exception t) { return newInstance(cls); } } private static Object newInstance(Class<?> cls) { try { return cls.getDeclaredConstructor().newInstance(); } catch (Exception t) { Constructor<?>[] constructors = cls.getDeclaredConstructors(); /* From Javadoc java.lang.Class#getDeclaredConstructors This method returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. This method returns an array of length 0, if this Class object represents an interface, a primitive type, an array class, or void. */ if (constructors.length == 0) { throw new RuntimeException("Illegal constructor: " + cls.getName()); } Throwable lastError = null; Arrays.sort(constructors, Comparator.comparingInt(a -> a.getParameterTypes().length)); for (Constructor<?> constructor : constructors) { try { constructor.setAccessible(true); Object[] parameters = Arrays.stream(constructor.getParameterTypes()) .map(PojoUtils::getDefaultValue) .toArray(); return constructor.newInstance(parameters); } catch (Exception e) { lastError = e; } } throw new RuntimeException(lastError.getMessage(), lastError); } } /** * return init value * * @param parameterType * @return */ private static Object getDefaultValue(Class<?> parameterType) { if ("char".equals(parameterType.getName())) { return Character.MIN_VALUE; } if ("boolean".equals(parameterType.getName())) { return false; } if ("byte".equals(parameterType.getName())) { return (byte) 0; } if ("short".equals(parameterType.getName())) { return (short) 0; } return parameterType.isPrimitive() ? 0 : null; } private static Method getSetterMethod(Class<?> cls, String property, Class<?> valueCls) { String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); Method method = NAME_METHODS_CACHE.get(cls.getName() + "." + name + "(" + valueCls.getName() + ")"); if (method == null) { try { method = cls.getMethod(name, valueCls); } catch (NoSuchMethodException e) { for (Method m : cls.getMethods()) { if (ReflectUtils.isBeanPropertyWriteMethod(m) && m.getName().equals(name)) { method = m; break; } } } if (method != null) { NAME_METHODS_CACHE.put(cls.getName() + "." + name + "(" + valueCls.getName() + ")", method); } } return method; } private static Field getAndCacheField(Class<?> cls, String fieldName) { Field result; if (CLASS_FIELD_CACHE.containsKey(cls) && CLASS_FIELD_CACHE.get(cls).containsKey(fieldName)) { return CLASS_FIELD_CACHE.get(cls).get(fieldName); } result = getField(cls, fieldName); if (result != null) { ConcurrentMap<String, Field> fields = ConcurrentHashMapUtils.computeIfAbsent(CLASS_FIELD_CACHE, cls, k -> new ConcurrentHashMap<>()); fields.putIfAbsent(fieldName, result); } return result; } private static Field getField(Class<?> cls, String fieldName) { Field result = null; for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { result = acls.getDeclaredField(fieldName); if (!Modifier.isPublic(result.getModifiers())) { result.setAccessible(true); } } catch (NoSuchFieldException e) { } } if (result == null && cls != null) { for (Field field : cls.getFields()) { if (fieldName.equals(field.getName()) && ReflectUtils.isPublicInstanceField(field)) { result = field; break; } } } return result; } public static boolean isPojo(Class<?> cls) { return !ReflectUtils.isPrimitives(cls) && !Collection.class.isAssignableFrom(cls) && !Map.class.isAssignableFrom(cls); } /** * Update the property if absent * * @param getterMethod the getter method * @param setterMethod the setter method * @param newValue the new value * @param <T> the value type * @since 2.7.8 */ public static <T> void updatePropertyIfAbsent(Supplier<T> getterMethod, Consumer<T> setterMethod, T newValue) { if (newValue != null && getterMethod.get() == null) { setterMethod.accept(newValue); } } /** * convert map to a specific class instance * * @param map map wait for convert * @param cls the specified class * @param <T> the type of {@code cls} * @return class instance declare in param {@code cls} * @throws ReflectiveOperationException if the instance creation is failed * @since 2.7.10 */ public static <T> T mapToPojo(Map<String, Object> map, Class<T> cls) throws ReflectiveOperationException { T instance = cls.getDeclaredConstructor().newInstance(); Map<String, Field> beanPropertyFields = ReflectUtils.getBeanPropertyFields(cls); for (Map.Entry<String, Field> entry : beanPropertyFields.entrySet()) { String name = entry.getKey(); Field field = entry.getValue(); Object mapObject = map.get(name); if (mapObject == null) { continue; } Type type = field.getGenericType(); Object fieldObject = getFieldObject(mapObject, type); field.set(instance, fieldObject); } return instance; } private static Object getFieldObject(Object mapObject, Type fieldType) throws ReflectiveOperationException { if (fieldType instanceof Class<?>) { return convertClassType(mapObject, (Class<?>) fieldType); } else if (fieldType instanceof ParameterizedType) { return convertParameterizedType(mapObject, (ParameterizedType) fieldType); } else if (fieldType instanceof GenericArrayType || fieldType instanceof TypeVariable<?> || fieldType instanceof WildcardType) { // ignore these type currently return null; } else { throw new IllegalArgumentException("Unrecognized Type: " + fieldType.toString()); } } @SuppressWarnings("unchecked") private static Object convertClassType(Object mapObject, Class<?> type) throws ReflectiveOperationException { if (type.isPrimitive() || isAssignableFrom(type, mapObject.getClass())) { return mapObject; } else if (Objects.equals(type, String.class) && CLASS_CAN_BE_STRING.contains(mapObject.getClass())) { // auto convert specified type to string return mapObject.toString(); } else if (mapObject instanceof Map) { return mapToPojo((Map<String, Object>) mapObject, type); } else { // type didn't match and mapObject is not another Map struct. // we just ignore this situation. return null; } } @SuppressWarnings("unchecked") private static Object convertParameterizedType(Object mapObject, ParameterizedType type) throws ReflectiveOperationException { Type rawType = type.getRawType(); if (!isAssignableFrom((Class<?>) rawType, mapObject.getClass())) { return null; } Type[] actualTypeArguments = type.getActualTypeArguments(); if (isAssignableFrom(Map.class, (Class<?>) rawType)) { Map<Object, Object> map = (Map<Object, Object>) mapObject.getClass().getDeclaredConstructor().newInstance(); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) mapObject).entrySet()) { Object key = getFieldObject(entry.getKey(), actualTypeArguments[0]); Object value = getFieldObject(entry.getValue(), actualTypeArguments[1]); map.put(key, value); } return map; } else if (isAssignableFrom(Collection.class, (Class<?>) rawType)) { Collection<Object> collection = (Collection<Object>) mapObject.getClass().getDeclaredConstructor().newInstance(); for (Object m : (Iterable<?>) mapObject) { Object ele = getFieldObject(m, actualTypeArguments[0]); collection.add(ele); } return collection; } else { // ignore other type currently return null; } } }
googleapis/google-cloud-java
37,606
java-cloudbuild/proto-google-cloud-build-v1/src/main/java/com/google/cloudbuild/v1/CreateWorkerPoolOperationMetadata.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/cloudbuild/v1/cloudbuild.proto // Protobuf Java Version: 3.25.8 package com.google.cloudbuild.v1; /** * * * <pre> * Metadata for the `CreateWorkerPool` operation. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.CreateWorkerPoolOperationMetadata} */ public final class CreateWorkerPoolOperationMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.cloudbuild.v1.CreateWorkerPoolOperationMetadata) CreateWorkerPoolOperationMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use CreateWorkerPoolOperationMetadata.newBuilder() to construct. private CreateWorkerPoolOperationMetadata( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateWorkerPoolOperationMetadata() { workerPool_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateWorkerPoolOperationMetadata(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_CreateWorkerPoolOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_CreateWorkerPoolOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.class, com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.Builder.class); } private int bitField0_; public static final int WORKER_POOL_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object workerPool_ = ""; /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The workerPool. */ @java.lang.Override public java.lang.String getWorkerPool() { java.lang.Object ref = workerPool_; 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(); workerPool_ = s; return s; } } /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for workerPool. */ @java.lang.Override public com.google.protobuf.ByteString getWorkerPoolBytes() { java.lang.Object ref = workerPool_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workerPool_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATE_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } public static final int COMPLETE_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp completeTime_; /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return Whether the completeTime field is set. */ @java.lang.Override public boolean hasCompleteTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return The completeTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCompleteTime() { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCompleteTimeOrBuilder() { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } 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(workerPool_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, workerPool_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getCompleteTime()); } 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(workerPool_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, workerPool_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCompleteTime()); } 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.cloudbuild.v1.CreateWorkerPoolOperationMetadata)) { return super.equals(obj); } com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata other = (com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata) obj; if (!getWorkerPool().equals(other.getWorkerPool())) return false; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasCompleteTime() != other.hasCompleteTime()) return false; if (hasCompleteTime()) { if (!getCompleteTime().equals(other.getCompleteTime())) 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) + WORKER_POOL_FIELD_NUMBER; hash = (53 * hash) + getWorkerPool().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasCompleteTime()) { hash = (37 * hash) + COMPLETE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCompleteTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata 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.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata 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.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata 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.cloudbuild.v1.CreateWorkerPoolOperationMetadata parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata 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.cloudbuild.v1.CreateWorkerPoolOperationMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Metadata for the `CreateWorkerPool` operation. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.CreateWorkerPoolOperationMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.cloudbuild.v1.CreateWorkerPoolOperationMetadata) com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_CreateWorkerPoolOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_CreateWorkerPoolOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.class, com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.Builder.class); } // Construct using com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCreateTimeFieldBuilder(); getCompleteTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; workerPool_ = ""; createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } completeTime_ = null; if (completeTimeBuilder_ != null) { completeTimeBuilder_.dispose(); completeTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_CreateWorkerPoolOperationMetadata_descriptor; } @java.lang.Override public com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata getDefaultInstanceForType() { return com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.getDefaultInstance(); } @java.lang.Override public com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata build() { com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata buildPartial() { com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata result = new com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.workerPool_ = workerPool_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.completeTime_ = completeTimeBuilder_ == null ? completeTime_ : completeTimeBuilder_.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.cloudbuild.v1.CreateWorkerPoolOperationMetadata) { return mergeFrom((com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata other) { if (other == com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata.getDefaultInstance()) return this; if (!other.getWorkerPool().isEmpty()) { workerPool_ = other.workerPool_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasCompleteTime()) { mergeCompleteTime(other.getCompleteTime()); } 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: { workerPool_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getCompleteTimeFieldBuilder().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 workerPool_ = ""; /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The workerPool. */ public java.lang.String getWorkerPool() { java.lang.Object ref = workerPool_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workerPool_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for workerPool. */ public com.google.protobuf.ByteString getWorkerPoolBytes() { java.lang.Object ref = workerPool_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workerPool_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The workerPool to set. * @return This builder for chaining. */ public Builder setWorkerPool(java.lang.String value) { if (value == null) { throw new NullPointerException(); } workerPool_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearWorkerPool() { workerPool_ = getDefaultInstance().getWorkerPool(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The resource name of the `WorkerPool` to create. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for workerPool to set. * @return This builder for chaining. */ public Builder setWorkerPoolBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); workerPool_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; } else { createTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && createTime_ != null && createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCreateTimeBuilder().mergeFrom(value); } else { createTime_ = value; } } else { createTimeBuilder_.mergeFrom(value); } if (createTime_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder clearCreateTime() { bitField0_ = (bitField0_ & ~0x00000002); createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.protobuf.Timestamp completeTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> completeTimeBuilder_; /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return Whether the completeTime field is set. */ public boolean hasCompleteTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return The completeTime. */ public com.google.protobuf.Timestamp getCompleteTime() { if (completeTimeBuilder_ == null) { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } else { return completeTimeBuilder_.getMessage(); } } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder setCompleteTime(com.google.protobuf.Timestamp value) { if (completeTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } completeTime_ = value; } else { completeTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder setCompleteTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (completeTimeBuilder_ == null) { completeTime_ = builderForValue.build(); } else { completeTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder mergeCompleteTime(com.google.protobuf.Timestamp value) { if (completeTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && completeTime_ != null && completeTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCompleteTimeBuilder().mergeFrom(value); } else { completeTime_ = value; } } else { completeTimeBuilder_.mergeFrom(value); } if (completeTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder clearCompleteTime() { bitField0_ = (bitField0_ & ~0x00000004); completeTime_ = null; if (completeTimeBuilder_ != null) { completeTimeBuilder_.dispose(); completeTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public com.google.protobuf.Timestamp.Builder getCompleteTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getCompleteTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public com.google.protobuf.TimestampOrBuilder getCompleteTimeOrBuilder() { if (completeTimeBuilder_ != null) { return completeTimeBuilder_.getMessageOrBuilder(); } else { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCompleteTimeFieldBuilder() { if (completeTimeBuilder_ == null) { completeTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCompleteTime(), getParentForChildren(), isClean()); completeTime_ = null; } return completeTimeBuilder_; } @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.cloudbuild.v1.CreateWorkerPoolOperationMetadata) } // @@protoc_insertion_point(class_scope:google.devtools.cloudbuild.v1.CreateWorkerPoolOperationMetadata) private static final com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata(); } public static com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateWorkerPoolOperationMetadata> PARSER = new com.google.protobuf.AbstractParser<CreateWorkerPoolOperationMetadata>() { @java.lang.Override public CreateWorkerPoolOperationMetadata 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<CreateWorkerPoolOperationMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateWorkerPoolOperationMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloudbuild.v1.CreateWorkerPoolOperationMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,651
java-deploy/proto-google-cloud-deploy-v1/src/main/java/com/google/cloud/deploy/v1/AdvanceRolloutRequest.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/cloud_deploy.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.deploy.v1; /** * * * <pre> * The request object used by `AdvanceRollout`. * </pre> * * Protobuf type {@code google.cloud.deploy.v1.AdvanceRolloutRequest} */ public final class AdvanceRolloutRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.deploy.v1.AdvanceRolloutRequest) AdvanceRolloutRequestOrBuilder { private static final long serialVersionUID = 0L; // Use AdvanceRolloutRequest.newBuilder() to construct. private AdvanceRolloutRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AdvanceRolloutRequest() { name_ = ""; phaseId_ = ""; overrideDeployPolicy_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new AdvanceRolloutRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_AdvanceRolloutRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_AdvanceRolloutRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.deploy.v1.AdvanceRolloutRequest.class, com.google.cloud.deploy.v1.AdvanceRolloutRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PHASE_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object phaseId_ = ""; /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The phaseId. */ @java.lang.Override public java.lang.String getPhaseId() { java.lang.Object ref = phaseId_; 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(); phaseId_ = s; return s; } } /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for phaseId. */ @java.lang.Override public com.google.protobuf.ByteString getPhaseIdBytes() { java.lang.Object ref = phaseId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); phaseId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OVERRIDE_DEPLOY_POLICY_FIELD_NUMBER = 3; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList overrideDeployPolicy_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @return A list containing the overrideDeployPolicy. */ public com.google.protobuf.ProtocolStringList getOverrideDeployPolicyList() { return overrideDeployPolicy_; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @return The count of overrideDeployPolicy. */ public int getOverrideDeployPolicyCount() { return overrideDeployPolicy_.size(); } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the element to return. * @return The overrideDeployPolicy at the given index. */ public java.lang.String getOverrideDeployPolicy(int index) { return overrideDeployPolicy_.get(index); } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the value to return. * @return The bytes of the overrideDeployPolicy at the given index. */ public com.google.protobuf.ByteString getOverrideDeployPolicyBytes(int index) { return overrideDeployPolicy_.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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(phaseId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, phaseId_); } for (int i = 0; i < overrideDeployPolicy_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString( output, 3, overrideDeployPolicy_.getRaw(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(phaseId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, phaseId_); } { int dataSize = 0; for (int i = 0; i < overrideDeployPolicy_.size(); i++) { dataSize += computeStringSizeNoTag(overrideDeployPolicy_.getRaw(i)); } size += dataSize; size += 1 * getOverrideDeployPolicyList().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.deploy.v1.AdvanceRolloutRequest)) { return super.equals(obj); } com.google.cloud.deploy.v1.AdvanceRolloutRequest other = (com.google.cloud.deploy.v1.AdvanceRolloutRequest) obj; if (!getName().equals(other.getName())) return false; if (!getPhaseId().equals(other.getPhaseId())) return false; if (!getOverrideDeployPolicyList().equals(other.getOverrideDeployPolicyList())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + PHASE_ID_FIELD_NUMBER; hash = (53 * hash) + getPhaseId().hashCode(); if (getOverrideDeployPolicyCount() > 0) { hash = (37 * hash) + OVERRIDE_DEPLOY_POLICY_FIELD_NUMBER; hash = (53 * hash) + getOverrideDeployPolicyList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest 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.AdvanceRolloutRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest 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.AdvanceRolloutRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest 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.AdvanceRolloutRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest 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.AdvanceRolloutRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest 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.AdvanceRolloutRequest 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.AdvanceRolloutRequest 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.AdvanceRolloutRequest 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 object used by `AdvanceRollout`. * </pre> * * Protobuf type {@code google.cloud.deploy.v1.AdvanceRolloutRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.deploy.v1.AdvanceRolloutRequest) com.google.cloud.deploy.v1.AdvanceRolloutRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_AdvanceRolloutRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_AdvanceRolloutRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.deploy.v1.AdvanceRolloutRequest.class, com.google.cloud.deploy.v1.AdvanceRolloutRequest.Builder.class); } // Construct using com.google.cloud.deploy.v1.AdvanceRolloutRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; phaseId_ = ""; overrideDeployPolicy_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.deploy.v1.CloudDeployProto .internal_static_google_cloud_deploy_v1_AdvanceRolloutRequest_descriptor; } @java.lang.Override public com.google.cloud.deploy.v1.AdvanceRolloutRequest getDefaultInstanceForType() { return com.google.cloud.deploy.v1.AdvanceRolloutRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.deploy.v1.AdvanceRolloutRequest build() { com.google.cloud.deploy.v1.AdvanceRolloutRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.deploy.v1.AdvanceRolloutRequest buildPartial() { com.google.cloud.deploy.v1.AdvanceRolloutRequest result = new com.google.cloud.deploy.v1.AdvanceRolloutRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.deploy.v1.AdvanceRolloutRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.phaseId_ = phaseId_; } if (((from_bitField0_ & 0x00000004) != 0)) { overrideDeployPolicy_.makeImmutable(); result.overrideDeployPolicy_ = overrideDeployPolicy_; } } @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.AdvanceRolloutRequest) { return mergeFrom((com.google.cloud.deploy.v1.AdvanceRolloutRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.deploy.v1.AdvanceRolloutRequest other) { if (other == com.google.cloud.deploy.v1.AdvanceRolloutRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPhaseId().isEmpty()) { phaseId_ = other.phaseId_; bitField0_ |= 0x00000002; onChanged(); } if (!other.overrideDeployPolicy_.isEmpty()) { if (overrideDeployPolicy_.isEmpty()) { overrideDeployPolicy_ = other.overrideDeployPolicy_; bitField0_ |= 0x00000004; } else { ensureOverrideDeployPolicyIsMutable(); overrideDeployPolicy_.addAll(other.overrideDeployPolicy_); } 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: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { phaseId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { java.lang.String s = input.readStringRequireUtf8(); ensureOverrideDeployPolicyIsMutable(); overrideDeployPolicy_.add(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 bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Name of the Rollout. Format is * `projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/releases/{release}/rollouts/{rollout}`. * </pre> * * <code> * string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object phaseId_ = ""; /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The phaseId. */ public java.lang.String getPhaseId() { java.lang.Object ref = phaseId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); phaseId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for phaseId. */ public com.google.protobuf.ByteString getPhaseIdBytes() { java.lang.Object ref = phaseId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); phaseId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The phaseId to set. * @return This builder for chaining. */ public Builder setPhaseId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } phaseId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearPhaseId() { phaseId_ = getDefaultInstance().getPhaseId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. The phase ID to advance the `Rollout` to. * </pre> * * <code>string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for phaseId to set. * @return This builder for chaining. */ public Builder setPhaseIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); phaseId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList overrideDeployPolicy_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureOverrideDeployPolicyIsMutable() { if (!overrideDeployPolicy_.isModifiable()) { overrideDeployPolicy_ = new com.google.protobuf.LazyStringArrayList(overrideDeployPolicy_); } bitField0_ |= 0x00000004; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @return A list containing the overrideDeployPolicy. */ public com.google.protobuf.ProtocolStringList getOverrideDeployPolicyList() { overrideDeployPolicy_.makeImmutable(); return overrideDeployPolicy_; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @return The count of overrideDeployPolicy. */ public int getOverrideDeployPolicyCount() { return overrideDeployPolicy_.size(); } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the element to return. * @return The overrideDeployPolicy at the given index. */ public java.lang.String getOverrideDeployPolicy(int index) { return overrideDeployPolicy_.get(index); } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the value to return. * @return The bytes of the overrideDeployPolicy at the given index. */ public com.google.protobuf.ByteString getOverrideDeployPolicyBytes(int index) { return overrideDeployPolicy_.getByteString(index); } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param index The index to set the value at. * @param value The overrideDeployPolicy to set. * @return This builder for chaining. */ public Builder setOverrideDeployPolicy(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureOverrideDeployPolicyIsMutable(); overrideDeployPolicy_.set(index, value); bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param value The overrideDeployPolicy to add. * @return This builder for chaining. */ public Builder addOverrideDeployPolicy(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureOverrideDeployPolicyIsMutable(); overrideDeployPolicy_.add(value); bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param values The overrideDeployPolicy to add. * @return This builder for chaining. */ public Builder addAllOverrideDeployPolicy(java.lang.Iterable<java.lang.String> values) { ensureOverrideDeployPolicyIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, overrideDeployPolicy_); bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearOverrideDeployPolicy() { overrideDeployPolicy_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); ; onChanged(); return this; } /** * * * <pre> * Optional. Deploy policies to override. Format is * `projects/{project}/locations/{location}/deployPolicies/{deployPolicy}`. * </pre> * * <code> * repeated string override_deploy_policy = 3 [(.google.api.field_behavior) = OPTIONAL, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes of the overrideDeployPolicy to add. * @return This builder for chaining. */ public Builder addOverrideDeployPolicyBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureOverrideDeployPolicyIsMutable(); overrideDeployPolicy_.add(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.deploy.v1.AdvanceRolloutRequest) } // @@protoc_insertion_point(class_scope:google.cloud.deploy.v1.AdvanceRolloutRequest) private static final com.google.cloud.deploy.v1.AdvanceRolloutRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.deploy.v1.AdvanceRolloutRequest(); } public static com.google.cloud.deploy.v1.AdvanceRolloutRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AdvanceRolloutRequest> PARSER = new com.google.protobuf.AbstractParser<AdvanceRolloutRequest>() { @java.lang.Override public AdvanceRolloutRequest 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<AdvanceRolloutRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AdvanceRolloutRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.deploy.v1.AdvanceRolloutRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,604
java-shopping-merchant-accounts/proto-google-shopping-merchant-accounts-v1beta/src/main/java/com/google/shopping/merchant/accounts/v1beta/ListProgramsResponse.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/shopping/merchant/accounts/v1beta/programs.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.accounts.v1beta; /** * * * <pre> * Response message for the ListPrograms method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1beta.ListProgramsResponse} */ public final class ListProgramsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.accounts.v1beta.ListProgramsResponse) ListProgramsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListProgramsResponse.newBuilder() to construct. private ListProgramsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListProgramsResponse() { programs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListProgramsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1beta.ProgramsProto .internal_static_google_shopping_merchant_accounts_v1beta_ListProgramsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1beta.ProgramsProto .internal_static_google_shopping_merchant_accounts_v1beta_ListProgramsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.class, com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.Builder.class); } public static final int PROGRAMS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.shopping.merchant.accounts.v1beta.Program> programs_; /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ @java.lang.Override public java.util.List<com.google.shopping.merchant.accounts.v1beta.Program> getProgramsList() { return programs_; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder> getProgramsOrBuilderList() { return programs_; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ @java.lang.Override public int getProgramsCount() { return programs_.size(); } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1beta.Program getPrograms(int index) { return programs_.get(index); } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ @java.lang.Override public com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder getProgramsOrBuilder( int index) { return programs_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < programs_.size(); i++) { output.writeMessage(1, programs_.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 < programs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, programs_.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.shopping.merchant.accounts.v1beta.ListProgramsResponse)) { return super.equals(obj); } com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse other = (com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse) obj; if (!getProgramsList().equals(other.getProgramsList())) 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 (getProgramsCount() > 0) { hash = (37 * hash) + PROGRAMS_FIELD_NUMBER; hash = (53 * hash) + getProgramsList().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.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse 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.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse 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.shopping.merchant.accounts.v1beta.ListProgramsResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse 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.shopping.merchant.accounts.v1beta.ListProgramsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse 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.shopping.merchant.accounts.v1beta.ListProgramsResponse 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 ListPrograms method. * </pre> * * Protobuf type {@code google.shopping.merchant.accounts.v1beta.ListProgramsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.accounts.v1beta.ListProgramsResponse) com.google.shopping.merchant.accounts.v1beta.ListProgramsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.accounts.v1beta.ProgramsProto .internal_static_google_shopping_merchant_accounts_v1beta_ListProgramsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.accounts.v1beta.ProgramsProto .internal_static_google_shopping_merchant_accounts_v1beta_ListProgramsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.class, com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.Builder.class); } // Construct using // com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (programsBuilder_ == null) { programs_ = java.util.Collections.emptyList(); } else { programs_ = null; programsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.accounts.v1beta.ProgramsProto .internal_static_google_shopping_merchant_accounts_v1beta_ListProgramsResponse_descriptor; } @java.lang.Override public com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse getDefaultInstanceForType() { return com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse build() { com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse buildPartial() { com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse result = new com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse result) { if (programsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { programs_ = java.util.Collections.unmodifiableList(programs_); bitField0_ = (bitField0_ & ~0x00000001); } result.programs_ = programs_; } else { result.programs_ = programsBuilder_.build(); } } private void buildPartial0( com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse 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.shopping.merchant.accounts.v1beta.ListProgramsResponse) { return mergeFrom((com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse other) { if (other == com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse.getDefaultInstance()) return this; if (programsBuilder_ == null) { if (!other.programs_.isEmpty()) { if (programs_.isEmpty()) { programs_ = other.programs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProgramsIsMutable(); programs_.addAll(other.programs_); } onChanged(); } } else { if (!other.programs_.isEmpty()) { if (programsBuilder_.isEmpty()) { programsBuilder_.dispose(); programsBuilder_ = null; programs_ = other.programs_; bitField0_ = (bitField0_ & ~0x00000001); programsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getProgramsFieldBuilder() : null; } else { programsBuilder_.addAllMessages(other.programs_); } } } 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.shopping.merchant.accounts.v1beta.Program m = input.readMessage( com.google.shopping.merchant.accounts.v1beta.Program.parser(), extensionRegistry); if (programsBuilder_ == null) { ensureProgramsIsMutable(); programs_.add(m); } else { programsBuilder_.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.shopping.merchant.accounts.v1beta.Program> programs_ = java.util.Collections.emptyList(); private void ensureProgramsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { programs_ = new java.util.ArrayList<com.google.shopping.merchant.accounts.v1beta.Program>( programs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1beta.Program, com.google.shopping.merchant.accounts.v1beta.Program.Builder, com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder> programsBuilder_; /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public java.util.List<com.google.shopping.merchant.accounts.v1beta.Program> getProgramsList() { if (programsBuilder_ == null) { return java.util.Collections.unmodifiableList(programs_); } else { return programsBuilder_.getMessageList(); } } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public int getProgramsCount() { if (programsBuilder_ == null) { return programs_.size(); } else { return programsBuilder_.getCount(); } } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public com.google.shopping.merchant.accounts.v1beta.Program getPrograms(int index) { if (programsBuilder_ == null) { return programs_.get(index); } else { return programsBuilder_.getMessage(index); } } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder setPrograms( int index, com.google.shopping.merchant.accounts.v1beta.Program value) { if (programsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProgramsIsMutable(); programs_.set(index, value); onChanged(); } else { programsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder setPrograms( int index, com.google.shopping.merchant.accounts.v1beta.Program.Builder builderForValue) { if (programsBuilder_ == null) { ensureProgramsIsMutable(); programs_.set(index, builderForValue.build()); onChanged(); } else { programsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder addPrograms(com.google.shopping.merchant.accounts.v1beta.Program value) { if (programsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProgramsIsMutable(); programs_.add(value); onChanged(); } else { programsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder addPrograms( int index, com.google.shopping.merchant.accounts.v1beta.Program value) { if (programsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProgramsIsMutable(); programs_.add(index, value); onChanged(); } else { programsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder addPrograms( com.google.shopping.merchant.accounts.v1beta.Program.Builder builderForValue) { if (programsBuilder_ == null) { ensureProgramsIsMutable(); programs_.add(builderForValue.build()); onChanged(); } else { programsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder addPrograms( int index, com.google.shopping.merchant.accounts.v1beta.Program.Builder builderForValue) { if (programsBuilder_ == null) { ensureProgramsIsMutable(); programs_.add(index, builderForValue.build()); onChanged(); } else { programsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder addAllPrograms( java.lang.Iterable<? extends com.google.shopping.merchant.accounts.v1beta.Program> values) { if (programsBuilder_ == null) { ensureProgramsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, programs_); onChanged(); } else { programsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder clearPrograms() { if (programsBuilder_ == null) { programs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { programsBuilder_.clear(); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public Builder removePrograms(int index) { if (programsBuilder_ == null) { ensureProgramsIsMutable(); programs_.remove(index); onChanged(); } else { programsBuilder_.remove(index); } return this; } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public com.google.shopping.merchant.accounts.v1beta.Program.Builder getProgramsBuilder( int index) { return getProgramsFieldBuilder().getBuilder(index); } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder getProgramsOrBuilder( int index) { if (programsBuilder_ == null) { return programs_.get(index); } else { return programsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public java.util.List<? extends com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder> getProgramsOrBuilderList() { if (programsBuilder_ != null) { return programsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(programs_); } } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public com.google.shopping.merchant.accounts.v1beta.Program.Builder addProgramsBuilder() { return getProgramsFieldBuilder() .addBuilder(com.google.shopping.merchant.accounts.v1beta.Program.getDefaultInstance()); } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public com.google.shopping.merchant.accounts.v1beta.Program.Builder addProgramsBuilder( int index) { return getProgramsFieldBuilder() .addBuilder( index, com.google.shopping.merchant.accounts.v1beta.Program.getDefaultInstance()); } /** * * * <pre> * The programs for the given account. * </pre> * * <code>repeated .google.shopping.merchant.accounts.v1beta.Program programs = 1;</code> */ public java.util.List<com.google.shopping.merchant.accounts.v1beta.Program.Builder> getProgramsBuilderList() { return getProgramsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1beta.Program, com.google.shopping.merchant.accounts.v1beta.Program.Builder, com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder> getProgramsFieldBuilder() { if (programsBuilder_ == null) { programsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.shopping.merchant.accounts.v1beta.Program, com.google.shopping.merchant.accounts.v1beta.Program.Builder, com.google.shopping.merchant.accounts.v1beta.ProgramOrBuilder>( programs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); programs_ = null; } return programsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token that can be sent as `page_token` to retrieve the next page. If this * field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.shopping.merchant.accounts.v1beta.ListProgramsResponse) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.accounts.v1beta.ListProgramsResponse) private static final com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse(); } public static com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListProgramsResponse> PARSER = new com.google.protobuf.AbstractParser<ListProgramsResponse>() { @java.lang.Override public ListProgramsResponse 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<ListProgramsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListProgramsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.accounts.v1beta.ListProgramsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,634
java-video-stitcher/proto-google-cloud-video-stitcher-v1/src/main/java/com/google/cloud/video/stitcher/v1/ListVodAdTagDetailsResponse.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/video/stitcher/v1/video_stitcher_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.video.stitcher.v1; /** * * * <pre> * Response message for VideoStitcherService.listVodAdTagDetails. * </pre> * * Protobuf type {@code google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse} */ public final class ListVodAdTagDetailsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse) ListVodAdTagDetailsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListVodAdTagDetailsResponse.newBuilder() to construct. private ListVodAdTagDetailsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListVodAdTagDetailsResponse() { vodAdTagDetails_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListVodAdTagDetailsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_ListVodAdTagDetailsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_ListVodAdTagDetailsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.class, com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.Builder.class); } public static final int VOD_AD_TAG_DETAILS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.video.stitcher.v1.VodAdTagDetail> vodAdTagDetails_; /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.video.stitcher.v1.VodAdTagDetail> getVodAdTagDetailsList() { return vodAdTagDetails_; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder> getVodAdTagDetailsOrBuilderList() { return vodAdTagDetails_; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ @java.lang.Override public int getVodAdTagDetailsCount() { return vodAdTagDetails_.size(); } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ @java.lang.Override public com.google.cloud.video.stitcher.v1.VodAdTagDetail getVodAdTagDetails(int index) { return vodAdTagDetails_.get(index); } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ @java.lang.Override public com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder getVodAdTagDetailsOrBuilder( int index) { return vodAdTagDetails_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The pagination 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 pagination 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 < vodAdTagDetails_.size(); i++) { output.writeMessage(1, vodAdTagDetails_.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 < vodAdTagDetails_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, vodAdTagDetails_.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.video.stitcher.v1.ListVodAdTagDetailsResponse)) { return super.equals(obj); } com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse other = (com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse) obj; if (!getVodAdTagDetailsList().equals(other.getVodAdTagDetailsList())) 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 (getVodAdTagDetailsCount() > 0) { hash = (37 * hash) + VOD_AD_TAG_DETAILS_FIELD_NUMBER; hash = (53 * hash) + getVodAdTagDetailsList().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.video.stitcher.v1.ListVodAdTagDetailsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse 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.video.stitcher.v1.ListVodAdTagDetailsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse 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.video.stitcher.v1.ListVodAdTagDetailsResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse 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.video.stitcher.v1.ListVodAdTagDetailsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse 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.video.stitcher.v1.ListVodAdTagDetailsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse 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.video.stitcher.v1.ListVodAdTagDetailsResponse 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 VideoStitcherService.listVodAdTagDetails. * </pre> * * Protobuf type {@code google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse) com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_ListVodAdTagDetailsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_ListVodAdTagDetailsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.class, com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.Builder.class); } // Construct using com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (vodAdTagDetailsBuilder_ == null) { vodAdTagDetails_ = java.util.Collections.emptyList(); } else { vodAdTagDetails_ = null; vodAdTagDetailsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.video.stitcher.v1.VideoStitcherServiceProto .internal_static_google_cloud_video_stitcher_v1_ListVodAdTagDetailsResponse_descriptor; } @java.lang.Override public com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse getDefaultInstanceForType() { return com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse build() { com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse buildPartial() { com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse result = new com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse result) { if (vodAdTagDetailsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { vodAdTagDetails_ = java.util.Collections.unmodifiableList(vodAdTagDetails_); bitField0_ = (bitField0_ & ~0x00000001); } result.vodAdTagDetails_ = vodAdTagDetails_; } else { result.vodAdTagDetails_ = vodAdTagDetailsBuilder_.build(); } } private void buildPartial0( com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse 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.video.stitcher.v1.ListVodAdTagDetailsResponse) { return mergeFrom((com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse other) { if (other == com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse.getDefaultInstance()) return this; if (vodAdTagDetailsBuilder_ == null) { if (!other.vodAdTagDetails_.isEmpty()) { if (vodAdTagDetails_.isEmpty()) { vodAdTagDetails_ = other.vodAdTagDetails_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.addAll(other.vodAdTagDetails_); } onChanged(); } } else { if (!other.vodAdTagDetails_.isEmpty()) { if (vodAdTagDetailsBuilder_.isEmpty()) { vodAdTagDetailsBuilder_.dispose(); vodAdTagDetailsBuilder_ = null; vodAdTagDetails_ = other.vodAdTagDetails_; bitField0_ = (bitField0_ & ~0x00000001); vodAdTagDetailsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getVodAdTagDetailsFieldBuilder() : null; } else { vodAdTagDetailsBuilder_.addAllMessages(other.vodAdTagDetails_); } } } 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.video.stitcher.v1.VodAdTagDetail m = input.readMessage( com.google.cloud.video.stitcher.v1.VodAdTagDetail.parser(), extensionRegistry); if (vodAdTagDetailsBuilder_ == null) { ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.add(m); } else { vodAdTagDetailsBuilder_.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.video.stitcher.v1.VodAdTagDetail> vodAdTagDetails_ = java.util.Collections.emptyList(); private void ensureVodAdTagDetailsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { vodAdTagDetails_ = new java.util.ArrayList<com.google.cloud.video.stitcher.v1.VodAdTagDetail>( vodAdTagDetails_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.video.stitcher.v1.VodAdTagDetail, com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder, com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder> vodAdTagDetailsBuilder_; /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public java.util.List<com.google.cloud.video.stitcher.v1.VodAdTagDetail> getVodAdTagDetailsList() { if (vodAdTagDetailsBuilder_ == null) { return java.util.Collections.unmodifiableList(vodAdTagDetails_); } else { return vodAdTagDetailsBuilder_.getMessageList(); } } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public int getVodAdTagDetailsCount() { if (vodAdTagDetailsBuilder_ == null) { return vodAdTagDetails_.size(); } else { return vodAdTagDetailsBuilder_.getCount(); } } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public com.google.cloud.video.stitcher.v1.VodAdTagDetail getVodAdTagDetails(int index) { if (vodAdTagDetailsBuilder_ == null) { return vodAdTagDetails_.get(index); } else { return vodAdTagDetailsBuilder_.getMessage(index); } } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder setVodAdTagDetails( int index, com.google.cloud.video.stitcher.v1.VodAdTagDetail value) { if (vodAdTagDetailsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.set(index, value); onChanged(); } else { vodAdTagDetailsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder setVodAdTagDetails( int index, com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder builderForValue) { if (vodAdTagDetailsBuilder_ == null) { ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.set(index, builderForValue.build()); onChanged(); } else { vodAdTagDetailsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder addVodAdTagDetails(com.google.cloud.video.stitcher.v1.VodAdTagDetail value) { if (vodAdTagDetailsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.add(value); onChanged(); } else { vodAdTagDetailsBuilder_.addMessage(value); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder addVodAdTagDetails( int index, com.google.cloud.video.stitcher.v1.VodAdTagDetail value) { if (vodAdTagDetailsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.add(index, value); onChanged(); } else { vodAdTagDetailsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder addVodAdTagDetails( com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder builderForValue) { if (vodAdTagDetailsBuilder_ == null) { ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.add(builderForValue.build()); onChanged(); } else { vodAdTagDetailsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder addVodAdTagDetails( int index, com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder builderForValue) { if (vodAdTagDetailsBuilder_ == null) { ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.add(index, builderForValue.build()); onChanged(); } else { vodAdTagDetailsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder addAllVodAdTagDetails( java.lang.Iterable<? extends com.google.cloud.video.stitcher.v1.VodAdTagDetail> values) { if (vodAdTagDetailsBuilder_ == null) { ensureVodAdTagDetailsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, vodAdTagDetails_); onChanged(); } else { vodAdTagDetailsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder clearVodAdTagDetails() { if (vodAdTagDetailsBuilder_ == null) { vodAdTagDetails_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { vodAdTagDetailsBuilder_.clear(); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public Builder removeVodAdTagDetails(int index) { if (vodAdTagDetailsBuilder_ == null) { ensureVodAdTagDetailsIsMutable(); vodAdTagDetails_.remove(index); onChanged(); } else { vodAdTagDetailsBuilder_.remove(index); } return this; } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder getVodAdTagDetailsBuilder( int index) { return getVodAdTagDetailsFieldBuilder().getBuilder(index); } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder getVodAdTagDetailsOrBuilder( int index) { if (vodAdTagDetailsBuilder_ == null) { return vodAdTagDetails_.get(index); } else { return vodAdTagDetailsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public java.util.List<? extends com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder> getVodAdTagDetailsOrBuilderList() { if (vodAdTagDetailsBuilder_ != null) { return vodAdTagDetailsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(vodAdTagDetails_); } } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder addVodAdTagDetailsBuilder() { return getVodAdTagDetailsFieldBuilder() .addBuilder(com.google.cloud.video.stitcher.v1.VodAdTagDetail.getDefaultInstance()); } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder addVodAdTagDetailsBuilder( int index) { return getVodAdTagDetailsFieldBuilder() .addBuilder( index, com.google.cloud.video.stitcher.v1.VodAdTagDetail.getDefaultInstance()); } /** * * * <pre> * A List of ad tag details. * </pre> * * <code>repeated .google.cloud.video.stitcher.v1.VodAdTagDetail vod_ad_tag_details = 1;</code> */ public java.util.List<com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder> getVodAdTagDetailsBuilderList() { return getVodAdTagDetailsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.video.stitcher.v1.VodAdTagDetail, com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder, com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder> getVodAdTagDetailsFieldBuilder() { if (vodAdTagDetailsBuilder_ == null) { vodAdTagDetailsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.video.stitcher.v1.VodAdTagDetail, com.google.cloud.video.stitcher.v1.VodAdTagDetail.Builder, com.google.cloud.video.stitcher.v1.VodAdTagDetailOrBuilder>( vodAdTagDetails_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); vodAdTagDetails_ = null; } return vodAdTagDetailsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The pagination 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 pagination 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 pagination 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 pagination 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 pagination 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.video.stitcher.v1.ListVodAdTagDetailsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse) private static final com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse(); } public static com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListVodAdTagDetailsResponse> PARSER = new com.google.protobuf.AbstractParser<ListVodAdTagDetailsResponse>() { @java.lang.Override public ListVodAdTagDetailsResponse 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<ListVodAdTagDetailsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListVodAdTagDetailsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.video.stitcher.v1.ListVodAdTagDetailsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,643
java-dataform/proto-google-cloud-dataform-v1beta1/src/main/java/com/google/cloud/dataform/v1beta1/FetchRepositoryHistoryResponse.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/dataform/v1beta1/dataform.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataform.v1beta1; /** * * * <pre> * `FetchRepositoryHistory` response message. * </pre> * * Protobuf type {@code google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse} */ public final class FetchRepositoryHistoryResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse) FetchRepositoryHistoryResponseOrBuilder { private static final long serialVersionUID = 0L; // Use FetchRepositoryHistoryResponse.newBuilder() to construct. private FetchRepositoryHistoryResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FetchRepositoryHistoryResponse() { commits_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FetchRepositoryHistoryResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataform.v1beta1.DataformProto .internal_static_google_cloud_dataform_v1beta1_FetchRepositoryHistoryResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataform.v1beta1.DataformProto .internal_static_google_cloud_dataform_v1beta1_FetchRepositoryHistoryResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.class, com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.Builder.class); } public static final int COMMITS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dataform.v1beta1.CommitLogEntry> commits_; /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dataform.v1beta1.CommitLogEntry> getCommitsList() { return commits_; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder> getCommitsOrBuilderList() { return commits_; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ @java.lang.Override public int getCommitsCount() { return commits_.size(); } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ @java.lang.Override public com.google.cloud.dataform.v1beta1.CommitLogEntry getCommits(int index) { return commits_.get(index); } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ @java.lang.Override public com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder getCommitsOrBuilder(int index) { return commits_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < commits_.size(); i++) { output.writeMessage(1, commits_.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 < commits_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, commits_.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.dataform.v1beta1.FetchRepositoryHistoryResponse)) { return super.equals(obj); } com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse other = (com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse) obj; if (!getCommitsList().equals(other.getCommitsList())) 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 (getCommitsCount() > 0) { hash = (37 * hash) + COMMITS_FIELD_NUMBER; hash = (53 * hash) + getCommitsList().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.dataform.v1beta1.FetchRepositoryHistoryResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse 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.dataform.v1beta1.FetchRepositoryHistoryResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse 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.dataform.v1beta1.FetchRepositoryHistoryResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse 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.dataform.v1beta1.FetchRepositoryHistoryResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse 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.dataform.v1beta1.FetchRepositoryHistoryResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse 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.dataform.v1beta1.FetchRepositoryHistoryResponse 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> * `FetchRepositoryHistory` response message. * </pre> * * Protobuf type {@code google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse) com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataform.v1beta1.DataformProto .internal_static_google_cloud_dataform_v1beta1_FetchRepositoryHistoryResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataform.v1beta1.DataformProto .internal_static_google_cloud_dataform_v1beta1_FetchRepositoryHistoryResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.class, com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.Builder.class); } // Construct using com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (commitsBuilder_ == null) { commits_ = java.util.Collections.emptyList(); } else { commits_ = null; commitsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataform.v1beta1.DataformProto .internal_static_google_cloud_dataform_v1beta1_FetchRepositoryHistoryResponse_descriptor; } @java.lang.Override public com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse getDefaultInstanceForType() { return com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse build() { com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse buildPartial() { com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse result = new com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse result) { if (commitsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { commits_ = java.util.Collections.unmodifiableList(commits_); bitField0_ = (bitField0_ & ~0x00000001); } result.commits_ = commits_; } else { result.commits_ = commitsBuilder_.build(); } } private void buildPartial0( com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse 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.dataform.v1beta1.FetchRepositoryHistoryResponse) { return mergeFrom((com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse other) { if (other == com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse.getDefaultInstance()) return this; if (commitsBuilder_ == null) { if (!other.commits_.isEmpty()) { if (commits_.isEmpty()) { commits_ = other.commits_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureCommitsIsMutable(); commits_.addAll(other.commits_); } onChanged(); } } else { if (!other.commits_.isEmpty()) { if (commitsBuilder_.isEmpty()) { commitsBuilder_.dispose(); commitsBuilder_ = null; commits_ = other.commits_; bitField0_ = (bitField0_ & ~0x00000001); commitsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCommitsFieldBuilder() : null; } else { commitsBuilder_.addAllMessages(other.commits_); } } } 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.dataform.v1beta1.CommitLogEntry m = input.readMessage( com.google.cloud.dataform.v1beta1.CommitLogEntry.parser(), extensionRegistry); if (commitsBuilder_ == null) { ensureCommitsIsMutable(); commits_.add(m); } else { commitsBuilder_.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.dataform.v1beta1.CommitLogEntry> commits_ = java.util.Collections.emptyList(); private void ensureCommitsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { commits_ = new java.util.ArrayList<com.google.cloud.dataform.v1beta1.CommitLogEntry>(commits_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataform.v1beta1.CommitLogEntry, com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder, com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder> commitsBuilder_; /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public java.util.List<com.google.cloud.dataform.v1beta1.CommitLogEntry> getCommitsList() { if (commitsBuilder_ == null) { return java.util.Collections.unmodifiableList(commits_); } else { return commitsBuilder_.getMessageList(); } } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public int getCommitsCount() { if (commitsBuilder_ == null) { return commits_.size(); } else { return commitsBuilder_.getCount(); } } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public com.google.cloud.dataform.v1beta1.CommitLogEntry getCommits(int index) { if (commitsBuilder_ == null) { return commits_.get(index); } else { return commitsBuilder_.getMessage(index); } } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder setCommits(int index, com.google.cloud.dataform.v1beta1.CommitLogEntry value) { if (commitsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCommitsIsMutable(); commits_.set(index, value); onChanged(); } else { commitsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder setCommits( int index, com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder builderForValue) { if (commitsBuilder_ == null) { ensureCommitsIsMutable(); commits_.set(index, builderForValue.build()); onChanged(); } else { commitsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder addCommits(com.google.cloud.dataform.v1beta1.CommitLogEntry value) { if (commitsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCommitsIsMutable(); commits_.add(value); onChanged(); } else { commitsBuilder_.addMessage(value); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder addCommits(int index, com.google.cloud.dataform.v1beta1.CommitLogEntry value) { if (commitsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCommitsIsMutable(); commits_.add(index, value); onChanged(); } else { commitsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder addCommits( com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder builderForValue) { if (commitsBuilder_ == null) { ensureCommitsIsMutable(); commits_.add(builderForValue.build()); onChanged(); } else { commitsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder addCommits( int index, com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder builderForValue) { if (commitsBuilder_ == null) { ensureCommitsIsMutable(); commits_.add(index, builderForValue.build()); onChanged(); } else { commitsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder addAllCommits( java.lang.Iterable<? extends com.google.cloud.dataform.v1beta1.CommitLogEntry> values) { if (commitsBuilder_ == null) { ensureCommitsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, commits_); onChanged(); } else { commitsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder clearCommits() { if (commitsBuilder_ == null) { commits_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { commitsBuilder_.clear(); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public Builder removeCommits(int index) { if (commitsBuilder_ == null) { ensureCommitsIsMutable(); commits_.remove(index); onChanged(); } else { commitsBuilder_.remove(index); } return this; } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder getCommitsBuilder(int index) { return getCommitsFieldBuilder().getBuilder(index); } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder getCommitsOrBuilder( int index) { if (commitsBuilder_ == null) { return commits_.get(index); } else { return commitsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public java.util.List<? extends com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder> getCommitsOrBuilderList() { if (commitsBuilder_ != null) { return commitsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(commits_); } } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder addCommitsBuilder() { return getCommitsFieldBuilder() .addBuilder(com.google.cloud.dataform.v1beta1.CommitLogEntry.getDefaultInstance()); } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder addCommitsBuilder(int index) { return getCommitsFieldBuilder() .addBuilder(index, com.google.cloud.dataform.v1beta1.CommitLogEntry.getDefaultInstance()); } /** * * * <pre> * A list of commit logs, ordered by 'git log' default order. * </pre> * * <code>repeated .google.cloud.dataform.v1beta1.CommitLogEntry commits = 1;</code> */ public java.util.List<com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder> getCommitsBuilderList() { return getCommitsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataform.v1beta1.CommitLogEntry, com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder, com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder> getCommitsFieldBuilder() { if (commitsBuilder_ == null) { commitsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataform.v1beta1.CommitLogEntry, com.google.cloud.dataform.v1beta1.CommitLogEntry.Builder, com.google.cloud.dataform.v1beta1.CommitLogEntryOrBuilder>( commits_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); commits_ = null; } return commitsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * If this field is omitted, there are no subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse) private static final com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse(); } public static com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FetchRepositoryHistoryResponse> PARSER = new com.google.protobuf.AbstractParser<FetchRepositoryHistoryResponse>() { @java.lang.Override public FetchRepositoryHistoryResponse 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<FetchRepositoryHistoryResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FetchRepositoryHistoryResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataform.v1beta1.FetchRepositoryHistoryResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,689
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GlobalSetLabelsRequest.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.GlobalSetLabelsRequest} */ public final class GlobalSetLabelsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GlobalSetLabelsRequest) GlobalSetLabelsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use GlobalSetLabelsRequest.newBuilder() to construct. private GlobalSetLabelsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GlobalSetLabelsRequest() { labelFingerprint_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new GlobalSetLabelsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GlobalSetLabelsRequest_descriptor; } @SuppressWarnings({"rawtypes"}) @java.lang.Override protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 500195327: return internalGetLabels(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GlobalSetLabelsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GlobalSetLabelsRequest.class, com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder.class); } private int bitField0_; public static final int LABEL_FINGERPRINT_FIELD_NUMBER = 178124825; @SuppressWarnings("serial") private volatile java.lang.Object labelFingerprint_ = ""; /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return Whether the labelFingerprint field is set. */ @java.lang.Override public boolean hasLabelFingerprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return The labelFingerprint. */ @java.lang.Override public java.lang.String getLabelFingerprint() { java.lang.Object ref = labelFingerprint_; 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(); labelFingerprint_ = s; return s; } } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return The bytes for labelFingerprint. */ @java.lang.Override public com.google.protobuf.ByteString getLabelFingerprintBytes() { java.lang.Object ref = labelFingerprint_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); labelFingerprint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int LABELS_FIELD_NUMBER = 500195327; private static final class LabelsDefaultEntryHolder { static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry = com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance( com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GlobalSetLabelsRequest_LabelsEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, ""); } @SuppressWarnings("serial") private com.google.protobuf.MapField<java.lang.String, java.lang.String> labels_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetLabels() { if (labels_ == null) { return com.google.protobuf.MapField.emptyMapField(LabelsDefaultEntryHolder.defaultEntry); } return labels_; } public int getLabelsCount() { return internalGetLabels().getMap().size(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public boolean containsLabels(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetLabels().getMap().containsKey(key); } /** Use {@link #getLabelsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getLabels() { return getLabelsMap(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getLabelsMap() { return internalGetLabels().getMap(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public /* nullable */ java.lang.String getLabelsOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public java.lang.String getLabelsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 178124825, labelFingerprint_); } com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( output, internalGetLabels(), LabelsDefaultEntryHolder.defaultEntry, 500195327); 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(178124825, labelFingerprint_); } for (java.util.Map.Entry<java.lang.String, java.lang.String> entry : internalGetLabels().getMap().entrySet()) { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> labels__ = LabelsDefaultEntryHolder.defaultEntry .newBuilderForType() .setKey(entry.getKey()) .setValue(entry.getValue()) .build(); size += com.google.protobuf.CodedOutputStream.computeMessageSize(500195327, labels__); } 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.GlobalSetLabelsRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.GlobalSetLabelsRequest other = (com.google.cloud.compute.v1.GlobalSetLabelsRequest) obj; if (hasLabelFingerprint() != other.hasLabelFingerprint()) return false; if (hasLabelFingerprint()) { if (!getLabelFingerprint().equals(other.getLabelFingerprint())) return false; } if (!internalGetLabels().equals(other.internalGetLabels())) 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 (hasLabelFingerprint()) { hash = (37 * hash) + LABEL_FINGERPRINT_FIELD_NUMBER; hash = (53 * hash) + getLabelFingerprint().hashCode(); } if (!internalGetLabels().getMap().isEmpty()) { hash = (37 * hash) + LABELS_FIELD_NUMBER; hash = (53 * hash) + internalGetLabels().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest 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.GlobalSetLabelsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GlobalSetLabelsRequest) com.google.cloud.compute.v1.GlobalSetLabelsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GlobalSetLabelsRequest_descriptor; } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection( int number) { switch (number) { case 500195327: return internalGetLabels(); default: throw new RuntimeException("Invalid map field number: " + number); } } @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection( int number) { switch (number) { case 500195327: return internalGetMutableLabels(); default: throw new RuntimeException("Invalid map field number: " + number); } } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_GlobalSetLabelsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.GlobalSetLabelsRequest.class, com.google.cloud.compute.v1.GlobalSetLabelsRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.GlobalSetLabelsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; labelFingerprint_ = ""; internalGetMutableLabels().clear(); 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_GlobalSetLabelsRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.GlobalSetLabelsRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.GlobalSetLabelsRequest build() { com.google.cloud.compute.v1.GlobalSetLabelsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.GlobalSetLabelsRequest buildPartial() { com.google.cloud.compute.v1.GlobalSetLabelsRequest result = new com.google.cloud.compute.v1.GlobalSetLabelsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.GlobalSetLabelsRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.labelFingerprint_ = labelFingerprint_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.labels_ = internalGetLabels(); result.labels_.makeImmutable(); } 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.GlobalSetLabelsRequest) { return mergeFrom((com.google.cloud.compute.v1.GlobalSetLabelsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.GlobalSetLabelsRequest other) { if (other == com.google.cloud.compute.v1.GlobalSetLabelsRequest.getDefaultInstance()) return this; if (other.hasLabelFingerprint()) { labelFingerprint_ = other.labelFingerprint_; bitField0_ |= 0x00000001; onChanged(); } internalGetMutableLabels().mergeFrom(other.internalGetLabels()); bitField0_ |= 0x00000002; 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 1424998602: { labelFingerprint_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 1424998602 case -293404678: { com.google.protobuf.MapEntry<java.lang.String, java.lang.String> labels__ = input.readMessage( LabelsDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); internalGetMutableLabels() .getMutableMap() .put(labels__.getKey(), labels__.getValue()); bitField0_ |= 0x00000002; break; } // case -293404678 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 labelFingerprint_ = ""; /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return Whether the labelFingerprint field is set. */ public boolean hasLabelFingerprint() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return The labelFingerprint. */ public java.lang.String getLabelFingerprint() { java.lang.Object ref = labelFingerprint_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); labelFingerprint_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return The bytes for labelFingerprint. */ public com.google.protobuf.ByteString getLabelFingerprintBytes() { java.lang.Object ref = labelFingerprint_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); labelFingerprint_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @param value The labelFingerprint to set. * @return This builder for chaining. */ public Builder setLabelFingerprint(java.lang.String value) { if (value == null) { throw new NullPointerException(); } labelFingerprint_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @return This builder for chaining. */ public Builder clearLabelFingerprint() { labelFingerprint_ = getDefaultInstance().getLabelFingerprint(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The fingerprint of the previous set of labels for this resource, used to detect conflicts. The fingerprint is initially generated by Compute Engine and changes after every request to modify or update labels. You must always provide an up-to-date fingerprint hash when updating or changing labels, otherwise the request will fail with error 412 conditionNotMet. Make a get() request to the resource to get the latest fingerprint. * </pre> * * <code>optional string label_fingerprint = 178124825;</code> * * @param value The bytes for labelFingerprint to set. * @return This builder for chaining. */ public Builder setLabelFingerprintBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); labelFingerprint_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> labels_; private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetLabels() { if (labels_ == null) { return com.google.protobuf.MapField.emptyMapField(LabelsDefaultEntryHolder.defaultEntry); } return labels_; } private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMutableLabels() { if (labels_ == null) { labels_ = com.google.protobuf.MapField.newMapField(LabelsDefaultEntryHolder.defaultEntry); } if (!labels_.isMutable()) { labels_ = labels_.copy(); } bitField0_ |= 0x00000002; onChanged(); return labels_; } public int getLabelsCount() { return internalGetLabels().getMap().size(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public boolean containsLabels(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } return internalGetLabels().getMap().containsKey(key); } /** Use {@link #getLabelsMap()} instead. */ @java.lang.Override @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getLabels() { return getLabelsMap(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public java.util.Map<java.lang.String, java.lang.String> getLabelsMap() { return internalGetLabels().getMap(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public /* nullable */ java.lang.String getLabelsOrDefault( java.lang.String key, /* nullable */ java.lang.String defaultValue) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); return map.containsKey(key) ? map.get(key) : defaultValue; } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ @java.lang.Override public java.lang.String getLabelsOrThrow(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } java.util.Map<java.lang.String, java.lang.String> map = internalGetLabels().getMap(); if (!map.containsKey(key)) { throw new java.lang.IllegalArgumentException(); } return map.get(key); } public Builder clearLabels() { bitField0_ = (bitField0_ & ~0x00000002); internalGetMutableLabels().getMutableMap().clear(); return this; } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ public Builder removeLabels(java.lang.String key) { if (key == null) { throw new NullPointerException("map key"); } internalGetMutableLabels().getMutableMap().remove(key); return this; } /** Use alternate mutation accessors instead. */ @java.lang.Deprecated public java.util.Map<java.lang.String, java.lang.String> getMutableLabels() { bitField0_ |= 0x00000002; return internalGetMutableLabels().getMutableMap(); } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ public Builder putLabels(java.lang.String key, java.lang.String value) { if (key == null) { throw new NullPointerException("map key"); } if (value == null) { throw new NullPointerException("map value"); } internalGetMutableLabels().getMutableMap().put(key, value); bitField0_ |= 0x00000002; return this; } /** * * * <pre> * A list of labels to apply for this resource. Each label must comply with the requirements for labels. For example, "webserver-frontend": "images". A label value can also be empty (e.g. "my-label": ""). * </pre> * * <code>map&lt;string, string&gt; labels = 500195327;</code> */ public Builder putAllLabels(java.util.Map<java.lang.String, java.lang.String> values) { internalGetMutableLabels().getMutableMap().putAll(values); bitField0_ |= 0x00000002; 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.GlobalSetLabelsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GlobalSetLabelsRequest) private static final com.google.cloud.compute.v1.GlobalSetLabelsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GlobalSetLabelsRequest(); } public static com.google.cloud.compute.v1.GlobalSetLabelsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GlobalSetLabelsRequest> PARSER = new com.google.protobuf.AbstractParser<GlobalSetLabelsRequest>() { @java.lang.Override public GlobalSetLabelsRequest 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<GlobalSetLabelsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GlobalSetLabelsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.GlobalSetLabelsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hadoop
37,739
hadoop-tools/hadoop-azure-datalake/src/main/java/org/apache/hadoop/fs/adl/AdlFileSystem.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.hadoop.fs.adl; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; import org.apache.hadoop.classification.VisibleForTesting; import org.apache.hadoop.util.Preconditions; import com.microsoft.azure.datalake.store.ADLStoreClient; import com.microsoft.azure.datalake.store.ADLStoreOptions; import com.microsoft.azure.datalake.store.DirectoryEntry; import com.microsoft.azure.datalake.store.IfExists; import com.microsoft.azure.datalake.store.LatencyTracker; import com.microsoft.azure.datalake.store.UserGroupRepresentation; import com.microsoft.azure.datalake.store.oauth2.AccessTokenProvider; import com.microsoft.azure.datalake.store.oauth2.ClientCredsTokenProvider; import com.microsoft.azure.datalake.store.oauth2.DeviceCodeTokenProvider; import com.microsoft.azure.datalake.store.oauth2.MsiTokenProvider; import com.microsoft.azure.datalake.store.oauth2.RefreshTokenBasedTokenProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonPathCapabilities; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.ContentSummary.Builder; import org.apache.hadoop.fs.CreateFlag; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.InvalidPathException; import org.apache.hadoop.fs.Options; import org.apache.hadoop.fs.Options.Rename; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.adl.oauth2.AzureADTokenProvider; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclStatus; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.ProviderUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Progressable; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.util.VersionInfo; import static org.apache.hadoop.fs.adl.AdlConfKeys.*; import static org.apache.hadoop.fs.impl.PathCapabilitiesSupport.validatePathCapabilityArgs; /** * A FileSystem to access Azure Data Lake Store. */ @InterfaceAudience.Public @InterfaceStability.Evolving public class AdlFileSystem extends FileSystem { private static final Logger LOG = LoggerFactory.getLogger(AdlFileSystem.class); public static final String SCHEME = "adl"; static final int DEFAULT_PORT = 443; private URI uri; private String userName; private boolean overrideOwner; private ADLStoreClient adlClient; private Path workingDirectory; private boolean aclBitStatus; private UserGroupRepresentation oidOrUpn; // retained for tests private AccessTokenProvider tokenProvider; private AzureADTokenProvider azureTokenProvider; static { AdlConfKeys.addDeprecatedKeys(); } @Override public String getScheme() { return SCHEME; } public URI getUri() { return uri; } @Override public int getDefaultPort() { return DEFAULT_PORT; } @Override public boolean supportsSymlinks() { return false; } /** * Called after a new FileSystem instance is constructed. * * @param storeUri a uri whose authority section names the host, port, * etc. for this FileSystem * @param originalConf the configuration to use for the FS. The account- * specific options are patched over the base ones * before any use is made of the config. */ @Override public void initialize(URI storeUri, Configuration originalConf) throws IOException { String hostname = storeUri.getHost(); String accountName = getAccountNameFromFQDN(hostname); Configuration conf = propagateAccountOptions(originalConf, accountName); super.initialize(storeUri, conf); this.setConf(conf); this.uri = URI .create(storeUri.getScheme() + "://" + storeUri.getAuthority()); try { userName = UserGroupInformation.getCurrentUser().getShortUserName(); } catch (IOException e) { userName = "hadoop"; LOG.warn("Got exception when getting Hadoop user name." + " Set the user name to '" + userName + "'.", e); } this.setWorkingDirectory(getHomeDirectory()); overrideOwner = getConf().getBoolean(ADL_DEBUG_OVERRIDE_LOCAL_USER_AS_OWNER, ADL_DEBUG_SET_LOCAL_USER_AS_OWNER_DEFAULT); aclBitStatus = conf.getBoolean(ADL_SUPPORT_ACL_BIT_IN_FSPERMISSION, ADL_SUPPORT_ACL_BIT_IN_FSPERMISSION_DEFAULT); String accountFQDN = null; String mountPoint = null; if (!hostname.contains(".") && !hostname.equalsIgnoreCase( "localhost")) { // this is a symbolic name. Resolve it. String hostNameProperty = "dfs.adls." + hostname + ".hostname"; String mountPointProperty = "dfs.adls." + hostname + ".mountpoint"; accountFQDN = getNonEmptyVal(conf, hostNameProperty); mountPoint = getNonEmptyVal(conf, mountPointProperty); } else { accountFQDN = hostname; } if (storeUri.getPort() > 0) { accountFQDN = accountFQDN + ":" + storeUri.getPort(); } adlClient = ADLStoreClient .createClient(accountFQDN, getAccessTokenProvider(conf)); ADLStoreOptions options = new ADLStoreOptions(); options.enableThrowingRemoteExceptions(); if (getTransportScheme().equalsIgnoreCase(INSECURE_TRANSPORT_SCHEME)) { options.setInsecureTransport(); } if (mountPoint != null) { options.setFilePathPrefix(mountPoint); } String clusterName = conf.get(ADL_EVENTS_TRACKING_CLUSTERNAME, "UNKNOWN"); String clusterType = conf.get(ADL_EVENTS_TRACKING_CLUSTERTYPE, "UNKNOWN"); String clientVersion = ADL_HADOOP_CLIENT_NAME + (StringUtils .isEmpty(VersionInfo.getVersion().trim()) ? ADL_HADOOP_CLIENT_VERSION.trim() : VersionInfo.getVersion().trim()); options.setUserAgentSuffix(clientVersion + "/" + VersionInfo.getVersion().trim() + "/" + clusterName + "/" + clusterType); int timeout = conf.getInt(ADL_HTTP_TIMEOUT, -1); if (timeout > 0) { // only set timeout if specified in config. Otherwise use SDK default options.setDefaultTimeout(timeout); } else { LOG.info("No valid ADL SDK timeout configured: using SDK default."); } String sslChannelMode = conf.get(ADL_SSL_CHANNEL_MODE, "Default"); options.setSSLChannelMode(sslChannelMode); adlClient.setOptions(options); boolean trackLatency = conf .getBoolean(LATENCY_TRACKER_KEY, LATENCY_TRACKER_DEFAULT); if (!trackLatency) { LatencyTracker.disable(); } boolean enableUPN = conf.getBoolean(ADL_ENABLEUPN_FOR_OWNERGROUP_KEY, ADL_ENABLEUPN_FOR_OWNERGROUP_DEFAULT); oidOrUpn = enableUPN ? UserGroupRepresentation.UPN : UserGroupRepresentation.OID; } /** * This method is provided for convenience for derived classes to define * custom {@link AzureADTokenProvider} instance. * * In order to ensure secure hadoop infrastructure and user context for which * respective {@link AdlFileSystem} instance is initialized, * Loading {@link AzureADTokenProvider} is not sufficient. * * The order of loading {@link AzureADTokenProvider} is to first invoke * {@link #getCustomAccessTokenProvider(Configuration)}, If method return null * which means no implementation provided by derived classes, then * configuration object is loaded to retrieve token configuration as specified * is documentation. * * Custom token management takes the higher precedence during initialization. * * @param conf Configuration object * @return null if the no custom {@link AzureADTokenProvider} token management * is specified. * @throws IOException if failed to initialize token provider. */ protected synchronized AzureADTokenProvider getCustomAccessTokenProvider( Configuration conf) throws IOException { String className = getNonEmptyVal(conf, AZURE_AD_TOKEN_PROVIDER_CLASS_KEY); Class<? extends AzureADTokenProvider> azureADTokenProviderClass = conf.getClass(AZURE_AD_TOKEN_PROVIDER_CLASS_KEY, null, AzureADTokenProvider.class); if (azureADTokenProviderClass == null) { throw new IllegalArgumentException( "Configuration " + className + " " + "not defined/accessible."); } azureTokenProvider = ReflectionUtils .newInstance(azureADTokenProviderClass, conf); if (azureTokenProvider == null) { throw new IllegalArgumentException("Failed to initialize " + className); } azureTokenProvider.initialize(conf); return azureTokenProvider; } private AccessTokenProvider getAccessTokenProvider(Configuration config) throws IOException { Configuration conf = ProviderUtils.excludeIncompatibleCredentialProviders( config, AdlFileSystem.class); TokenProviderType type = conf.getEnum( AdlConfKeys.AZURE_AD_TOKEN_PROVIDER_TYPE_KEY, AdlConfKeys.AZURE_AD_TOKEN_PROVIDER_TYPE_DEFAULT); switch (type) { case RefreshToken: tokenProvider = getConfRefreshTokenBasedTokenProvider(conf); break; case ClientCredential: tokenProvider = getConfCredentialBasedTokenProvider(conf); break; case MSI: tokenProvider = getMsiBasedTokenProvider(conf); break; case DeviceCode: tokenProvider = getDeviceCodeTokenProvider(conf); break; case Custom: default: AzureADTokenProvider azureADTokenProvider = getCustomAccessTokenProvider( conf); tokenProvider = new SdkTokenProviderAdapter(azureADTokenProvider); break; } return tokenProvider; } private AccessTokenProvider getConfCredentialBasedTokenProvider( Configuration conf) throws IOException { String clientId = getPasswordString(conf, AZURE_AD_CLIENT_ID_KEY); String refreshUrl = getPasswordString(conf, AZURE_AD_REFRESH_URL_KEY); String clientSecret = getPasswordString(conf, AZURE_AD_CLIENT_SECRET_KEY); return new ClientCredsTokenProvider(refreshUrl, clientId, clientSecret); } private AccessTokenProvider getConfRefreshTokenBasedTokenProvider( Configuration conf) throws IOException { String clientId = getPasswordString(conf, AZURE_AD_CLIENT_ID_KEY); String refreshToken = getPasswordString(conf, AZURE_AD_REFRESH_TOKEN_KEY); return new RefreshTokenBasedTokenProvider(clientId, refreshToken); } private AccessTokenProvider getMsiBasedTokenProvider( Configuration conf) throws IOException { return new MsiTokenProvider(conf.getInt(MSI_PORT, -1)); } private AccessTokenProvider getDeviceCodeTokenProvider( Configuration conf) throws IOException { String clientAppId = getNonEmptyVal(conf, DEVICE_CODE_CLIENT_APP_ID); return new DeviceCodeTokenProvider(clientAppId); } @VisibleForTesting AccessTokenProvider getTokenProvider() { return tokenProvider; } @VisibleForTesting AzureADTokenProvider getAzureTokenProvider() { return azureTokenProvider; } @VisibleForTesting public ADLStoreClient getAdlClient() { return adlClient; } /** * Constructing home directory locally is fine as long as Hadoop * local user name and ADL user name relationship story is not fully baked * yet. * * @return Hadoop local user home directory. */ @Override public Path getHomeDirectory() { return makeQualified(new Path("/user/" + userName)); } /** * Create call semantic is handled differently in case of ADL. Create * semantics is translated to Create/Append * semantics. * 1. No dedicated connection to server. * 2. Buffering is locally done, Once buffer is full or flush is invoked on * the by the caller. All the pending * data is pushed to ADL as APPEND operation code. * 3. On close - Additional call is send to server to close the stream, and * release lock from the stream. * * Necessity of Create/Append semantics is * 1. ADL backend server does not allow idle connection for longer duration * . In case of slow writer scenario, * observed connection timeout/Connection reset causing occasional job * failures. * 2. Performance boost to jobs which are slow writer, avoided network latency * 3. ADL equally better performing with multiple of 4MB chunk as append * calls. * * @param f File path * @param permission Access permission for the newly created file * @param overwrite Remove existing file and recreate new one if true * otherwise throw error if file exist * @param bufferSize Buffer size, ADL backend does not honour * @param replication Replication count, ADL backend does not honour * @param blockSize Block size, ADL backend does not honour * @param progress Progress indicator * @return FSDataOutputStream OutputStream on which application can push * stream of bytes * @throws IOException when system error, internal server error or user error */ @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { statistics.incrementWriteOps(1); IfExists overwriteRule = overwrite ? IfExists.OVERWRITE : IfExists.FAIL; return new FSDataOutputStream(new AdlFsOutputStream(adlClient .createFile(toRelativeFilePath(f), overwriteRule, Integer.toOctalString(applyUMask(permission).toShort()), true), getConf()), this.statistics); } /** * Opens an FSDataOutputStream at the indicated Path with write-progress * reporting. Same as create(), except fails if parent directory doesn't * already exist. * * @param f the file name to open * @param permission Access permission for the newly created file * @param flags {@link CreateFlag}s to use for this stream. * @param bufferSize the size of the buffer to be used. ADL backend does * not honour * @param replication required block replication for the file. ADL backend * does not honour * @param blockSize Block size, ADL backend does not honour * @param progress Progress indicator * @throws IOException when system error, internal server error or user error * @see #setPermission(Path, FsPermission) * @deprecated API only for 0.20-append */ @Override public FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { statistics.incrementWriteOps(1); IfExists overwriteRule = IfExists.FAIL; for (CreateFlag flag : flags) { if (flag == CreateFlag.OVERWRITE) { overwriteRule = IfExists.OVERWRITE; break; } } return new FSDataOutputStream(new AdlFsOutputStream(adlClient .createFile(toRelativeFilePath(f), overwriteRule, Integer.toOctalString(applyUMask(permission).toShort()), false), getConf()), this.statistics); } /** * Append to an existing file (optional operation). * * @param f the existing file to be appended. * @param bufferSize the size of the buffer to be used. ADL backend does * not honour * @param progress Progress indicator * @throws IOException when system error, internal server error or user error */ @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { statistics.incrementWriteOps(1); return new FSDataOutputStream( new AdlFsOutputStream(adlClient.getAppendStream(toRelativeFilePath(f)), getConf()), this.statistics); } /** * Azure data lake does not support user configuration for data replication * hence not leaving system to query on * azure data lake. * * Stub implementation * * @param p Not honoured * @param replication Not honoured * @return True hard coded since ADL file system does not support * replication configuration * @throws IOException No exception would not thrown in this case however * aligning with parent api definition. */ @Override public boolean setReplication(final Path p, final short replication) throws IOException { statistics.incrementWriteOps(1); return true; } /** * Open call semantic is handled differently in case of ADL. Instead of * network stream is returned to the user, * Overridden FsInputStream is returned. * * @param f File path * @param buffersize Buffer size, Not honoured * @return FSDataInputStream InputStream on which application can read * stream of bytes * @throws IOException when system error, internal server error or user error */ @Override public FSDataInputStream open(final Path f, final int buffersize) throws IOException { statistics.incrementReadOps(1); return new FSDataInputStream( new AdlFsInputStream(adlClient.getReadStream(toRelativeFilePath(f)), statistics, getConf())); } /** * Return a file status object that represents the path. * * @param f The path we want information from * @return a FileStatus object * @throws IOException when the path does not exist or any other error; * IOException see specific implementation */ @Override public FileStatus getFileStatus(final Path f) throws IOException { statistics.incrementReadOps(1); DirectoryEntry entry = adlClient.getDirectoryEntry(toRelativeFilePath(f), oidOrUpn); return toFileStatus(entry, f); } /** * List the statuses of the files/directories in the given path if the path is * a directory. * * @param f given path * @return the statuses of the files/directories in the given patch * @throws IOException when the path does not exist or any other error; * IOException see specific implementation */ @Override public FileStatus[] listStatus(final Path f) throws IOException { statistics.incrementReadOps(1); List<DirectoryEntry> entries = adlClient.enumerateDirectory(toRelativeFilePath(f), oidOrUpn); return toFileStatuses(entries, f); } /** * Renames Path src to Path dst. Can take place on local fs * or remote DFS. * * ADLS support POSIX standard for rename operation. * * @param src path to be renamed * @param dst new path after rename * @return true if rename is successful * @throws IOException on failure */ @Override public boolean rename(final Path src, final Path dst) throws IOException { statistics.incrementWriteOps(1); if (toRelativeFilePath(src).equals("/")) { return false; } return adlClient.rename(toRelativeFilePath(src), toRelativeFilePath(dst)); } @Override @Deprecated public void rename(final Path src, final Path dst, final Options.Rename... options) throws IOException { statistics.incrementWriteOps(1); boolean overwrite = false; for (Rename renameOption : options) { if (renameOption == Rename.OVERWRITE) { overwrite = true; break; } } adlClient .rename(toRelativeFilePath(src), toRelativeFilePath(dst), overwrite); } /** * Concat existing files together. * * @param trg the path to the target destination. * @param srcs the paths to the sources to use for the concatenation. * @throws IOException when system error, internal server error or user error */ @Override public void concat(final Path trg, final Path[] srcs) throws IOException { statistics.incrementWriteOps(1); List<String> sourcesList = new ArrayList<String>(); for (Path entry : srcs) { sourcesList.add(toRelativeFilePath(entry)); } adlClient.concatenateFiles(toRelativeFilePath(trg), sourcesList); } /** * Delete a file. * * @param path the path to delete. * @param recursive if path is a directory and set to * true, the directory is deleted else throws an exception. * In case of a file the recursive can be set to either * true or false. * @return true if delete is successful else false. * @throws IOException when system error, internal server error or user error */ @Override public boolean delete(final Path path, final boolean recursive) throws IOException { statistics.incrementWriteOps(1); String relativePath = toRelativeFilePath(path); // Delete on root directory not supported. if (relativePath.equals("/")) { // This is important check after recent commit // HADOOP-12977 and HADOOP-13716 validates on root for // 1. if root is empty and non recursive delete then return false. // 2. if root is non empty and non recursive delete then throw exception. if (!recursive && adlClient.enumerateDirectory(toRelativeFilePath(path), 1).size() > 0) { throw new IOException("Delete on root is not supported."); } return false; } return recursive ? adlClient.deleteRecursive(relativePath) : adlClient.delete(relativePath); } /** * Make the given file and all non-existent parents into * directories. Has the semantics of Unix 'mkdir -p'. * Existence of the directory hierarchy is not an error. * * @param path path to create * @param permission to apply to path */ @Override public boolean mkdirs(final Path path, final FsPermission permission) throws IOException { statistics.incrementWriteOps(1); return adlClient.createDirectory(toRelativeFilePath(path), Integer.toOctalString(applyUMask(permission).toShort())); } private FileStatus[] toFileStatuses(final List<DirectoryEntry> entries, final Path parent) { FileStatus[] fileStatuses = new FileStatus[entries.size()]; int index = 0; for (DirectoryEntry entry : entries) { FileStatus status = toFileStatus(entry, parent); if (!(entry.name == null || entry.name == "")) { status.setPath( new Path(parent.makeQualified(uri, workingDirectory), entry.name)); } fileStatuses[index++] = status; } return fileStatuses; } private FsPermission applyUMask(FsPermission permission) { if (permission == null) { permission = FsPermission.getDefault(); } return permission.applyUMask(FsPermission.getUMask(getConf())); } private FileStatus toFileStatus(final DirectoryEntry entry, final Path f) { Path p = makeQualified(f); boolean aclBit = aclBitStatus ? entry.aclBit : false; if (overrideOwner) { return new AdlFileStatus(entry, p, userName, "hdfs", aclBit); } return new AdlFileStatus(entry, p, aclBit); } /** * Set owner of a path (i.e. a file or a directory). * The parameters owner and group cannot both be null. * * @param path The path * @param owner If it is null, the original username remains unchanged. * @param group If it is null, the original groupname remains unchanged. */ @Override public void setOwner(final Path path, final String owner, final String group) throws IOException { statistics.incrementWriteOps(1); adlClient.setOwner(toRelativeFilePath(path), owner, group); } /** * Set permission of a path. * * @param path The path * @param permission Access permission */ @Override public void setPermission(final Path path, final FsPermission permission) throws IOException { statistics.incrementWriteOps(1); adlClient.setPermission(toRelativeFilePath(path), Integer.toOctalString(permission.toShort())); } /** * Modifies ACL entries of files and directories. This method can add new ACL * entries or modify the permissions on existing ACL entries. All existing * ACL entries that are not specified in this call are retained without * changes. (Modifications are merged into the current ACL.) * * @param path Path to modify * @param aclSpec List of AclEntry describing modifications * @throws IOException if an ACL could not be modified */ @Override public void modifyAclEntries(final Path path, final List<AclEntry> aclSpec) throws IOException { statistics.incrementWriteOps(1); List<com.microsoft.azure.datalake.store.acl.AclEntry> msAclEntries = new ArrayList<com.microsoft.azure.datalake.store.acl.AclEntry>(); for (AclEntry aclEntry : aclSpec) { msAclEntries.add(com.microsoft.azure.datalake.store.acl.AclEntry .parseAclEntry(aclEntry.toString())); } adlClient.modifyAclEntries(toRelativeFilePath(path), msAclEntries); } /** * Removes ACL entries from files and directories. Other ACL entries are * retained. * * @param path Path to modify * @param aclSpec List of AclEntry describing entries to remove * @throws IOException if an ACL could not be modified */ @Override public void removeAclEntries(final Path path, final List<AclEntry> aclSpec) throws IOException { statistics.incrementWriteOps(1); List<com.microsoft.azure.datalake.store.acl.AclEntry> msAclEntries = new ArrayList<com.microsoft.azure.datalake.store.acl.AclEntry>(); for (AclEntry aclEntry : aclSpec) { msAclEntries.add(com.microsoft.azure.datalake.store.acl.AclEntry .parseAclEntry(aclEntry.toString(), true)); } adlClient.removeAclEntries(toRelativeFilePath(path), msAclEntries); } /** * Removes all default ACL entries from files and directories. * * @param path Path to modify * @throws IOException if an ACL could not be modified */ @Override public void removeDefaultAcl(final Path path) throws IOException { statistics.incrementWriteOps(1); adlClient.removeDefaultAcls(toRelativeFilePath(path)); } /** * Removes all but the base ACL entries of files and directories. The entries * for user, group, and others are retained for compatibility with permission * bits. * * @param path Path to modify * @throws IOException if an ACL could not be removed */ @Override public void removeAcl(final Path path) throws IOException { statistics.incrementWriteOps(1); adlClient.removeAllAcls(toRelativeFilePath(path)); } /** * Fully replaces ACL of files and directories, discarding all existing * entries. * * @param path Path to modify * @param aclSpec List of AclEntry describing modifications, must include * entries for user, group, and others for compatibility with * permission bits. * @throws IOException if an ACL could not be modified */ @Override public void setAcl(final Path path, final List<AclEntry> aclSpec) throws IOException { statistics.incrementWriteOps(1); List<com.microsoft.azure.datalake.store.acl.AclEntry> msAclEntries = new ArrayList<com.microsoft.azure.datalake.store.acl.AclEntry>(); for (AclEntry aclEntry : aclSpec) { msAclEntries.add(com.microsoft.azure.datalake.store.acl.AclEntry .parseAclEntry(aclEntry.toString())); } adlClient.setAcl(toRelativeFilePath(path), msAclEntries); } /** * Gets the ACL of a file or directory. * * @param path Path to get * @return AclStatus describing the ACL of the file or directory * @throws IOException if an ACL could not be read */ @Override public AclStatus getAclStatus(final Path path) throws IOException { statistics.incrementReadOps(1); com.microsoft.azure.datalake.store.acl.AclStatus adlStatus = adlClient.getAclStatus(toRelativeFilePath(path), oidOrUpn); AclStatus.Builder aclStatusBuilder = new AclStatus.Builder(); aclStatusBuilder.owner(adlStatus.owner); aclStatusBuilder.group(adlStatus.group); aclStatusBuilder.setPermission( new FsPermission(Short.valueOf(adlStatus.octalPermissions, 8))); aclStatusBuilder.stickyBit(adlStatus.stickyBit); String aclListString = com.microsoft.azure.datalake.store.acl.AclEntry .aclListToString(adlStatus.aclSpec); List<AclEntry> aclEntries = AclEntry.parseAclSpec(aclListString, true); aclStatusBuilder.addEntries(aclEntries); return aclStatusBuilder.build(); } /** * Checks if the user can access a path. The mode specifies which access * checks to perform. If the requested permissions are granted, then the * method returns normally. If access is denied, then the method throws an * {@link AccessControlException}. * * @param path Path to check * @param mode type of access to check * @throws AccessControlException if access is denied * @throws java.io.FileNotFoundException if the path does not exist * @throws IOException see specific implementation */ @Override public void access(final Path path, FsAction mode) throws IOException { statistics.incrementReadOps(1); if (!adlClient.checkAccess(toRelativeFilePath(path), mode.SYMBOL)) { throw new AccessControlException("Access Denied : " + path.toString()); } } /** * Return the {@link ContentSummary} of a given {@link Path}. * * @param f path to use */ @Override public ContentSummary getContentSummary(Path f) throws IOException { statistics.incrementReadOps(1); com.microsoft.azure.datalake.store.ContentSummary msSummary = adlClient .getContentSummary(toRelativeFilePath(f)); return new Builder().length(msSummary.length) .directoryCount(msSummary.directoryCount).fileCount(msSummary.fileCount) .spaceConsumed(msSummary.spaceConsumed).build(); } @VisibleForTesting protected String getTransportScheme() { return SECURE_TRANSPORT_SCHEME; } @VisibleForTesting String toRelativeFilePath(Path path) { return path.makeQualified(uri, workingDirectory).toUri().getPath(); } /** * Get the current working directory for the given file system. * * @return the directory pathname */ @Override public Path getWorkingDirectory() { return workingDirectory; } /** * Set the current working directory for the given file system. All relative * paths will be resolved relative to it. * * @param dir Working directory path. */ @Override public void setWorkingDirectory(final Path dir) { if (dir == null) { throw new InvalidPathException("Working directory cannot be set to NULL"); } /** * Do not validate the scheme and URI of the passsed parameter. When Adls * runs as additional file system, working directory set has the default * file system scheme and uri. * * Found a problem during PIG execution in * https://github.com/apache/pig/blob/branch-0 * .15/src/org/apache/pig/backend/hadoop/executionengine/mapReduceLayer * /PigInputFormat.java#L235 * However similar problem would be present in other application so * defaulting to build working directory using relative path only. */ this.workingDirectory = this.makeAbsolute(dir); } /** * Return the number of bytes that large input files should be optimally * be split into to minimize i/o time. * * @deprecated use {@link #getDefaultBlockSize(Path)} instead */ @Deprecated public long getDefaultBlockSize() { return ADL_BLOCK_SIZE; } /** * Return the number of bytes that large input files should be optimally * be split into to minimize i/o time. The given path will be used to * locate the actual filesystem. The full path does not have to exist. * * @param f path of file * @return the default block size for the path's filesystem */ public long getDefaultBlockSize(Path f) { return getDefaultBlockSize(); } /** * Get the block size. * @param f the filename * @return the number of bytes in a block */ /** * @deprecated Use getFileStatus() instead */ @Deprecated public long getBlockSize(Path f) throws IOException { return ADL_BLOCK_SIZE; } /** * Get replication. * * @param src file name * @return file replication * @deprecated Use getFileStatus() instead */ @Deprecated public short getReplication(Path src) { return ADL_REPLICATION_FACTOR; } private Path makeAbsolute(Path path) { return path.isAbsolute() ? path : new Path(this.workingDirectory, path); } private static String getNonEmptyVal(Configuration conf, String key) { String value = conf.get(key); if (StringUtils.isEmpty(value)) { throw new IllegalArgumentException( "No value for " + key + " found in conf file."); } return value; } /** * A wrapper of {@link Configuration#getPassword(String)}. It returns * <code>String</code> instead of <code>char[]</code>. * * @param conf the configuration * @param key the property key * @return the password string * @throws IOException if the password was not found */ private static String getPasswordString(Configuration conf, String key) throws IOException { char[] passchars = conf.getPassword(key); if (passchars == null) { throw new IOException("Password " + key + " not found"); } return new String(passchars); } @VisibleForTesting public void setUserGroupRepresentationAsUPN(boolean enableUPN) { oidOrUpn = enableUPN ? UserGroupRepresentation.UPN : UserGroupRepresentation.OID; } /** * Gets ADL account name from ADL FQDN. * @param accountFQDN ADL account fqdn * @return ADL account name */ public static String getAccountNameFromFQDN(String accountFQDN) { return accountFQDN.contains(".") ? accountFQDN.substring(0, accountFQDN.indexOf(".")) : accountFQDN; } /** * Propagates account-specific settings into generic ADL configuration keys. * This is done by propagating the values of the form * {@code fs.adl.account.${account_name}.key} to * {@code fs.adl.key}, for all values of "key" * * The source of the updated property is set to the key name of the account * property, to aid in diagnostics of where things came from. * * Returns a new configuration. Why the clone? * You can use the same conf for different filesystems, and the original * values are not updated. * * * @param source Source Configuration object * @param accountName account name. Must not be empty * @return a (potentially) patched clone of the original */ public static Configuration propagateAccountOptions(Configuration source, String accountName) { Preconditions.checkArgument(StringUtils.isNotEmpty(accountName), "accountName"); final String accountPrefix = AZURE_AD_ACCOUNT_PREFIX + accountName +'.'; LOG.debug("Propagating entries under {}", accountPrefix); final Configuration dest = new Configuration(source); for (Map.Entry<String, String> entry : source) { final String key = entry.getKey(); // get the (unexpanded) value. final String value = entry.getValue(); if (!key.startsWith(accountPrefix) || accountPrefix.equals(key)) { continue; } // there's a account prefix, so strip it final String stripped = key.substring(accountPrefix.length()); // propagate the value, building a new origin field. // to track overwrites, the generic key is overwritten even if // already matches the new one. String origin = "[" + StringUtils.join( source.getPropertySources(key), ", ") +"]"; final String generic = AZURE_AD_PREFIX + stripped; LOG.debug("Updating {} from {}", generic, origin); dest.set(generic, value, key + " via " + origin); } return dest; } @Override public boolean hasPathCapability(final Path path, final String capability) throws IOException { switch (validatePathCapabilityArgs(makeQualified(path), capability)) { case CommonPathCapabilities.FS_ACLS: case CommonPathCapabilities.FS_APPEND: case CommonPathCapabilities.FS_CONCAT: case CommonPathCapabilities.FS_PERMISSIONS: return true; default: return super.hasPathCapability(path, capability); } } }
apache/pulsar
37,986
pulsar-testclient/src/main/java/org/apache/pulsar/testclient/PerformanceTransaction.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.testclient; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static org.apache.pulsar.testclient.PerfClientUtils.addShutdownHook; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.common.util.concurrent.RateLimiter; import java.io.FileOutputStream; import java.io.PrintStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.LongAdder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import org.HdrHistogram.Recorder; import org.apache.pulsar.client.admin.PulsarAdmin; import org.apache.pulsar.client.admin.PulsarAdminBuilder; import org.apache.pulsar.client.admin.PulsarAdminException; import org.apache.pulsar.client.api.ClientBuilder; import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.ConsumerBuilder; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.ProducerBuilder; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.api.SubscriptionInitialPosition; import org.apache.pulsar.client.api.SubscriptionType; import org.apache.pulsar.client.api.transaction.Transaction; import org.apache.pulsar.common.partition.PartitionedTopicMetadata; import org.apache.pulsar.testclient.utils.PaddingDecimalFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import picocli.CommandLine.Command; import picocli.CommandLine.Option; @Command(name = "transaction", description = "Test pulsar transaction performance.") public class PerformanceTransaction extends PerformanceBaseArguments{ private static final LongAdder totalNumEndTxnOpFailed = new LongAdder(); private static final LongAdder totalNumEndTxnOpSuccess = new LongAdder(); private static final LongAdder numTxnOpSuccess = new LongAdder(); private static final LongAdder totalNumTxnOpenTxnFail = new LongAdder(); private static final LongAdder totalNumTxnOpenTxnSuccess = new LongAdder(); private static final LongAdder numMessagesAckFailed = new LongAdder(); private static final LongAdder numMessagesAckSuccess = new LongAdder(); private static final LongAdder numMessagesSendFailed = new LongAdder(); private static final LongAdder numMessagesSendSuccess = new LongAdder(); private static final Recorder messageAckRecorder = new Recorder(TimeUnit.SECONDS.toMicros(120000), 5); private static final Recorder messageAckCumulativeRecorder = new Recorder(TimeUnit.SECONDS.toMicros(120000), 5); private static final Recorder messageSendRecorder = new Recorder(TimeUnit.SECONDS.toMicros(120000), 5); private static final Recorder messageSendRCumulativeRecorder = new Recorder(TimeUnit.SECONDS.toMicros(120000), 5); @Option(names = "--topics-c", description = "All topics that need ack for a transaction", required = true) public List<String> consumerTopic = Collections.singletonList("test-consume"); @Option(names = "--topics-p", description = "All topics that need produce for a transaction", required = true) public List<String> producerTopic = Collections.singletonList("test-produce"); @Option(names = {"-threads", "--num-test-threads"}, description = "Number of test threads." + "This thread is for a new transaction to ack messages from consumer topics and produce message to " + "producer topics, and then commit or abort this transaction. " + "Increasing the number of threads increases the parallelism of the performance test, " + "thereby increasing the intensity of the stress test.") public int numTestThreads = 1; @Option(names = {"-au", "--admin-url"}, description = "Pulsar Admin URL", descriptionKey = "webServiceUrl") public String adminURL; @Option(names = {"-np", "--partitions"}, description = "Create partitioned topics with a given number of partitions, 0 means" + "not trying to create a topic") public Integer partitions = null; @Option(names = {"-time", "--test-duration"}, description = "Test duration (in second). 0 means keeping publishing") public long testTime = 0; @Option(names = {"-ss", "--subscriptions"}, description = "A list of subscriptions to consume (for example, sub1,sub2)") public List<String> subscriptions = Collections.singletonList("sub"); @Option(names = {"-ns", "--num-subscriptions"}, description = "Number of subscriptions (per topic)") public int numSubscriptions = 1; @Option(names = {"-sp", "--subscription-position"}, description = "Subscription position") private SubscriptionInitialPosition subscriptionInitialPosition = SubscriptionInitialPosition.Earliest; @Option(names = {"-st", "--subscription-type"}, description = "Subscription type") public SubscriptionType subscriptionType = SubscriptionType.Shared; @Option(names = {"-rs", "--replicated" }, description = "Whether the subscription status should be replicated") private boolean replicatedSubscription = false; @Option(names = {"-q", "--receiver-queue-size"}, description = "Size of the receiver queue") public int receiverQueueSize = 1000; @Option(names = {"-tto", "--txn-timeout"}, description = "Set the time value of transaction timeout," + " and the time unit is second. (After --txn-enable setting to true, --txn-timeout takes effect)") public long transactionTimeout = 5; @Option(names = {"-ntxn", "--number-txn"}, description = "Set the number of transaction. 0 means keeping open." + "If transaction disabled, it means the number of tasks. The task or transaction produces or " + "consumes a specified number of messages.") public long numTransactions = 0; @Option(names = {"-nmp", "--numMessage-perTransaction-produce"}, description = "Set the number of messages produced in a transaction." + "If transaction disabled, it means the number of messages produced in a task.") public int numMessagesProducedPerTransaction = 1; @Option(names = {"-nmc", "--numMessage-perTransaction-consume"}, description = "Set the number of messages consumed in a transaction." + "If transaction disabled, it means the number of messages consumed in a task.") public int numMessagesReceivedPerTransaction = 1; @Option(names = {"--txn-disable"}, description = "Disable transaction") public boolean isDisableTransaction = false; @Option(names = {"-abort"}, description = "Abort the transaction. (After --txn-disEnable " + "setting to false, -abort takes effect)") public boolean isAbortTransaction = false; @Option(names = "-txnRate", description = "Set the rate of opened transaction or task. 0 means no limit") public int openTxnRate = 0; public PerformanceTransaction() { super("transaction"); } @Override public void run() throws Exception { super.parseCLI(); // Dump config variables PerfClientUtils.printJVMInformation(log); ObjectMapper m = new ObjectMapper(); ObjectWriter w = m.writerWithDefaultPrettyPrinter(); log.info("Starting Pulsar perf transaction with config: {}", w.writeValueAsString(this)); final byte[] payloadBytes = new byte[1024]; Random random = new Random(0); for (int i = 0; i < payloadBytes.length; ++i) { payloadBytes[i] = (byte) (random.nextInt(26) + 65); } if (this.partitions != null) { final PulsarAdminBuilder adminBuilder = PerfClientUtils .createAdminBuilderFromArguments(this, this.adminURL); try (PulsarAdmin adminClient = adminBuilder.build()) { for (String topic : this.producerTopic) { log.info("Creating produce partitioned topic {} with {} partitions", topic, this.partitions); try { adminClient.topics().createPartitionedTopic(topic, this.partitions); } catch (PulsarAdminException.ConflictException alreadyExists) { if (log.isDebugEnabled()) { log.debug("Topic {} already exists: {}", topic, alreadyExists); } PartitionedTopicMetadata partitionedTopicMetadata = adminClient.topics().getPartitionedTopicMetadata(topic); if (partitionedTopicMetadata.partitions != this.partitions) { log.error( "Topic {} already exists but it has a wrong number of partitions: {}, expecting {}", topic, partitionedTopicMetadata.partitions, this.partitions); PerfClientUtils.exit(1); } } } } } ClientBuilder clientBuilder = PerfClientUtils.createClientBuilderFromArguments(this) .enableTransaction(!this.isDisableTransaction); PulsarClient client = clientBuilder.build(); try { ExecutorService executorService = new ThreadPoolExecutor(this.numTestThreads, this.numTestThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); long startTime = System.nanoTime(); long testEndTime = startTime + (long) (this.testTime * 1e9); Thread shutdownHookThread = addShutdownHook(() -> { if (!this.isDisableTransaction) { printTxnAggregatedThroughput(startTime); } else { printAggregatedThroughput(startTime); } printAggregatedStats(); }); // start perf test AtomicBoolean executing = new AtomicBoolean(true); RateLimiter rateLimiter = this.openTxnRate > 0 ? RateLimiter.create(this.openTxnRate) : null; for (int i = 0; i < this.numTestThreads; i++) { executorService.submit(() -> { //The producer and consumer clients are built in advance, and then this thread is //responsible for the production and consumption tasks of the transaction through the loop. //A thread may perform tasks of multiple transactions in a traversing manner. List<Producer<byte[]>> producers = null; List<List<Consumer<byte[]>>> consumers = null; AtomicReference<Transaction> atomicReference = null; try { producers = buildProducers(client); consumers = buildConsumer(client); if (!this.isDisableTransaction) { atomicReference = new AtomicReference<>(client.newTransaction() .withTransactionTimeout(this.transactionTimeout, TimeUnit.SECONDS) .build() .get()); } else { atomicReference = new AtomicReference<>(null); } } catch (Exception e) { if (PerfClientUtils.hasInterruptedException(e)) { Thread.currentThread().interrupt(); } else { log.error("Failed to build Producer/Consumer with exception : ", e); } executorService.shutdownNow(); PerfClientUtils.exit(1); } //The while loop has no break, and finally ends the execution through the shutdownNow of //the executorService while (!Thread.currentThread().isInterrupted()) { if (this.numTransactions > 0) { if (totalNumTxnOpenTxnFail.sum() + totalNumTxnOpenTxnSuccess.sum() >= this.numTransactions) { if (totalNumEndTxnOpFailed.sum() + totalNumEndTxnOpSuccess.sum() < this.numTransactions) { continue; } log.info("------------------- DONE -----------------------"); executing.compareAndSet(true, false); executorService.shutdownNow(); PerfClientUtils.exit(0); break; } } if (this.testTime > 0) { if (System.nanoTime() > testEndTime) { log.info("------------------- DONE -----------------------"); executing.compareAndSet(true, false); executorService.shutdownNow(); PerfClientUtils.exit(0); break; } } Transaction transaction = atomicReference.get(); for (List<Consumer<byte[]>> subscriptions : consumers) { for (Consumer<byte[]> consumer : subscriptions) { for (int j = 0; j < this.numMessagesReceivedPerTransaction; j++) { Message<byte[]> message = null; try { message = consumer.receive(); } catch (PulsarClientException e) { log.error("Receive message failed", e); executorService.shutdownNow(); PerfClientUtils.exit(1); } long receiveTime = System.nanoTime(); if (!this.isDisableTransaction) { consumer.acknowledgeAsync(message.getMessageId(), transaction) .thenRun(() -> { long latencyMicros = NANOSECONDS.toMicros( System.nanoTime() - receiveTime); messageAckRecorder.recordValue(latencyMicros); messageAckCumulativeRecorder.recordValue(latencyMicros); numMessagesAckSuccess.increment(); }).exceptionally(exception -> { if (PerfClientUtils.hasInterruptedException(exception)) { Thread.currentThread().interrupt(); return null; } log.error( "Ack message failed with transaction {} throw exception", transaction, exception); numMessagesAckFailed.increment(); return null; }); } else { consumer.acknowledgeAsync(message).thenRun(() -> { long latencyMicros = NANOSECONDS.toMicros( System.nanoTime() - receiveTime); messageAckRecorder.recordValue(latencyMicros); messageAckCumulativeRecorder.recordValue(latencyMicros); numMessagesAckSuccess.increment(); }).exceptionally(exception -> { if (PerfClientUtils.hasInterruptedException(exception)) { Thread.currentThread().interrupt(); return null; } log.error( "Ack message failed with transaction {} throw exception", transaction, exception); numMessagesAckFailed.increment(); return null; }); } } } } for (Producer<byte[]> producer : producers) { for (int j = 0; j < this.numMessagesProducedPerTransaction; j++) { long sendTime = System.nanoTime(); if (!this.isDisableTransaction) { producer.newMessage(transaction).value(payloadBytes) .sendAsync().thenRun(() -> { long latencyMicros = NANOSECONDS.toMicros( System.nanoTime() - sendTime); messageSendRecorder.recordValue(latencyMicros); messageSendRCumulativeRecorder.recordValue(latencyMicros); numMessagesSendSuccess.increment(); }).exceptionally(exception -> { if (PerfClientUtils.hasInterruptedException(exception)) { Thread.currentThread().interrupt(); return null; } // Ignore the exception when the producer is closed if (exception.getCause() instanceof PulsarClientException.AlreadyClosedException) { return null; } log.error("Send transaction message failed with exception : ", exception); numMessagesSendFailed.increment(); return null; }); } else { producer.newMessage().value(payloadBytes) .sendAsync().thenRun(() -> { long latencyMicros = NANOSECONDS.toMicros( System.nanoTime() - sendTime); messageSendRecorder.recordValue(latencyMicros); messageSendRCumulativeRecorder.recordValue(latencyMicros); numMessagesSendSuccess.increment(); }).exceptionally(exception -> { if (PerfClientUtils.hasInterruptedException(exception)) { Thread.currentThread().interrupt(); return null; } // Ignore the exception when the producer is closed if (exception.getCause() instanceof PulsarClientException.AlreadyClosedException) { return null; } log.error("Send message failed with exception : ", exception); numMessagesSendFailed.increment(); return null; }); } } } if (rateLimiter != null) { rateLimiter.tryAcquire(); } if (!this.isDisableTransaction) { if (!this.isAbortTransaction) { transaction.commit() .thenRun(() -> { numTxnOpSuccess.increment(); totalNumEndTxnOpSuccess.increment(); }).exceptionally(exception -> { if (PerfClientUtils.hasInterruptedException(exception)) { Thread.currentThread().interrupt(); return null; } log.error("Commit transaction {} failed with exception", transaction.getTxnID().toString(), exception); totalNumEndTxnOpFailed.increment(); return null; }); } else { transaction.abort().thenRun(() -> { numTxnOpSuccess.increment(); totalNumEndTxnOpSuccess.increment(); }).exceptionally(exception -> { if (PerfClientUtils.hasInterruptedException(exception)) { Thread.currentThread().interrupt(); return null; } log.error("Commit transaction {} failed with exception", transaction.getTxnID().toString(), exception); totalNumEndTxnOpFailed.increment(); return null; }); } while (!Thread.currentThread().isInterrupted()) { try { Transaction newTransaction = client.newTransaction() .withTransactionTimeout(this.transactionTimeout, TimeUnit.SECONDS) .build() .get(); atomicReference.compareAndSet(transaction, newTransaction); totalNumTxnOpenTxnSuccess.increment(); break; } catch (Exception throwable) { if (PerfClientUtils.hasInterruptedException(throwable)) { Thread.currentThread().interrupt(); } else { log.error("Failed to new transaction with exception: ", throwable); totalNumTxnOpenTxnFail.increment(); } } } } else { totalNumTxnOpenTxnSuccess.increment(); totalNumEndTxnOpSuccess.increment(); numTxnOpSuccess.increment(); } } }); } // Print report stats long oldTime = System.nanoTime(); Histogram reportSendHistogram = null; Histogram reportAckHistogram = null; String statsFileName = "perf-transaction-" + System.currentTimeMillis() + ".hgrm"; log.info("Dumping latency stats to {}", statsFileName); PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false); HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog); // Some log header bits histogramLogWriter.outputLogFormatVersion(); histogramLogWriter.outputLegend(); while (!Thread.currentThread().isInterrupted() && executing.get()) { try { Thread.sleep(10000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } long now = System.nanoTime(); double elapsed = (now - oldTime) / 1e9; long total = totalNumEndTxnOpFailed.sum() + totalNumTxnOpenTxnSuccess.sum(); double rate = numTxnOpSuccess.sumThenReset() / elapsed; reportSendHistogram = messageSendRecorder.getIntervalHistogram(reportSendHistogram); reportAckHistogram = messageAckRecorder.getIntervalHistogram(reportAckHistogram); String txnOrTaskLog = !this.isDisableTransaction ? "Throughput transaction: {} transaction executes --- {} transaction/s" : "Throughput task: {} task executes --- {} task/s"; log.info( txnOrTaskLog + " --- send Latency: mean: {} ms - med: {} " + "- 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}" + " --- ack Latency: " + "mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: " + "{}", INTFORMAT.format(total), DEC.format(rate), DEC.format(reportSendHistogram.getMean() / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(50) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(95) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99.9) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99.99) / 1000.0), DEC.format(reportSendHistogram.getMaxValue() / 1000.0), DEC.format(reportAckHistogram.getMean() / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(50) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(95) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99.9) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99.99) / 1000.0), DEC.format(reportAckHistogram.getMaxValue() / 1000.0)); histogramLogWriter.outputIntervalHistogram(reportSendHistogram); histogramLogWriter.outputIntervalHistogram(reportAckHistogram); reportSendHistogram.reset(); reportAckHistogram.reset(); oldTime = now; } PerfClientUtils.removeAndRunShutdownHook(shutdownHookThread); } finally { PerfClientUtils.closeClient(client); } } private static void printTxnAggregatedThroughput(long start) { double elapsed = (System.nanoTime() - start) / 1e9; long numTransactionEndFailed = totalNumEndTxnOpFailed.sum(); long numTransactionEndSuccess = totalNumEndTxnOpSuccess.sum(); long total = numTransactionEndFailed + numTransactionEndSuccess; double rate = total / elapsed; long numMessageAckFailed = numMessagesAckFailed.sum(); long numMessageAckSuccess = numMessagesAckSuccess.sum(); long numMessageSendFailed = numMessagesSendFailed.sum(); long numMessageSendSuccess = numMessagesSendSuccess.sum(); long numTransactionOpenFailed = totalNumTxnOpenTxnFail.sum(); long numTransactionOpenSuccess = totalNumTxnOpenTxnSuccess.sum(); log.info( "Aggregated throughput stats --- {} transaction executed --- {} transaction/s " + " --- {} transaction open successfully --- {} transaction open failed" + " --- {} transaction end successfully --- {} transaction end failed" + " --- {} message ack failed --- {} message send failed" + " --- {} message ack success --- {} message send success ", total, DEC.format(rate), numTransactionOpenSuccess, numTransactionOpenFailed, numTransactionEndSuccess, numTransactionEndFailed, numMessageAckFailed, numMessageSendFailed, numMessageAckSuccess, numMessageSendSuccess); } private static void printAggregatedThroughput(long start) { double elapsed = (System.nanoTime() - start) / 1e9; long total = totalNumEndTxnOpFailed.sum() + totalNumEndTxnOpSuccess.sum(); double rate = total / elapsed; long numMessageAckFailed = numMessagesAckFailed.sum(); long numMessageAckSuccess = numMessagesAckSuccess.sum(); long numMessageSendFailed = numMessagesSendFailed.sum(); long numMessageSendSuccess = numMessagesSendSuccess.sum(); log.info( "Aggregated throughput stats --- {} task executed --- {} task/s" + " --- {} message ack failed --- {} message send failed" + " --- {} message ack success --- {} message send success", total, TOTALFORMAT.format(rate), numMessageAckFailed, numMessageSendFailed, numMessageAckSuccess, numMessageSendSuccess); } private static void printAggregatedStats() { Histogram reportAckHistogram = messageAckCumulativeRecorder.getIntervalHistogram(); Histogram reportSendHistogram = messageSendRCumulativeRecorder.getIntervalHistogram(); log.info( "Messages ack aggregated latency stats --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - " + "99.9pct: {} - " + "99.99pct: {} - 99.999pct: {} - Max: {}", DEC.format(reportAckHistogram.getMean() / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(50) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(95) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99.9) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99.99) / 1000.0), DEC.format(reportAckHistogram.getValueAtPercentile(99.999) / 1000.0), DEC.format(reportAckHistogram.getMaxValue() / 1000.0)); log.info( "Messages send aggregated latency stats --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - " + "99.9pct: {} - " + "99.99pct: {} - 99.999pct: {} - Max: {}", DEC.format(reportSendHistogram.getMean() / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(50) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(95) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99.9) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99.99) / 1000.0), DEC.format(reportSendHistogram.getValueAtPercentile(99.999) / 1000.0), DEC.format(reportSendHistogram.getMaxValue() / 1000.0)); } static final DecimalFormat DEC = new PaddingDecimalFormat("0.000", 7); static final DecimalFormat INTFORMAT = new PaddingDecimalFormat("0", 7); static final DecimalFormat TOTALFORMAT = new DecimalFormat("0.000"); private static final Logger log = LoggerFactory.getLogger(PerformanceTransaction.class); private List<List<Consumer<byte[]>>> buildConsumer(PulsarClient client) throws ExecutionException, InterruptedException { ConsumerBuilder<byte[]> consumerBuilder = client.newConsumer(Schema.BYTES) .subscriptionType(this.subscriptionType) .receiverQueueSize(this.receiverQueueSize) .subscriptionInitialPosition(this.subscriptionInitialPosition) .replicateSubscriptionState(this.replicatedSubscription); Iterator<String> consumerTopicsIterator = this.consumerTopic.iterator(); List<List<Consumer<byte[]>>> consumers = new ArrayList<>(this.consumerTopic.size()); while (consumerTopicsIterator.hasNext()){ String topic = consumerTopicsIterator.next(); final List<Consumer<byte[]>> subscriptions = new ArrayList<>(this.numSubscriptions); final List<Future<Consumer<byte[]>>> subscriptionFutures = new ArrayList<>(this.numSubscriptions); log.info("Create subscriptions for topic {}", topic); for (int j = 0; j < this.numSubscriptions; j++) { String subscriberName = this.subscriptions.get(j); subscriptionFutures .add(consumerBuilder.clone().topic(topic).subscriptionName(subscriberName) .subscribeAsync()); } for (Future<Consumer<byte[]>> future : subscriptionFutures) { subscriptions.add(future.get()); } consumers.add(subscriptions); } return consumers; } private List<Producer<byte[]>> buildProducers(PulsarClient client) throws ExecutionException, InterruptedException { ProducerBuilder<byte[]> producerBuilder = client.newProducer(Schema.BYTES) .sendTimeout(0, TimeUnit.SECONDS); final List<Future<Producer<byte[]>>> producerFutures = new ArrayList<>(); for (String topic : this.producerTopic) { log.info("Create producer for topic {}", topic); producerFutures.add(producerBuilder.clone().topic(topic).createAsync()); } final List<Producer<byte[]>> producers = new ArrayList<>(producerFutures.size()); for (Future<Producer<byte[]>> future : producerFutures) { producers.add(future.get()); } return producers; } }
googleapis/google-cloud-java
37,627
java-maps-solar/proto-google-maps-solar-v1/src/main/java/com/google/maps/solar/v1/LeasingSavings.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/maps/solar/v1/solar_service.proto // Protobuf Java Version: 3.25.8 package com.google.maps.solar.v1; /** * * * <pre> * Cost and benefit of leasing a particular configuration of solar panels * with a particular electricity usage. * </pre> * * Protobuf type {@code google.maps.solar.v1.LeasingSavings} */ public final class LeasingSavings extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.maps.solar.v1.LeasingSavings) LeasingSavingsOrBuilder { private static final long serialVersionUID = 0L; // Use LeasingSavings.newBuilder() to construct. private LeasingSavings(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private LeasingSavings() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new LeasingSavings(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.solar.v1.SolarServiceProto .internal_static_google_maps_solar_v1_LeasingSavings_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.solar.v1.SolarServiceProto .internal_static_google_maps_solar_v1_LeasingSavings_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.solar.v1.LeasingSavings.class, com.google.maps.solar.v1.LeasingSavings.Builder.class); } private int bitField0_; public static final int LEASES_ALLOWED_FIELD_NUMBER = 1; private boolean leasesAllowed_ = false; /** * * * <pre> * Whether leases are allowed in this juristiction (leases are not * allowed in some states). If this field is false, then the values in * this message should probably be ignored. * </pre> * * <code>bool leases_allowed = 1;</code> * * @return The leasesAllowed. */ @java.lang.Override public boolean getLeasesAllowed() { return leasesAllowed_; } public static final int LEASES_SUPPORTED_FIELD_NUMBER = 2; private boolean leasesSupported_ = false; /** * * * <pre> * Whether leases are supported in this juristiction by the financial * calculation engine. If this field is false, then the values in this * message should probably be ignored. This is independent of * `leases_allowed`: in some areas leases are allowed, but under conditions * that aren't handled by the financial models. * </pre> * * <code>bool leases_supported = 2;</code> * * @return The leasesSupported. */ @java.lang.Override public boolean getLeasesSupported() { return leasesSupported_; } public static final int ANNUAL_LEASING_COST_FIELD_NUMBER = 3; private com.google.type.Money annualLeasingCost_; /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> * * @return Whether the annualLeasingCost field is set. */ @java.lang.Override public boolean hasAnnualLeasingCost() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> * * @return The annualLeasingCost. */ @java.lang.Override public com.google.type.Money getAnnualLeasingCost() { return annualLeasingCost_ == null ? com.google.type.Money.getDefaultInstance() : annualLeasingCost_; } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ @java.lang.Override public com.google.type.MoneyOrBuilder getAnnualLeasingCostOrBuilder() { return annualLeasingCost_ == null ? com.google.type.Money.getDefaultInstance() : annualLeasingCost_; } public static final int SAVINGS_FIELD_NUMBER = 4; private com.google.maps.solar.v1.SavingsOverTime savings_; /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> * * @return Whether the savings field is set. */ @java.lang.Override public boolean hasSavings() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> * * @return The savings. */ @java.lang.Override public com.google.maps.solar.v1.SavingsOverTime getSavings() { return savings_ == null ? com.google.maps.solar.v1.SavingsOverTime.getDefaultInstance() : savings_; } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ @java.lang.Override public com.google.maps.solar.v1.SavingsOverTimeOrBuilder getSavingsOrBuilder() { return savings_ == null ? com.google.maps.solar.v1.SavingsOverTime.getDefaultInstance() : savings_; } 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 (leasesAllowed_ != false) { output.writeBool(1, leasesAllowed_); } if (leasesSupported_ != false) { output.writeBool(2, leasesSupported_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getAnnualLeasingCost()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(4, getSavings()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (leasesAllowed_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, leasesAllowed_); } if (leasesSupported_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(2, leasesSupported_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getAnnualLeasingCost()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getSavings()); } 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.maps.solar.v1.LeasingSavings)) { return super.equals(obj); } com.google.maps.solar.v1.LeasingSavings other = (com.google.maps.solar.v1.LeasingSavings) obj; if (getLeasesAllowed() != other.getLeasesAllowed()) return false; if (getLeasesSupported() != other.getLeasesSupported()) return false; if (hasAnnualLeasingCost() != other.hasAnnualLeasingCost()) return false; if (hasAnnualLeasingCost()) { if (!getAnnualLeasingCost().equals(other.getAnnualLeasingCost())) return false; } if (hasSavings() != other.hasSavings()) return false; if (hasSavings()) { if (!getSavings().equals(other.getSavings())) 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) + LEASES_ALLOWED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getLeasesAllowed()); hash = (37 * hash) + LEASES_SUPPORTED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getLeasesSupported()); if (hasAnnualLeasingCost()) { hash = (37 * hash) + ANNUAL_LEASING_COST_FIELD_NUMBER; hash = (53 * hash) + getAnnualLeasingCost().hashCode(); } if (hasSavings()) { hash = (37 * hash) + SAVINGS_FIELD_NUMBER; hash = (53 * hash) + getSavings().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.maps.solar.v1.LeasingSavings parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.solar.v1.LeasingSavings parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.solar.v1.LeasingSavings parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.solar.v1.LeasingSavings 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.maps.solar.v1.LeasingSavings parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.solar.v1.LeasingSavings parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.solar.v1.LeasingSavings parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.solar.v1.LeasingSavings 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.maps.solar.v1.LeasingSavings parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.maps.solar.v1.LeasingSavings 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.maps.solar.v1.LeasingSavings parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.solar.v1.LeasingSavings 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.maps.solar.v1.LeasingSavings 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> * Cost and benefit of leasing a particular configuration of solar panels * with a particular electricity usage. * </pre> * * Protobuf type {@code google.maps.solar.v1.LeasingSavings} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.maps.solar.v1.LeasingSavings) com.google.maps.solar.v1.LeasingSavingsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.solar.v1.SolarServiceProto .internal_static_google_maps_solar_v1_LeasingSavings_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.solar.v1.SolarServiceProto .internal_static_google_maps_solar_v1_LeasingSavings_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.solar.v1.LeasingSavings.class, com.google.maps.solar.v1.LeasingSavings.Builder.class); } // Construct using com.google.maps.solar.v1.LeasingSavings.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getAnnualLeasingCostFieldBuilder(); getSavingsFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; leasesAllowed_ = false; leasesSupported_ = false; annualLeasingCost_ = null; if (annualLeasingCostBuilder_ != null) { annualLeasingCostBuilder_.dispose(); annualLeasingCostBuilder_ = null; } savings_ = null; if (savingsBuilder_ != null) { savingsBuilder_.dispose(); savingsBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.maps.solar.v1.SolarServiceProto .internal_static_google_maps_solar_v1_LeasingSavings_descriptor; } @java.lang.Override public com.google.maps.solar.v1.LeasingSavings getDefaultInstanceForType() { return com.google.maps.solar.v1.LeasingSavings.getDefaultInstance(); } @java.lang.Override public com.google.maps.solar.v1.LeasingSavings build() { com.google.maps.solar.v1.LeasingSavings result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.maps.solar.v1.LeasingSavings buildPartial() { com.google.maps.solar.v1.LeasingSavings result = new com.google.maps.solar.v1.LeasingSavings(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.maps.solar.v1.LeasingSavings result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.leasesAllowed_ = leasesAllowed_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.leasesSupported_ = leasesSupported_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.annualLeasingCost_ = annualLeasingCostBuilder_ == null ? annualLeasingCost_ : annualLeasingCostBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000008) != 0)) { result.savings_ = savingsBuilder_ == null ? savings_ : savingsBuilder_.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.maps.solar.v1.LeasingSavings) { return mergeFrom((com.google.maps.solar.v1.LeasingSavings) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.maps.solar.v1.LeasingSavings other) { if (other == com.google.maps.solar.v1.LeasingSavings.getDefaultInstance()) return this; if (other.getLeasesAllowed() != false) { setLeasesAllowed(other.getLeasesAllowed()); } if (other.getLeasesSupported() != false) { setLeasesSupported(other.getLeasesSupported()); } if (other.hasAnnualLeasingCost()) { mergeAnnualLeasingCost(other.getAnnualLeasingCost()); } if (other.hasSavings()) { mergeSavings(other.getSavings()); } 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: { leasesAllowed_ = input.readBool(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { leasesSupported_ = input.readBool(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { input.readMessage( getAnnualLeasingCostFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 case 34: { input.readMessage(getSavingsFieldBuilder().getBuilder(), extensionRegistry); 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 leasesAllowed_; /** * * * <pre> * Whether leases are allowed in this juristiction (leases are not * allowed in some states). If this field is false, then the values in * this message should probably be ignored. * </pre> * * <code>bool leases_allowed = 1;</code> * * @return The leasesAllowed. */ @java.lang.Override public boolean getLeasesAllowed() { return leasesAllowed_; } /** * * * <pre> * Whether leases are allowed in this juristiction (leases are not * allowed in some states). If this field is false, then the values in * this message should probably be ignored. * </pre> * * <code>bool leases_allowed = 1;</code> * * @param value The leasesAllowed to set. * @return This builder for chaining. */ public Builder setLeasesAllowed(boolean value) { leasesAllowed_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Whether leases are allowed in this juristiction (leases are not * allowed in some states). If this field is false, then the values in * this message should probably be ignored. * </pre> * * <code>bool leases_allowed = 1;</code> * * @return This builder for chaining. */ public Builder clearLeasesAllowed() { bitField0_ = (bitField0_ & ~0x00000001); leasesAllowed_ = false; onChanged(); return this; } private boolean leasesSupported_; /** * * * <pre> * Whether leases are supported in this juristiction by the financial * calculation engine. If this field is false, then the values in this * message should probably be ignored. This is independent of * `leases_allowed`: in some areas leases are allowed, but under conditions * that aren't handled by the financial models. * </pre> * * <code>bool leases_supported = 2;</code> * * @return The leasesSupported. */ @java.lang.Override public boolean getLeasesSupported() { return leasesSupported_; } /** * * * <pre> * Whether leases are supported in this juristiction by the financial * calculation engine. If this field is false, then the values in this * message should probably be ignored. This is independent of * `leases_allowed`: in some areas leases are allowed, but under conditions * that aren't handled by the financial models. * </pre> * * <code>bool leases_supported = 2;</code> * * @param value The leasesSupported to set. * @return This builder for chaining. */ public Builder setLeasesSupported(boolean value) { leasesSupported_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Whether leases are supported in this juristiction by the financial * calculation engine. If this field is false, then the values in this * message should probably be ignored. This is independent of * `leases_allowed`: in some areas leases are allowed, but under conditions * that aren't handled by the financial models. * </pre> * * <code>bool leases_supported = 2;</code> * * @return This builder for chaining. */ public Builder clearLeasesSupported() { bitField0_ = (bitField0_ & ~0x00000002); leasesSupported_ = false; onChanged(); return this; } private com.google.type.Money annualLeasingCost_; private com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder> annualLeasingCostBuilder_; /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> * * @return Whether the annualLeasingCost field is set. */ public boolean hasAnnualLeasingCost() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> * * @return The annualLeasingCost. */ public com.google.type.Money getAnnualLeasingCost() { if (annualLeasingCostBuilder_ == null) { return annualLeasingCost_ == null ? com.google.type.Money.getDefaultInstance() : annualLeasingCost_; } else { return annualLeasingCostBuilder_.getMessage(); } } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ public Builder setAnnualLeasingCost(com.google.type.Money value) { if (annualLeasingCostBuilder_ == null) { if (value == null) { throw new NullPointerException(); } annualLeasingCost_ = value; } else { annualLeasingCostBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ public Builder setAnnualLeasingCost(com.google.type.Money.Builder builderForValue) { if (annualLeasingCostBuilder_ == null) { annualLeasingCost_ = builderForValue.build(); } else { annualLeasingCostBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ public Builder mergeAnnualLeasingCost(com.google.type.Money value) { if (annualLeasingCostBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && annualLeasingCost_ != null && annualLeasingCost_ != com.google.type.Money.getDefaultInstance()) { getAnnualLeasingCostBuilder().mergeFrom(value); } else { annualLeasingCost_ = value; } } else { annualLeasingCostBuilder_.mergeFrom(value); } if (annualLeasingCost_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ public Builder clearAnnualLeasingCost() { bitField0_ = (bitField0_ & ~0x00000004); annualLeasingCost_ = null; if (annualLeasingCostBuilder_ != null) { annualLeasingCostBuilder_.dispose(); annualLeasingCostBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ public com.google.type.Money.Builder getAnnualLeasingCostBuilder() { bitField0_ |= 0x00000004; onChanged(); return getAnnualLeasingCostFieldBuilder().getBuilder(); } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ public com.google.type.MoneyOrBuilder getAnnualLeasingCostOrBuilder() { if (annualLeasingCostBuilder_ != null) { return annualLeasingCostBuilder_.getMessageOrBuilder(); } else { return annualLeasingCost_ == null ? com.google.type.Money.getDefaultInstance() : annualLeasingCost_; } } /** * * * <pre> * Estimated annual leasing cost. * </pre> * * <code>.google.type.Money annual_leasing_cost = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder> getAnnualLeasingCostFieldBuilder() { if (annualLeasingCostBuilder_ == null) { annualLeasingCostBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.type.Money, com.google.type.Money.Builder, com.google.type.MoneyOrBuilder>( getAnnualLeasingCost(), getParentForChildren(), isClean()); annualLeasingCost_ = null; } return annualLeasingCostBuilder_; } private com.google.maps.solar.v1.SavingsOverTime savings_; private com.google.protobuf.SingleFieldBuilderV3< com.google.maps.solar.v1.SavingsOverTime, com.google.maps.solar.v1.SavingsOverTime.Builder, com.google.maps.solar.v1.SavingsOverTimeOrBuilder> savingsBuilder_; /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> * * @return Whether the savings field is set. */ public boolean hasSavings() { return ((bitField0_ & 0x00000008) != 0); } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> * * @return The savings. */ public com.google.maps.solar.v1.SavingsOverTime getSavings() { if (savingsBuilder_ == null) { return savings_ == null ? com.google.maps.solar.v1.SavingsOverTime.getDefaultInstance() : savings_; } else { return savingsBuilder_.getMessage(); } } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ public Builder setSavings(com.google.maps.solar.v1.SavingsOverTime value) { if (savingsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } savings_ = value; } else { savingsBuilder_.setMessage(value); } bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ public Builder setSavings(com.google.maps.solar.v1.SavingsOverTime.Builder builderForValue) { if (savingsBuilder_ == null) { savings_ = builderForValue.build(); } else { savingsBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ public Builder mergeSavings(com.google.maps.solar.v1.SavingsOverTime value) { if (savingsBuilder_ == null) { if (((bitField0_ & 0x00000008) != 0) && savings_ != null && savings_ != com.google.maps.solar.v1.SavingsOverTime.getDefaultInstance()) { getSavingsBuilder().mergeFrom(value); } else { savings_ = value; } } else { savingsBuilder_.mergeFrom(value); } if (savings_ != null) { bitField0_ |= 0x00000008; onChanged(); } return this; } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ public Builder clearSavings() { bitField0_ = (bitField0_ & ~0x00000008); savings_ = null; if (savingsBuilder_ != null) { savingsBuilder_.dispose(); savingsBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ public com.google.maps.solar.v1.SavingsOverTime.Builder getSavingsBuilder() { bitField0_ |= 0x00000008; onChanged(); return getSavingsFieldBuilder().getBuilder(); } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ public com.google.maps.solar.v1.SavingsOverTimeOrBuilder getSavingsOrBuilder() { if (savingsBuilder_ != null) { return savingsBuilder_.getMessageOrBuilder(); } else { return savings_ == null ? com.google.maps.solar.v1.SavingsOverTime.getDefaultInstance() : savings_; } } /** * * * <pre> * How much is saved (or not) over the lifetime period. * </pre> * * <code>.google.maps.solar.v1.SavingsOverTime savings = 4;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.maps.solar.v1.SavingsOverTime, com.google.maps.solar.v1.SavingsOverTime.Builder, com.google.maps.solar.v1.SavingsOverTimeOrBuilder> getSavingsFieldBuilder() { if (savingsBuilder_ == null) { savingsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.maps.solar.v1.SavingsOverTime, com.google.maps.solar.v1.SavingsOverTime.Builder, com.google.maps.solar.v1.SavingsOverTimeOrBuilder>( getSavings(), getParentForChildren(), isClean()); savings_ = null; } return savingsBuilder_; } @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.maps.solar.v1.LeasingSavings) } // @@protoc_insertion_point(class_scope:google.maps.solar.v1.LeasingSavings) private static final com.google.maps.solar.v1.LeasingSavings DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.maps.solar.v1.LeasingSavings(); } public static com.google.maps.solar.v1.LeasingSavings getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<LeasingSavings> PARSER = new com.google.protobuf.AbstractParser<LeasingSavings>() { @java.lang.Override public LeasingSavings 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<LeasingSavings> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<LeasingSavings> getParserForType() { return PARSER; } @java.lang.Override public com.google.maps.solar.v1.LeasingSavings getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,652
java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListEntityTypesResponse.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/featurestore_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1; /** * * * <pre> * Response message for * [FeaturestoreService.ListEntityTypes][google.cloud.aiplatform.v1.FeaturestoreService.ListEntityTypes]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListEntityTypesResponse} */ public final class ListEntityTypesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListEntityTypesResponse) ListEntityTypesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListEntityTypesResponse.newBuilder() to construct. private ListEntityTypesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEntityTypesResponse() { entityTypes_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEntityTypesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListEntityTypesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListEntityTypesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListEntityTypesResponse.class, com.google.cloud.aiplatform.v1.ListEntityTypesResponse.Builder.class); } public static final int ENTITY_TYPES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1.EntityType> entityTypes_; /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1.EntityType> getEntityTypesList() { return entityTypes_; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1.EntityTypeOrBuilder> getEntityTypesOrBuilderList() { return entityTypes_; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ @java.lang.Override public int getEntityTypesCount() { return entityTypes_.size(); } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.EntityType getEntityTypes(int index) { return entityTypes_.get(index); } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.EntityTypeOrBuilder getEntityTypesOrBuilder(int index) { return entityTypes_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < entityTypes_.size(); i++) { output.writeMessage(1, entityTypes_.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 < entityTypes_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entityTypes_.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.ListEntityTypesResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.ListEntityTypesResponse other = (com.google.cloud.aiplatform.v1.ListEntityTypesResponse) obj; if (!getEntityTypesList().equals(other.getEntityTypesList())) 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 (getEntityTypesCount() > 0) { hash = (37 * hash) + ENTITY_TYPES_FIELD_NUMBER; hash = (53 * hash) + getEntityTypesList().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.ListEntityTypesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListEntityTypesResponse 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.ListEntityTypesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListEntityTypesResponse 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.ListEntityTypesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.ListEntityTypesResponse 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.ListEntityTypesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListEntityTypesResponse 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.ListEntityTypesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.ListEntityTypesResponse 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.ListEntityTypesResponse 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.ListEntityTypesResponse 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.ListEntityTypesResponse 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 * [FeaturestoreService.ListEntityTypes][google.cloud.aiplatform.v1.FeaturestoreService.ListEntityTypes]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.ListEntityTypesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListEntityTypesResponse) com.google.cloud.aiplatform.v1.ListEntityTypesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListEntityTypesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListEntityTypesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.ListEntityTypesResponse.class, com.google.cloud.aiplatform.v1.ListEntityTypesResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.ListEntityTypesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (entityTypesBuilder_ == null) { entityTypes_ = java.util.Collections.emptyList(); } else { entityTypes_ = null; entityTypesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.FeaturestoreServiceProto .internal_static_google_cloud_aiplatform_v1_ListEntityTypesResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListEntityTypesResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.ListEntityTypesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.ListEntityTypesResponse build() { com.google.cloud.aiplatform.v1.ListEntityTypesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListEntityTypesResponse buildPartial() { com.google.cloud.aiplatform.v1.ListEntityTypesResponse result = new com.google.cloud.aiplatform.v1.ListEntityTypesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1.ListEntityTypesResponse result) { if (entityTypesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { entityTypes_ = java.util.Collections.unmodifiableList(entityTypes_); bitField0_ = (bitField0_ & ~0x00000001); } result.entityTypes_ = entityTypes_; } else { result.entityTypes_ = entityTypesBuilder_.build(); } } private void buildPartial0(com.google.cloud.aiplatform.v1.ListEntityTypesResponse 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.ListEntityTypesResponse) { return mergeFrom((com.google.cloud.aiplatform.v1.ListEntityTypesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListEntityTypesResponse other) { if (other == com.google.cloud.aiplatform.v1.ListEntityTypesResponse.getDefaultInstance()) return this; if (entityTypesBuilder_ == null) { if (!other.entityTypes_.isEmpty()) { if (entityTypes_.isEmpty()) { entityTypes_ = other.entityTypes_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEntityTypesIsMutable(); entityTypes_.addAll(other.entityTypes_); } onChanged(); } } else { if (!other.entityTypes_.isEmpty()) { if (entityTypesBuilder_.isEmpty()) { entityTypesBuilder_.dispose(); entityTypesBuilder_ = null; entityTypes_ = other.entityTypes_; bitField0_ = (bitField0_ & ~0x00000001); entityTypesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntityTypesFieldBuilder() : null; } else { entityTypesBuilder_.addAllMessages(other.entityTypes_); } } } 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.EntityType m = input.readMessage( com.google.cloud.aiplatform.v1.EntityType.parser(), extensionRegistry); if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.add(m); } else { entityTypesBuilder_.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.EntityType> entityTypes_ = java.util.Collections.emptyList(); private void ensureEntityTypesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { entityTypes_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1.EntityType>(entityTypes_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.EntityType, com.google.cloud.aiplatform.v1.EntityType.Builder, com.google.cloud.aiplatform.v1.EntityTypeOrBuilder> entityTypesBuilder_; /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.EntityType> getEntityTypesList() { if (entityTypesBuilder_ == null) { return java.util.Collections.unmodifiableList(entityTypes_); } else { return entityTypesBuilder_.getMessageList(); } } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public int getEntityTypesCount() { if (entityTypesBuilder_ == null) { return entityTypes_.size(); } else { return entityTypesBuilder_.getCount(); } } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public com.google.cloud.aiplatform.v1.EntityType getEntityTypes(int index) { if (entityTypesBuilder_ == null) { return entityTypes_.get(index); } else { return entityTypesBuilder_.getMessage(index); } } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder setEntityTypes(int index, com.google.cloud.aiplatform.v1.EntityType value) { if (entityTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntityTypesIsMutable(); entityTypes_.set(index, value); onChanged(); } else { entityTypesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder setEntityTypes( int index, com.google.cloud.aiplatform.v1.EntityType.Builder builderForValue) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.set(index, builderForValue.build()); onChanged(); } else { entityTypesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes(com.google.cloud.aiplatform.v1.EntityType value) { if (entityTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntityTypesIsMutable(); entityTypes_.add(value); onChanged(); } else { entityTypesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes(int index, com.google.cloud.aiplatform.v1.EntityType value) { if (entityTypesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntityTypesIsMutable(); entityTypes_.add(index, value); onChanged(); } else { entityTypesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes( com.google.cloud.aiplatform.v1.EntityType.Builder builderForValue) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.add(builderForValue.build()); onChanged(); } else { entityTypesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder addEntityTypes( int index, com.google.cloud.aiplatform.v1.EntityType.Builder builderForValue) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.add(index, builderForValue.build()); onChanged(); } else { entityTypesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder addAllEntityTypes( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.EntityType> values) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entityTypes_); onChanged(); } else { entityTypesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder clearEntityTypes() { if (entityTypesBuilder_ == null) { entityTypes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { entityTypesBuilder_.clear(); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public Builder removeEntityTypes(int index) { if (entityTypesBuilder_ == null) { ensureEntityTypesIsMutable(); entityTypes_.remove(index); onChanged(); } else { entityTypesBuilder_.remove(index); } return this; } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public com.google.cloud.aiplatform.v1.EntityType.Builder getEntityTypesBuilder(int index) { return getEntityTypesFieldBuilder().getBuilder(index); } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public com.google.cloud.aiplatform.v1.EntityTypeOrBuilder getEntityTypesOrBuilder(int index) { if (entityTypesBuilder_ == null) { return entityTypes_.get(index); } else { return entityTypesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1.EntityTypeOrBuilder> getEntityTypesOrBuilderList() { if (entityTypesBuilder_ != null) { return entityTypesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(entityTypes_); } } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public com.google.cloud.aiplatform.v1.EntityType.Builder addEntityTypesBuilder() { return getEntityTypesFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1.EntityType.getDefaultInstance()); } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public com.google.cloud.aiplatform.v1.EntityType.Builder addEntityTypesBuilder(int index) { return getEntityTypesFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1.EntityType.getDefaultInstance()); } /** * * * <pre> * The EntityTypes matching the request. * </pre> * * <code>repeated .google.cloud.aiplatform.v1.EntityType entity_types = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1.EntityType.Builder> getEntityTypesBuilderList() { return getEntityTypesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.EntityType, com.google.cloud.aiplatform.v1.EntityType.Builder, com.google.cloud.aiplatform.v1.EntityTypeOrBuilder> getEntityTypesFieldBuilder() { if (entityTypesBuilder_ == null) { entityTypesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1.EntityType, com.google.cloud.aiplatform.v1.EntityType.Builder, com.google.cloud.aiplatform.v1.EntityTypeOrBuilder>( entityTypes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); entityTypes_ = null; } return entityTypesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as * [ListEntityTypesRequest.page_token][google.cloud.aiplatform.v1.ListEntityTypesRequest.page_token] * to retrieve the next page. If this field is omitted, there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.ListEntityTypesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListEntityTypesResponse) private static final com.google.cloud.aiplatform.v1.ListEntityTypesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListEntityTypesResponse(); } public static com.google.cloud.aiplatform.v1.ListEntityTypesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEntityTypesResponse> PARSER = new com.google.protobuf.AbstractParser<ListEntityTypesResponse>() { @java.lang.Override public ListEntityTypesResponse 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<ListEntityTypesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEntityTypesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.ListEntityTypesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,601
java-telcoautomation/proto-google-cloud-telcoautomation-v1alpha1/src/main/java/com/google/cloud/telcoautomation/v1alpha1/CreateDeploymentRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/telcoautomation/v1alpha1/telcoautomation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.telcoautomation.v1alpha1; /** * * * <pre> * Request object for `CreateDeployment`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest} */ public final class CreateDeploymentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest) CreateDeploymentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateDeploymentRequest.newBuilder() to construct. private CreateDeploymentRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateDeploymentRequest() { parent_ = ""; deploymentId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateDeploymentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateDeploymentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateDeploymentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.class, com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </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 DEPLOYMENT_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object deploymentId_ = ""; /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The deploymentId. */ @java.lang.Override public java.lang.String getDeploymentId() { java.lang.Object ref = deploymentId_; 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(); deploymentId_ = s; return s; } } /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for deploymentId. */ @java.lang.Override public com.google.protobuf.ByteString getDeploymentIdBytes() { java.lang.Object ref = deploymentId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); deploymentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DEPLOYMENT_FIELD_NUMBER = 3; private com.google.cloud.telcoautomation.v1alpha1.Deployment deployment_; /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the deployment field is set. */ @java.lang.Override public boolean hasDeployment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The deployment. */ @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.Deployment getDeployment() { return deployment_ == null ? com.google.cloud.telcoautomation.v1alpha1.Deployment.getDefaultInstance() : deployment_; } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.DeploymentOrBuilder getDeploymentOrBuilder() { return deployment_ == null ? com.google.cloud.telcoautomation.v1alpha1.Deployment.getDefaultInstance() : deployment_; } 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(deploymentId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, deploymentId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getDeployment()); } 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(deploymentId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, deploymentId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getDeployment()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest)) { return super.equals(obj); } com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest other = (com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getDeploymentId().equals(other.getDeploymentId())) return false; if (hasDeployment() != other.hasDeployment()) return false; if (hasDeployment()) { if (!getDeployment().equals(other.getDeployment())) 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) + DEPLOYMENT_ID_FIELD_NUMBER; hash = (53 * hash) + getDeploymentId().hashCode(); if (hasDeployment()) { hash = (37 * hash) + DEPLOYMENT_FIELD_NUMBER; hash = (53 * hash) + getDeployment().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest 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 object for `CreateDeployment`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest) com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateDeploymentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateDeploymentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.class, com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.Builder.class); } // Construct using // com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getDeploymentFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; deploymentId_ = ""; deployment_ = null; if (deploymentBuilder_ != null) { deploymentBuilder_.dispose(); deploymentBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.telcoautomation.v1alpha1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1alpha1_CreateDeploymentRequest_descriptor; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest getDefaultInstanceForType() { return com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest build() { com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest buildPartial() { com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest result = new com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.deploymentId_ = deploymentId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.deployment_ = deploymentBuilder_ == null ? deployment_ : deploymentBuilder_.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.telcoautomation.v1alpha1.CreateDeploymentRequest) { return mergeFrom((com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest other) { if (other == com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getDeploymentId().isEmpty()) { deploymentId_ = other.deploymentId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasDeployment()) { mergeDeployment(other.getDeployment()); } 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: { deploymentId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getDeploymentFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The name of parent resource. * Format should be - * "projects/{project_id}/locations/{location_name}/orchestrationClusters/{orchestration_cluster}". * </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 deploymentId_ = ""; /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The deploymentId. */ public java.lang.String getDeploymentId() { java.lang.Object ref = deploymentId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); deploymentId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for deploymentId. */ public com.google.protobuf.ByteString getDeploymentIdBytes() { java.lang.Object ref = deploymentId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); deploymentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The deploymentId to set. * @return This builder for chaining. */ public Builder setDeploymentId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } deploymentId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearDeploymentId() { deploymentId_ = getDefaultInstance().getDeploymentId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. The name of the deployment. * </pre> * * <code>string deployment_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for deploymentId to set. * @return This builder for chaining. */ public Builder setDeploymentIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); deploymentId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.telcoautomation.v1alpha1.Deployment deployment_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Deployment, com.google.cloud.telcoautomation.v1alpha1.Deployment.Builder, com.google.cloud.telcoautomation.v1alpha1.DeploymentOrBuilder> deploymentBuilder_; /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the deployment field is set. */ public boolean hasDeployment() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The deployment. */ public com.google.cloud.telcoautomation.v1alpha1.Deployment getDeployment() { if (deploymentBuilder_ == null) { return deployment_ == null ? com.google.cloud.telcoautomation.v1alpha1.Deployment.getDefaultInstance() : deployment_; } else { return deploymentBuilder_.getMessage(); } } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDeployment(com.google.cloud.telcoautomation.v1alpha1.Deployment value) { if (deploymentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } deployment_ = value; } else { deploymentBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setDeployment( com.google.cloud.telcoautomation.v1alpha1.Deployment.Builder builderForValue) { if (deploymentBuilder_ == null) { deployment_ = builderForValue.build(); } else { deploymentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeDeployment(com.google.cloud.telcoautomation.v1alpha1.Deployment value) { if (deploymentBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && deployment_ != null && deployment_ != com.google.cloud.telcoautomation.v1alpha1.Deployment.getDefaultInstance()) { getDeploymentBuilder().mergeFrom(value); } else { deployment_ = value; } } else { deploymentBuilder_.mergeFrom(value); } if (deployment_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearDeployment() { bitField0_ = (bitField0_ & ~0x00000004); deployment_ = null; if (deploymentBuilder_ != null) { deploymentBuilder_.dispose(); deploymentBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.telcoautomation.v1alpha1.Deployment.Builder getDeploymentBuilder() { bitField0_ |= 0x00000004; onChanged(); return getDeploymentFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.telcoautomation.v1alpha1.DeploymentOrBuilder getDeploymentOrBuilder() { if (deploymentBuilder_ != null) { return deploymentBuilder_.getMessageOrBuilder(); } else { return deployment_ == null ? com.google.cloud.telcoautomation.v1alpha1.Deployment.getDefaultInstance() : deployment_; } } /** * * * <pre> * Required. The `Deployment` to create. * </pre> * * <code> * .google.cloud.telcoautomation.v1alpha1.Deployment deployment = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Deployment, com.google.cloud.telcoautomation.v1alpha1.Deployment.Builder, com.google.cloud.telcoautomation.v1alpha1.DeploymentOrBuilder> getDeploymentFieldBuilder() { if (deploymentBuilder_ == null) { deploymentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1alpha1.Deployment, com.google.cloud.telcoautomation.v1alpha1.Deployment.Builder, com.google.cloud.telcoautomation.v1alpha1.DeploymentOrBuilder>( getDeployment(), getParentForChildren(), isClean()); deployment_ = null; } return deploymentBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest) private static final com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest(); } public static com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateDeploymentRequest> PARSER = new com.google.protobuf.AbstractParser<CreateDeploymentRequest>() { @java.lang.Override public CreateDeploymentRequest 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<CreateDeploymentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateDeploymentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.telcoautomation.v1alpha1.CreateDeploymentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,642
java-contentwarehouse/proto-google-cloud-contentwarehouse-v1/src/main/java/com/google/cloud/contentwarehouse/v1/ListSynonymSetsResponse.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/synonymset_service_request.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.contentwarehouse.v1; /** * * * <pre> * Response message for SynonymSetService.ListSynonymSets. * </pre> * * Protobuf type {@code google.cloud.contentwarehouse.v1.ListSynonymSetsResponse} */ public final class ListSynonymSetsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.contentwarehouse.v1.ListSynonymSetsResponse) ListSynonymSetsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListSynonymSetsResponse.newBuilder() to construct. private ListSynonymSetsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSynonymSetsResponse() { synonymSets_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSynonymSetsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.contentwarehouse.v1.SynonymSetServiceRequestProto .internal_static_google_cloud_contentwarehouse_v1_ListSynonymSetsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.contentwarehouse.v1.SynonymSetServiceRequestProto .internal_static_google_cloud_contentwarehouse_v1_ListSynonymSetsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.class, com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.Builder.class); } public static final int SYNONYM_SETS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.contentwarehouse.v1.SynonymSet> synonymSets_; /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.contentwarehouse.v1.SynonymSet> getSynonymSetsList() { return synonymSets_; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder> getSynonymSetsOrBuilderList() { return synonymSets_; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ @java.lang.Override public int getSynonymSetsCount() { return synonymSets_.size(); } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ @java.lang.Override public com.google.cloud.contentwarehouse.v1.SynonymSet getSynonymSets(int index) { return synonymSets_.get(index); } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ @java.lang.Override public com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder getSynonymSetsOrBuilder( int index) { return synonymSets_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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 page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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 < synonymSets_.size(); i++) { output.writeMessage(1, synonymSets_.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 < synonymSets_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, synonymSets_.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.contentwarehouse.v1.ListSynonymSetsResponse)) { return super.equals(obj); } com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse other = (com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse) obj; if (!getSynonymSetsList().equals(other.getSynonymSetsList())) 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 (getSynonymSetsCount() > 0) { hash = (37 * hash) + SYNONYM_SETS_FIELD_NUMBER; hash = (53 * hash) + getSynonymSetsList().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.contentwarehouse.v1.ListSynonymSetsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse 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.ListSynonymSetsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse 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.ListSynonymSetsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse 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.ListSynonymSetsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse 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.ListSynonymSetsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse 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.ListSynonymSetsResponse 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.ListSynonymSetsResponse 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.ListSynonymSetsResponse 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 SynonymSetService.ListSynonymSets. * </pre> * * Protobuf type {@code google.cloud.contentwarehouse.v1.ListSynonymSetsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.contentwarehouse.v1.ListSynonymSetsResponse) com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.contentwarehouse.v1.SynonymSetServiceRequestProto .internal_static_google_cloud_contentwarehouse_v1_ListSynonymSetsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.contentwarehouse.v1.SynonymSetServiceRequestProto .internal_static_google_cloud_contentwarehouse_v1_ListSynonymSetsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.class, com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.Builder.class); } // Construct using com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (synonymSetsBuilder_ == null) { synonymSets_ = java.util.Collections.emptyList(); } else { synonymSets_ = null; synonymSetsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.contentwarehouse.v1.SynonymSetServiceRequestProto .internal_static_google_cloud_contentwarehouse_v1_ListSynonymSetsResponse_descriptor; } @java.lang.Override public com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse getDefaultInstanceForType() { return com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse build() { com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse buildPartial() { com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse result = new com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse result) { if (synonymSetsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { synonymSets_ = java.util.Collections.unmodifiableList(synonymSets_); bitField0_ = (bitField0_ & ~0x00000001); } result.synonymSets_ = synonymSets_; } else { result.synonymSets_ = synonymSetsBuilder_.build(); } } private void buildPartial0( com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse 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.contentwarehouse.v1.ListSynonymSetsResponse) { return mergeFrom((com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse other) { if (other == com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse.getDefaultInstance()) return this; if (synonymSetsBuilder_ == null) { if (!other.synonymSets_.isEmpty()) { if (synonymSets_.isEmpty()) { synonymSets_ = other.synonymSets_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSynonymSetsIsMutable(); synonymSets_.addAll(other.synonymSets_); } onChanged(); } } else { if (!other.synonymSets_.isEmpty()) { if (synonymSetsBuilder_.isEmpty()) { synonymSetsBuilder_.dispose(); synonymSetsBuilder_ = null; synonymSets_ = other.synonymSets_; bitField0_ = (bitField0_ & ~0x00000001); synonymSetsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSynonymSetsFieldBuilder() : null; } else { synonymSetsBuilder_.addAllMessages(other.synonymSets_); } } } 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.contentwarehouse.v1.SynonymSet m = input.readMessage( com.google.cloud.contentwarehouse.v1.SynonymSet.parser(), extensionRegistry); if (synonymSetsBuilder_ == null) { ensureSynonymSetsIsMutable(); synonymSets_.add(m); } else { synonymSetsBuilder_.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.contentwarehouse.v1.SynonymSet> synonymSets_ = java.util.Collections.emptyList(); private void ensureSynonymSetsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { synonymSets_ = new java.util.ArrayList<com.google.cloud.contentwarehouse.v1.SynonymSet>(synonymSets_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.contentwarehouse.v1.SynonymSet, com.google.cloud.contentwarehouse.v1.SynonymSet.Builder, com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder> synonymSetsBuilder_; /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public java.util.List<com.google.cloud.contentwarehouse.v1.SynonymSet> getSynonymSetsList() { if (synonymSetsBuilder_ == null) { return java.util.Collections.unmodifiableList(synonymSets_); } else { return synonymSetsBuilder_.getMessageList(); } } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public int getSynonymSetsCount() { if (synonymSetsBuilder_ == null) { return synonymSets_.size(); } else { return synonymSetsBuilder_.getCount(); } } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public com.google.cloud.contentwarehouse.v1.SynonymSet getSynonymSets(int index) { if (synonymSetsBuilder_ == null) { return synonymSets_.get(index); } else { return synonymSetsBuilder_.getMessage(index); } } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder setSynonymSets( int index, com.google.cloud.contentwarehouse.v1.SynonymSet value) { if (synonymSetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSynonymSetsIsMutable(); synonymSets_.set(index, value); onChanged(); } else { synonymSetsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder setSynonymSets( int index, com.google.cloud.contentwarehouse.v1.SynonymSet.Builder builderForValue) { if (synonymSetsBuilder_ == null) { ensureSynonymSetsIsMutable(); synonymSets_.set(index, builderForValue.build()); onChanged(); } else { synonymSetsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder addSynonymSets(com.google.cloud.contentwarehouse.v1.SynonymSet value) { if (synonymSetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSynonymSetsIsMutable(); synonymSets_.add(value); onChanged(); } else { synonymSetsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder addSynonymSets( int index, com.google.cloud.contentwarehouse.v1.SynonymSet value) { if (synonymSetsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSynonymSetsIsMutable(); synonymSets_.add(index, value); onChanged(); } else { synonymSetsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder addSynonymSets( com.google.cloud.contentwarehouse.v1.SynonymSet.Builder builderForValue) { if (synonymSetsBuilder_ == null) { ensureSynonymSetsIsMutable(); synonymSets_.add(builderForValue.build()); onChanged(); } else { synonymSetsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder addSynonymSets( int index, com.google.cloud.contentwarehouse.v1.SynonymSet.Builder builderForValue) { if (synonymSetsBuilder_ == null) { ensureSynonymSetsIsMutable(); synonymSets_.add(index, builderForValue.build()); onChanged(); } else { synonymSetsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder addAllSynonymSets( java.lang.Iterable<? extends com.google.cloud.contentwarehouse.v1.SynonymSet> values) { if (synonymSetsBuilder_ == null) { ensureSynonymSetsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, synonymSets_); onChanged(); } else { synonymSetsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder clearSynonymSets() { if (synonymSetsBuilder_ == null) { synonymSets_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { synonymSetsBuilder_.clear(); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public Builder removeSynonymSets(int index) { if (synonymSetsBuilder_ == null) { ensureSynonymSetsIsMutable(); synonymSets_.remove(index); onChanged(); } else { synonymSetsBuilder_.remove(index); } return this; } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public com.google.cloud.contentwarehouse.v1.SynonymSet.Builder getSynonymSetsBuilder( int index) { return getSynonymSetsFieldBuilder().getBuilder(index); } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder getSynonymSetsOrBuilder( int index) { if (synonymSetsBuilder_ == null) { return synonymSets_.get(index); } else { return synonymSetsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public java.util.List<? extends com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder> getSynonymSetsOrBuilderList() { if (synonymSetsBuilder_ != null) { return synonymSetsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(synonymSets_); } } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public com.google.cloud.contentwarehouse.v1.SynonymSet.Builder addSynonymSetsBuilder() { return getSynonymSetsFieldBuilder() .addBuilder(com.google.cloud.contentwarehouse.v1.SynonymSet.getDefaultInstance()); } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public com.google.cloud.contentwarehouse.v1.SynonymSet.Builder addSynonymSetsBuilder( int index) { return getSynonymSetsFieldBuilder() .addBuilder(index, com.google.cloud.contentwarehouse.v1.SynonymSet.getDefaultInstance()); } /** * * * <pre> * The synonymSets from the specified parent. * </pre> * * <code>repeated .google.cloud.contentwarehouse.v1.SynonymSet synonym_sets = 1;</code> */ public java.util.List<com.google.cloud.contentwarehouse.v1.SynonymSet.Builder> getSynonymSetsBuilderList() { return getSynonymSetsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.contentwarehouse.v1.SynonymSet, com.google.cloud.contentwarehouse.v1.SynonymSet.Builder, com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder> getSynonymSetsFieldBuilder() { if (synonymSetsBuilder_ == null) { synonymSetsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.contentwarehouse.v1.SynonymSet, com.google.cloud.contentwarehouse.v1.SynonymSet.Builder, com.google.cloud.contentwarehouse.v1.SynonymSetOrBuilder>( synonymSets_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); synonymSets_ = null; } return synonymSetsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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 page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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 page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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 page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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 page token, received from a previous `ListSynonymSets` call. * Provide this to retrieve the subsequent 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.contentwarehouse.v1.ListSynonymSetsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.contentwarehouse.v1.ListSynonymSetsResponse) private static final com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse(); } public static com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSynonymSetsResponse> PARSER = new com.google.protobuf.AbstractParser<ListSynonymSetsResponse>() { @java.lang.Override public ListSynonymSetsResponse 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<ListSynonymSetsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSynonymSetsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.contentwarehouse.v1.ListSynonymSetsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hbase
37,752
hbase-client/src/main/java/org/apache/hadoop/hbase/client/Scan.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.hbase.client; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.client.metrics.ScanMetrics; import org.apache.hadoop.hbase.filter.Filter; import org.apache.hadoop.hbase.filter.IncompatibleFilterException; import org.apache.hadoop.hbase.io.TimeRange; import org.apache.hadoop.hbase.security.access.Permission; import org.apache.hadoop.hbase.security.visibility.Authorizations; import org.apache.hadoop.hbase.util.Bytes; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Used to perform Scan operations. * <p> * All operations are identical to {@link Get} with the exception of instantiation. Rather than * specifying a single row, an optional startRow and stopRow may be defined. If rows are not * specified, the Scanner will iterate over all rows. * <p> * To get all columns from all rows of a Table, create an instance with no constraints; use the * {@link #Scan()} constructor. To constrain the scan to specific column families, call * {@link #addFamily(byte[]) addFamily} for each family to retrieve on your Scan instance. * <p> * To get specific columns, call {@link #addColumn(byte[], byte[]) addColumn} for each column to * retrieve. * <p> * To only retrieve columns within a specific range of version timestamps, call * {@link #setTimeRange(long, long) setTimeRange}. * <p> * To only retrieve columns with a specific timestamp, call {@link #setTimestamp(long) setTimestamp} * . * <p> * To limit the number of versions of each column to be returned, call {@link #readVersions(int)}. * <p> * To limit the maximum number of values returned for each call to next(), call * {@link #setBatch(int) setBatch}. * <p> * To add a filter, call {@link #setFilter(org.apache.hadoop.hbase.filter.Filter) setFilter}. * <p> * For small scan, it is deprecated in 2.0.0. Now we have a {@link #setLimit(int)} method in Scan * object which is used to tell RS how many rows we want. If the rows return reaches the limit, the * RS will close the RegionScanner automatically. And we will also fetch data when openScanner in * the new implementation, this means we can also finish a scan operation in one rpc call. And we * have also introduced a {@link #setReadType(ReadType)} method. You can use this method to tell RS * to use pread explicitly. * <p> * Expert: To explicitly disable server-side block caching for this scan, execute * {@link #setCacheBlocks(boolean)}. * <p> * <em>Note:</em> Usage alters Scan instances. Internally, attributes are updated as the Scan runs * and if enabled, metrics accumulate in the Scan instance. Be aware this is the case when you go to * clone a Scan instance or if you go to reuse a created Scan instance; safer is create a Scan * instance per usage. */ @InterfaceAudience.Public public class Scan extends Query { private static final Logger LOG = LoggerFactory.getLogger(Scan.class); private static final String RAW_ATTR = "_raw_"; private byte[] startRow = HConstants.EMPTY_START_ROW; private boolean includeStartRow = true; private byte[] stopRow = HConstants.EMPTY_END_ROW; private boolean includeStopRow = false; private int maxVersions = 1; private int batch = -1; /** * Partial {@link Result}s are {@link Result}s must be combined to form a complete {@link Result}. * The {@link Result}s had to be returned in fragments (i.e. as partials) because the size of the * cells in the row exceeded max result size on the server. Typically partial results will be * combined client side into complete results before being delivered to the caller. However, if * this flag is set, the caller is indicating that they do not mind seeing partial results (i.e. * they understand that the results returned from the Scanner may only represent part of a * particular row). In such a case, any attempt to combine the partials into a complete result on * the client side will be skipped, and the caller will be able to see the exact results returned * from the server. */ private boolean allowPartialResults = false; private int storeLimit = -1; private int storeOffset = 0; private static final String SCAN_ATTRIBUTES_METRICS_ENABLE = "scan.attributes.metrics.enable"; // If an application wants to use multiple scans over different tables each scan must // define this attribute with the appropriate table name by calling // scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME, Bytes.toBytes(tableName)) static public final String SCAN_ATTRIBUTES_TABLE_NAME = "scan.attributes.table.name"; static private final String SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE = "scan.attributes.metrics.byregion.enable"; /** * -1 means no caching specified and the value of {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} * (default to {@link HConstants#DEFAULT_HBASE_CLIENT_SCANNER_CACHING}) will be used */ private int caching = -1; private long maxResultSize = -1; private boolean cacheBlocks = true; private boolean reversed = false; private TimeRange tr = TimeRange.allTime(); private Map<byte[], NavigableSet<byte[]>> familyMap = new TreeMap<byte[], NavigableSet<byte[]>>(Bytes.BYTES_COMPARATOR); private Boolean asyncPrefetch = null; /** * Parameter name for client scanner sync/async prefetch toggle. When using async scanner, * prefetching data from the server is done at the background. The parameter currently won't have * any effect in the case that the user has set Scan#setSmall or Scan#setReversed */ public static final String HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = "hbase.client.scanner.async.prefetch"; /** * Default value of {@link #HBASE_CLIENT_SCANNER_ASYNC_PREFETCH}. */ public static final boolean DEFAULT_HBASE_CLIENT_SCANNER_ASYNC_PREFETCH = false; /** * The mvcc read point to use when open a scanner. Remember to clear it after switching regions as * the mvcc is only valid within region scope. */ private long mvccReadPoint = -1L; /** * The number of rows we want for this scan. We will terminate the scan if the number of return * rows reaches this value. */ private int limit = -1; /** * Control whether to use pread at server side. */ private ReadType readType = ReadType.DEFAULT; private boolean needCursorResult = false; /** * Create a Scan operation across all rows. */ public Scan() { } /** * Creates a new instance of this class while copying all values. * @param scan The scan instance to copy from. * @throws IOException When copying the values fails. */ public Scan(Scan scan) throws IOException { startRow = scan.getStartRow(); includeStartRow = scan.includeStartRow(); stopRow = scan.getStopRow(); includeStopRow = scan.includeStopRow(); maxVersions = scan.getMaxVersions(); batch = scan.getBatch(); storeLimit = scan.getMaxResultsPerColumnFamily(); storeOffset = scan.getRowOffsetPerColumnFamily(); caching = scan.getCaching(); maxResultSize = scan.getMaxResultSize(); cacheBlocks = scan.getCacheBlocks(); filter = scan.getFilter(); // clone? loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue(); consistency = scan.getConsistency(); this.setIsolationLevel(scan.getIsolationLevel()); reversed = scan.isReversed(); asyncPrefetch = scan.isAsyncPrefetch(); allowPartialResults = scan.getAllowPartialResults(); tr = scan.getTimeRange(); // TimeRange is immutable Map<byte[], NavigableSet<byte[]>> fams = scan.getFamilyMap(); for (Map.Entry<byte[], NavigableSet<byte[]>> entry : fams.entrySet()) { byte[] fam = entry.getKey(); NavigableSet<byte[]> cols = entry.getValue(); if (cols != null && cols.size() > 0) { for (byte[] col : cols) { addColumn(fam, col); } } else { addFamily(fam); } } for (Map.Entry<String, byte[]> attr : scan.getAttributesMap().entrySet()) { setAttribute(attr.getKey(), attr.getValue()); } for (Map.Entry<byte[], TimeRange> entry : scan.getColumnFamilyTimeRange().entrySet()) { TimeRange tr = entry.getValue(); setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); } this.mvccReadPoint = scan.getMvccReadPoint(); this.limit = scan.getLimit(); this.needCursorResult = scan.isNeedCursorResult(); setPriority(scan.getPriority()); readType = scan.getReadType(); super.setReplicaId(scan.getReplicaId()); super.setQueryMetricsEnabled(scan.isQueryMetricsEnabled()); } /** * Builds a scan object with the same specs as get. * @param get get to model scan after */ public Scan(Get get) { this.startRow = get.getRow(); this.includeStartRow = true; this.stopRow = get.getRow(); this.includeStopRow = true; this.filter = get.getFilter(); this.cacheBlocks = get.getCacheBlocks(); this.maxVersions = get.getMaxVersions(); this.storeLimit = get.getMaxResultsPerColumnFamily(); this.storeOffset = get.getRowOffsetPerColumnFamily(); this.tr = get.getTimeRange(); this.familyMap = get.getFamilyMap(); this.asyncPrefetch = false; this.consistency = get.getConsistency(); this.setIsolationLevel(get.getIsolationLevel()); this.loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue(); for (Map.Entry<String, byte[]> attr : get.getAttributesMap().entrySet()) { setAttribute(attr.getKey(), attr.getValue()); } for (Map.Entry<byte[], TimeRange> entry : get.getColumnFamilyTimeRange().entrySet()) { TimeRange tr = entry.getValue(); setColumnFamilyTimeRange(entry.getKey(), tr.getMin(), tr.getMax()); } this.mvccReadPoint = -1L; setPriority(get.getPriority()); super.setReplicaId(get.getReplicaId()); super.setQueryMetricsEnabled(get.isQueryMetricsEnabled()); } public boolean isGetScan() { return includeStartRow && includeStopRow && ClientUtil.areScanStartRowAndStopRowEqual(this.startRow, this.stopRow); } /** * Get all columns from the specified family. * <p> * Overrides previous calls to addColumn for this family. * @param family family name */ public Scan addFamily(byte[] family) { familyMap.remove(family); familyMap.put(family, null); return this; } /** * Get the column from the specified family with the specified qualifier. * <p> * Overrides previous calls to addFamily for this family. * @param family family name * @param qualifier column qualifier */ public Scan addColumn(byte[] family, byte[] qualifier) { NavigableSet<byte[]> set = familyMap.get(family); if (set == null) { set = new TreeSet<>(Bytes.BYTES_COMPARATOR); familyMap.put(family, set); } if (qualifier == null) { qualifier = HConstants.EMPTY_BYTE_ARRAY; } set.add(qualifier); return this; } /** * Get versions of columns only within the specified timestamp range, [minStamp, maxStamp). Note, * default maximum versions to return is 1. If your time range spans more than one version and you * want all versions returned, up the number of versions beyond the default. * @param minStamp minimum timestamp value, inclusive * @param maxStamp maximum timestamp value, exclusive * @see #readAllVersions() * @see #readVersions(int) */ public Scan setTimeRange(long minStamp, long maxStamp) throws IOException { tr = TimeRange.between(minStamp, maxStamp); return this; } /** * Get versions of columns with the specified timestamp. Note, default maximum versions to return * is 1. If your time range spans more than one version and you want all versions returned, up the * number of versions beyond the defaut. * @param timestamp version timestamp * @see #readAllVersions() * @see #readVersions(int) */ public Scan setTimestamp(long timestamp) { try { tr = TimeRange.at(timestamp); } catch (Exception e) { // This should never happen, unless integer overflow or something extremely wrong... LOG.error("TimeRange failed, likely caused by integer overflow. ", e); throw e; } return this; } @Override public Scan setColumnFamilyTimeRange(byte[] cf, long minStamp, long maxStamp) { super.setColumnFamilyTimeRange(cf, minStamp, maxStamp); return this; } /** * Set the start row of the scan. * <p> * If the specified row does not exist, the Scanner will start from the next closest row after the * specified row. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param startRow row to start scanner at or after * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStartRow(byte[] startRow) { return withStartRow(startRow, true); } /** * Set the start row of the scan. * <p> * If the specified row does not exist, or the {@code inclusive} is {@code false}, the Scanner * will start from the next closest row after the specified row. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param startRow row to start scanner at or after * @param inclusive whether we should include the start row when scan * @throws IllegalArgumentException if startRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStartRow(byte[] startRow, boolean inclusive) { if (Bytes.len(startRow) > HConstants.MAX_ROW_LENGTH) { throw new IllegalArgumentException("startRow's length must be less than or equal to " + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key."); } this.startRow = startRow; this.includeStartRow = inclusive; return this; } /** * Set the stop row of the scan. * <p> * The scan will include rows that are lexicographically less than the provided stopRow. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param stopRow row to end at (exclusive) * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStopRow(byte[] stopRow) { return withStopRow(stopRow, false); } /** * Set the stop row of the scan. * <p> * The scan will include rows that are lexicographically less than (or equal to if * {@code inclusive} is {@code true}) the provided stopRow. * <p> * <b>Note:</b> <strong>Do NOT use this in combination with {@link #setRowPrefixFilter(byte[])} or * {@link #setStartStopRowForPrefixScan(byte[])}.</strong> Doing so will make the scan result * unexpected or even undefined. * </p> * @param stopRow row to end at * @param inclusive whether we should include the stop row when scan * @throws IllegalArgumentException if stopRow does not meet criteria for a row key (when length * exceeds {@link HConstants#MAX_ROW_LENGTH}) */ public Scan withStopRow(byte[] stopRow, boolean inclusive) { if (Bytes.len(stopRow) > HConstants.MAX_ROW_LENGTH) { throw new IllegalArgumentException("stopRow's length must be less than or equal to " + HConstants.MAX_ROW_LENGTH + " to meet the criteria" + " for a row key."); } this.stopRow = stopRow; this.includeStopRow = inclusive; return this; } /** * <p> * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey * starts with the specified prefix. * </p> * <p> * This is a utility method that converts the desired rowPrefix into the appropriate values for * the startRow and stopRow to achieve the desired result. * </p> * <p> * This can safely be used in combination with setFilter. * </p> * <p> * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such * a combination will yield unexpected and even undefined results. * </p> * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.) * @deprecated since 2.5.0, will be removed in 4.0.0. The name of this method is considered to be * confusing as it does not use a {@link Filter} but uses setting the startRow and * stopRow instead. Use {@link #setStartStopRowForPrefixScan(byte[])} instead. */ @Deprecated public Scan setRowPrefixFilter(byte[] rowPrefix) { return setStartStopRowForPrefixScan(rowPrefix); } /** * <p> * Set a filter (using stopRow and startRow) so the result set only contains rows where the rowKey * starts with the specified prefix. * </p> * <p> * This is a utility method that converts the desired rowPrefix into the appropriate values for * the startRow and stopRow to achieve the desired result. * </p> * <p> * This can safely be used in combination with setFilter. * </p> * <p> * <strong>This CANNOT be used in combination with withStartRow and/or withStopRow.</strong> Such * a combination will yield unexpected and even undefined results. * </p> * @param rowPrefix the prefix all rows must start with. (Set <i>null</i> to remove the filter.) */ public Scan setStartStopRowForPrefixScan(byte[] rowPrefix) { if (rowPrefix == null) { withStartRow(HConstants.EMPTY_START_ROW); withStopRow(HConstants.EMPTY_END_ROW); } else { this.withStartRow(rowPrefix); this.withStopRow(ClientUtil.calculateTheClosestNextRowKeyForPrefix(rowPrefix)); } return this; } /** * Get all available versions. */ public Scan readAllVersions() { this.maxVersions = Integer.MAX_VALUE; return this; } /** * Get up to the specified number of versions of each column. * @param versions specified number of versions for each column */ public Scan readVersions(int versions) { this.maxVersions = versions; return this; } /** * Set the maximum number of cells to return for each call to next(). Callers should be aware that * this is not equivalent to calling {@link #setAllowPartialResults(boolean)}. If you don't allow * partial results, the number of cells in each Result must equal to your batch setting unless it * is the last Result for current row. So this method is helpful in paging queries. If you just * want to prevent OOM at client, use setAllowPartialResults(true) is better. * @param batch the maximum number of values * @see Result#mayHaveMoreCellsInRow() */ public Scan setBatch(int batch) { if (this.hasFilter() && this.filter.hasFilterRow()) { throw new IncompatibleFilterException( "Cannot set batch on a scan using a filter" + " that returns true for filter.hasFilterRow"); } this.batch = batch; return this; } /** * Set the maximum number of values to return per row per Column Family * @param limit the maximum number of values returned / row / CF */ public Scan setMaxResultsPerColumnFamily(int limit) { this.storeLimit = limit; return this; } /** * Set offset for the row per Column Family. * @param offset is the number of kvs that will be skipped. */ public Scan setRowOffsetPerColumnFamily(int offset) { this.storeOffset = offset; return this; } /** * Set the number of rows for caching that will be passed to scanners. If not set, the * Configuration setting {@link HConstants#HBASE_CLIENT_SCANNER_CACHING} will apply. Higher * caching values will enable faster scanners but will use more memory. * @param caching the number of rows for caching */ public Scan setCaching(int caching) { this.caching = caching; return this; } /** Returns the maximum result size in bytes. See {@link #setMaxResultSize(long)} */ public long getMaxResultSize() { return maxResultSize; } /** * Set the maximum result size. The default is -1; this means that no specific maximum result size * will be set for this scan, and the global configured value will be used instead. (Defaults to * unlimited). * @param maxResultSize The maximum result size in bytes. */ public Scan setMaxResultSize(long maxResultSize) { this.maxResultSize = maxResultSize; return this; } @Override public Scan setFilter(Filter filter) { super.setFilter(filter); return this; } /** * Setting the familyMap * @param familyMap map of family to qualifier */ public Scan setFamilyMap(Map<byte[], NavigableSet<byte[]>> familyMap) { this.familyMap = familyMap; return this; } /** * Getting the familyMap */ public Map<byte[], NavigableSet<byte[]>> getFamilyMap() { return this.familyMap; } /** Returns the number of families in familyMap */ public int numFamilies() { if (hasFamilies()) { return this.familyMap.size(); } return 0; } /** Returns true if familyMap is non empty, false otherwise */ public boolean hasFamilies() { return !this.familyMap.isEmpty(); } /** Returns the keys of the familyMap */ public byte[][] getFamilies() { if (hasFamilies()) { return this.familyMap.keySet().toArray(new byte[0][0]); } return null; } /** Returns the startrow */ public byte[] getStartRow() { return this.startRow; } /** Returns if we should include start row when scan */ public boolean includeStartRow() { return includeStartRow; } /** Returns the stoprow */ public byte[] getStopRow() { return this.stopRow; } /** Returns if we should include stop row when scan */ public boolean includeStopRow() { return includeStopRow; } /** Returns the max number of versions to fetch */ public int getMaxVersions() { return this.maxVersions; } /** Returns maximum number of values to return for a single call to next() */ public int getBatch() { return this.batch; } /** Returns maximum number of values to return per row per CF */ public int getMaxResultsPerColumnFamily() { return this.storeLimit; } /** * Method for retrieving the scan's offset per row per column family (#kvs to be skipped) * @return row offset */ public int getRowOffsetPerColumnFamily() { return this.storeOffset; } /** Returns caching the number of rows fetched when calling next on a scanner */ public int getCaching() { return this.caching; } /** Returns TimeRange */ public TimeRange getTimeRange() { return this.tr; } /** Returns RowFilter */ @Override public Filter getFilter() { return filter; } /** Returns true is a filter has been specified, false if not */ public boolean hasFilter() { return filter != null; } /** * Set whether blocks should be cached for this Scan. * <p> * This is true by default. When true, default settings of the table and family are used (this * will never override caching blocks if the block cache is disabled for that family or entirely). * @param cacheBlocks if false, default settings are overridden and blocks will not be cached */ public Scan setCacheBlocks(boolean cacheBlocks) { this.cacheBlocks = cacheBlocks; return this; } /** * Get whether blocks should be cached for this Scan. * @return true if default caching should be used, false if blocks should not be cached */ public boolean getCacheBlocks() { return cacheBlocks; } /** * Set whether this scan is a reversed one * <p> * This is false by default which means forward(normal) scan. * @param reversed if true, scan will be backward order */ public Scan setReversed(boolean reversed) { this.reversed = reversed; return this; } /** * Get whether this scan is a reversed one. * @return true if backward scan, false if forward(default) scan */ public boolean isReversed() { return reversed; } /** * Setting whether the caller wants to see the partial results when server returns * less-than-expected cells. It is helpful while scanning a huge row to prevent OOM at client. By * default this value is false and the complete results will be assembled client side before being * delivered to the caller. * @see Result#mayHaveMoreCellsInRow() * @see #setBatch(int) */ public Scan setAllowPartialResults(final boolean allowPartialResults) { this.allowPartialResults = allowPartialResults; return this; } /** * Returns true when the constructor of this scan understands that the results they will see may * only represent a partial portion of a row. The entire row would be retrieved by subsequent * calls to {@link ResultScanner#next()} */ public boolean getAllowPartialResults() { return allowPartialResults; } @Override public Scan setLoadColumnFamiliesOnDemand(boolean value) { super.setLoadColumnFamiliesOnDemand(value); return this; } /** * Compile the table and column family (i.e. schema) information into a String. Useful for parsing * and aggregation by debugging, logging, and administration tools. */ @Override public Map<String, Object> getFingerprint() { Map<String, Object> map = new HashMap<>(); List<String> families = new ArrayList<>(); if (this.familyMap.isEmpty()) { map.put("families", "ALL"); return map; } else { map.put("families", families); } for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { families.add(Bytes.toStringBinary(entry.getKey())); } return map; } /** * Compile the details beyond the scope of getFingerprint (row, columns, timestamps, etc.) into a * Map along with the fingerprinted information. Useful for debugging, logging, and administration * tools. * @param maxCols a limit on the number of columns output prior to truncation */ @Override public Map<String, Object> toMap(int maxCols) { // start with the fingerprint map and build on top of it Map<String, Object> map = getFingerprint(); // map from families to column list replaces fingerprint's list of families Map<String, List<String>> familyColumns = new HashMap<>(); map.put("families", familyColumns); // add scalar information first map.put("startRow", Bytes.toStringBinary(this.startRow)); map.put("stopRow", Bytes.toStringBinary(this.stopRow)); map.put("maxVersions", this.maxVersions); map.put("batch", this.batch); map.put("caching", this.caching); map.put("maxResultSize", this.maxResultSize); map.put("cacheBlocks", this.cacheBlocks); map.put("loadColumnFamiliesOnDemand", this.loadColumnFamiliesOnDemand); List<Long> timeRange = new ArrayList<>(2); timeRange.add(this.tr.getMin()); timeRange.add(this.tr.getMax()); map.put("timeRange", timeRange); int colCount = 0; // iterate through affected families and list out up to maxCols columns for (Map.Entry<byte[], NavigableSet<byte[]>> entry : this.familyMap.entrySet()) { List<String> columns = new ArrayList<>(); familyColumns.put(Bytes.toStringBinary(entry.getKey()), columns); if (entry.getValue() == null) { colCount++; --maxCols; columns.add("ALL"); } else { colCount += entry.getValue().size(); if (maxCols <= 0) { continue; } for (byte[] column : entry.getValue()) { if (--maxCols <= 0) { continue; } columns.add(Bytes.toStringBinary(column)); } } } map.put("totalColumns", colCount); if (this.filter != null) { map.put("filter", this.filter.toString()); } // add the id if set if (getId() != null) { map.put("id", getId()); } map.put("includeStartRow", includeStartRow); map.put("includeStopRow", includeStopRow); map.put("allowPartialResults", allowPartialResults); map.put("storeLimit", storeLimit); map.put("storeOffset", storeOffset); map.put("reversed", reversed); if (null != asyncPrefetch) { map.put("asyncPrefetch", asyncPrefetch); } map.put("mvccReadPoint", mvccReadPoint); map.put("limit", limit); map.put("readType", readType); map.put("needCursorResult", needCursorResult); map.put("targetReplicaId", targetReplicaId); map.put("consistency", consistency); if (!colFamTimeRangeMap.isEmpty()) { Map<String, List<Long>> colFamTimeRangeMapStr = colFamTimeRangeMap.entrySet().stream() .collect(Collectors.toMap((e) -> Bytes.toStringBinary(e.getKey()), e -> { TimeRange value = e.getValue(); List<Long> rangeList = new ArrayList<>(); rangeList.add(value.getMin()); rangeList.add(value.getMax()); return rangeList; })); map.put("colFamTimeRangeMap", colFamTimeRangeMapStr); } map.put("priority", getPriority()); map.put("queryMetricsEnabled", queryMetricsEnabled); return map; } /** * Enable/disable "raw" mode for this scan. If "raw" is enabled the scan will return all delete * marker and deleted rows that have not been collected, yet. This is mostly useful for Scan on * column families that have KEEP_DELETED_ROWS enabled. It is an error to specify any column when * "raw" is set. * @param raw True/False to enable/disable "raw" mode. */ public Scan setRaw(boolean raw) { setAttribute(RAW_ATTR, Bytes.toBytes(raw)); return this; } /** Returns True if this Scan is in "raw" mode. */ public boolean isRaw() { byte[] attr = getAttribute(RAW_ATTR); return attr == null ? false : Bytes.toBoolean(attr); } @Override public Scan setAttribute(String name, byte[] value) { super.setAttribute(name, value); return this; } @Override public Scan setId(String id) { super.setId(id); return this; } @Override public Scan setAuthorizations(Authorizations authorizations) { super.setAuthorizations(authorizations); return this; } @Override public Scan setACL(Map<String, Permission> perms) { super.setACL(perms); return this; } @Override public Scan setACL(String user, Permission perms) { super.setACL(user, perms); return this; } @Override public Scan setConsistency(Consistency consistency) { super.setConsistency(consistency); return this; } @Override public Scan setReplicaId(int Id) { super.setReplicaId(Id); return this; } @Override public Scan setIsolationLevel(IsolationLevel level) { super.setIsolationLevel(level); return this; } @Override public Scan setPriority(int priority) { super.setPriority(priority); return this; } /** * Enable collection of {@link ScanMetrics}. For advanced users. While disabling scan metrics, * will also disable region level scan metrics. * @param enabled Set to true to enable accumulating scan metrics */ public Scan setScanMetricsEnabled(final boolean enabled) { setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE, Bytes.toBytes(Boolean.valueOf(enabled))); if (!enabled) { setEnableScanMetricsByRegion(false); } return this; } /** Returns True if collection of scan metrics is enabled. For advanced users. */ public boolean isScanMetricsEnabled() { byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_ENABLE); return attr == null ? false : Bytes.toBoolean(attr); } public Boolean isAsyncPrefetch() { return asyncPrefetch; } /** * @deprecated Since 3.0.0, will be removed in 4.0.0. After building sync client upon async * client, the implementation is always 'async prefetch', so this flag is useless now. */ @Deprecated public Scan setAsyncPrefetch(boolean asyncPrefetch) { this.asyncPrefetch = asyncPrefetch; return this; } /** Returns the limit of rows for this scan */ public int getLimit() { return limit; } /** * Set the limit of rows for this scan. We will terminate the scan if the number of returned rows * reaches this value. * <p> * This condition will be tested at last, after all other conditions such as stopRow, filter, etc. * @param limit the limit of rows for this scan */ public Scan setLimit(int limit) { this.limit = limit; return this; } /** * Call this when you only want to get one row. It will set {@code limit} to {@code 1}, and also * set {@code readType} to {@link ReadType#PREAD}. */ public Scan setOneRowLimit() { return setLimit(1).setReadType(ReadType.PREAD); } @InterfaceAudience.Public public enum ReadType { DEFAULT, STREAM, PREAD } /** Returns the read type for this scan */ public ReadType getReadType() { return readType; } /** * Set the read type for this scan. * <p> * Notice that we may choose to use pread even if you specific {@link ReadType#STREAM} here. For * example, we will always use pread if this is a get scan. */ public Scan setReadType(ReadType readType) { this.readType = readType; return this; } /** * Get the mvcc read point used to open a scanner. */ long getMvccReadPoint() { return mvccReadPoint; } /** * Set the mvcc read point used to open a scanner. */ Scan setMvccReadPoint(long mvccReadPoint) { this.mvccReadPoint = mvccReadPoint; return this; } /** * Set the mvcc read point to -1 which means do not use it. */ Scan resetMvccReadPoint() { return setMvccReadPoint(-1L); } /** * When the server is slow or we scan a table with many deleted data or we use a sparse filter, * the server will response heartbeat to prevent timeout. However the scanner will return a Result * only when client can do it. So if there are many heartbeats, the blocking time on * ResultScanner#next() may be very long, which is not friendly to online services. Set this to * true then you can get a special Result whose #isCursor() returns true and is not contains any * real data. It only tells you where the server has scanned. You can call next to continue * scanning or open a new scanner with this row key as start row whenever you want. Users can get * a cursor when and only when there is a response from the server but we can not return a Result * to users, for example, this response is a heartbeat or there are partial cells but users do not * allow partial result. Now the cursor is in row level which means the special Result will only * contains a row key. {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor} */ public Scan setNeedCursorResult(boolean needCursorResult) { this.needCursorResult = needCursorResult; return this; } public boolean isNeedCursorResult() { return needCursorResult; } /** * Create a new Scan with a cursor. It only set the position information like start row key. The * others (like cfs, stop row, limit) should still be filled in by the user. * {@link Result#isCursor()} {@link Result#getCursor()} {@link Cursor} */ public static Scan createScanFromCursor(Cursor cursor) { return new Scan().withStartRow(cursor.getRow()); } /** * Enables region level scan metrics. If scan metrics are disabled then first enables scan metrics * followed by region level scan metrics. * @param enable Set to true to enable region level scan metrics. */ public Scan setEnableScanMetricsByRegion(final boolean enable) { if (enable) { setScanMetricsEnabled(true); } setAttribute(Scan.SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE, Bytes.toBytes(enable)); return this; } public boolean isScanMetricsByRegionEnabled() { byte[] attr = getAttribute(Scan.SCAN_ATTRIBUTES_METRICS_BY_REGION_ENABLE); return attr != null && Bytes.toBoolean(attr); } }
apache/royale-compiler
37,664
compiler-jx/src/main/java/com/google/javascript/jscomp/CollapsePropertiesWithModuleSupport.java
/* * Copyright 2006 The Closure Compiler Authors. * * 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.javascript.jscomp; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.io.Files; import com.google.javascript.jscomp.CompilerOptions.PropertyCollapseLevel; import com.google.javascript.jscomp.GlobalNamespace.Name; import com.google.javascript.jscomp.GlobalNamespace.Ref; import com.google.javascript.jscomp.Normalize.PropagateConstantAnnotationsOverVars; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.InputId; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import com.google.javascript.rhino.TokenStream; import com.google.javascript.rhino.jstype.JSType; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Apache Royale copied CollapseProperties and modified it to handle * Royale modules. * * Flattens global objects/namespaces by replacing each '.' with '$' in * their names. This reduces the number of property lookups the browser has * to do and allows the {@link RenameVars} pass to shorten namespaced names. * For example, goog.events.handleEvent() -> goog$events$handleEvent() -> Za(). * * <p>If a global object's name is assigned to more than once, or if a property * is added to the global object in a complex expression, then none of its * properties will be collapsed (for safety/correctness). * * <p>If, after a global object is declared, it is never referenced except when * its properties are read or set, then the object will be removed after its * properties have been collapsed. * * <p>Uninitialized variable stubs are created at a global object's declaration * site for any of its properties that are added late in a local scope. * * <p> Static properties of constructors are always collapsed, unsafely! * For other objects: if, after an object is declared, it is referenced directly * in a way that might create an alias for it, then none of its properties will * be collapsed. * This behavior is a safeguard to prevent the values associated with the * flattened names from getting out of sync with the object's actual property * values. For example, in the following case, an alias a$b, if created, could * easily keep the value 0 even after a.b became 5: * <code> a = {b: 0}; c = a; c.b = 5; </code>. * * <p>This pass doesn't flatten property accesses of the form: a[b]. * * <p>For lots of examples, see the unit test. * */ class CollapsePropertiesWithModuleSupport implements CompilerPass { // Warnings static final DiagnosticType UNSAFE_NAMESPACE_WARNING = DiagnosticType.warning( "JSC_UNSAFE_NAMESPACE", "incomplete alias created for namespace {0}"); static final DiagnosticType NAMESPACE_REDEFINED_WARNING = DiagnosticType.warning( "JSC_NAMESPACE_REDEFINED", "namespace {0} should not be redefined"); static final DiagnosticType UNSAFE_THIS = DiagnosticType.warning( "JSC_UNSAFE_THIS", "dangerous use of ''this'' in static method {0}"); private final AbstractCompiler compiler; private final PropertyCollapseLevel propertyCollapseLevel; /** Global namespace tree */ private List<Name> globalNames; /** Maps names (e.g. "a.b.c") to nodes in the global namespace tree */ private Map<String, Name> nameMap; /** name of a source file we can use to inject other code */ private String sourceFileName; /** name of the file of renamed variables */ private File varRenameMapFile; /** list of renamed variables */ private ArrayList<String> renamedVars = null; /** list of aliases that are also in externs */ private List<String> externAliases; /** list of aliases that came from goog.provides */ private List<String> providedAliases = new ArrayList<String>(); /** list of namespaces that came from goog.provides */ private List<String> providedNamespaces = new ArrayList<String>(); CollapsePropertiesWithModuleSupport(AbstractCompiler compiler, PropertyCollapseLevel propertyCollapseLevel, String sourceFileName, File varRenameMapFile) { this.compiler = compiler; this.propertyCollapseLevel = propertyCollapseLevel; this.varRenameMapFile = varRenameMapFile; this.sourceFileName = sourceFileName; } @Override public void process(Node externs, Node root) { // ProcessClosurePrimitives runs first and builds up an initial list of // namespaces from goog.provides that were also in externs. externAliases = ProcessClosurePrimitivesWithModuleSupport.externedAliases.get(externs); int n = externAliases.size(); for (int i = 0; i < n; i++) { String s = externAliases.get(i); String t = s.replace(".", "$"); externAliases.set(i, t); } // ProcessClosurePrimitives runs first and builds up an initial list of // namespaces from goog.provides. providedAliases = ProcessClosurePrimitivesWithModuleSupport.providedsMap.get(externs); providedNamespaces.addAll(providedAliases); n = providedAliases.size(); for (int i = 0; i < n; i++) { String s = providedAliases.get(i); String t = s.replace(".", "$"); providedAliases.set(i, t); } /* * The goal is to use knowledge of the aliases and which are externed * to eliminate warnings and allow aliases in more places than * closure compiler would normally. Closure compiler doesn't want to * collapse things found in externs, but we want to collapse * them to save size and need to collapse them when there are * overrides in the module of a collapsed property in code * in the main app. Or when the code in the main app is calling * via an interface and code in the module implements that * interface. */ GlobalNamespace namespace = new GlobalNamespace(compiler, externs, root); nameMap = namespace.getNameIndex(); globalNames = namespace.getNameForest(); checkNamespaces(); for (Name name : globalNames) { flattenReferencesToCollapsibleDescendantNames(name, name.getBaseName()); } // We collapse property definitions after collapsing property references // because this step can alter the parse tree above property references, // invalidating the node ancestry stored with each reference. for (Name name : globalNames) { collapseDeclarationOfNameAndDescendants(name, name.getBaseName()); } // This shouldn't be necessary, this pass should already be setting new constants as constant. // TODO(b/64256754): Investigate. (new PropagateConstantAnnotationsOverVars(compiler, false)).process(externs, root); } private boolean canCollapse(Name name) { if (!name.canCollapse()) { return false; } if (propertyCollapseLevel == PropertyCollapseLevel.MODULE_EXPORT && !name.isModuleExport()) { return false; } return true; } private boolean canEliminate(Name name) { if (!name.canEliminate()) { return false; } if (name.props == null || name.props.isEmpty() || propertyCollapseLevel != PropertyCollapseLevel.MODULE_EXPORT) { return true; } return false; } /** * Runs through all namespaces (prefixes of classes and enums), and checks if any of them have * been used in an unsafe way. */ private void checkNamespaces() { for (Name name : nameMap.values()) { if (name.isNamespaceObjectLit() && (name.getAliasingGets() > 0 || name.getLocalSets() + name.getGlobalSets() > 1 || name.getDeleteProps() > 0)) { boolean initialized = name.getDeclaration() != null; for (Ref ref : name.getRefs()) { if (ref == name.getDeclaration()) { continue; } if (ref.type == Ref.Type.DELETE_PROP) { if (initialized) { warnAboutNamespaceRedefinition(name, ref); } } else if ( ref.type == Ref.Type.SET_FROM_GLOBAL || ref.type == Ref.Type.SET_FROM_LOCAL) { if (initialized && !isSafeNamespaceReinit(ref) && !providedNamespaces.contains(name.getFullName())) { warnAboutNamespaceRedefinition(name, ref); } initialized = true; } else if (ref.type == Ref.Type.ALIASING_GET) { if (!providedNamespaces.contains(name.getFullName()) && !ref.name.inExterns()) warnAboutNamespaceAliasing(name, ref); } } } } } static boolean isSafeNamespaceReinit(Ref ref) { // allow "a = a || {}" or "var a = a || {}" or "var a;" Node valParent = getValueParent(ref); Node val = valParent.getLastChild(); if (val != null && val.isOr()) { Node maybeName = val.getFirstChild(); if (ref.node.matchesQualifiedName(maybeName)) { return true; } } return false; } /** * Gets the parent node of the value for any assignment to a Name. * For example, in the assignment * {@code var x = 3;} * the parent would be the NAME node. */ private static Node getValueParent(Ref ref) { // there are four types of declarations: VARs, LETs, CONSTs, and ASSIGNs Node n = ref.node.getParent(); return (n != null && NodeUtil.isNameDeclaration(n)) ? ref.node : ref.node.getParent(); } /** * Reports a warning because a namespace was aliased. * * @param nameObj A namespace that is being aliased * @param ref The reference that forced the alias */ private void warnAboutNamespaceAliasing(Name nameObj, Ref ref) { compiler.report( JSError.make(ref.node, UNSAFE_NAMESPACE_WARNING, nameObj.getFullName())); } /** * Reports a warning because a namespace was redefined. * * @param nameObj A namespace that is being redefined * @param ref The reference that set the namespace */ private void warnAboutNamespaceRedefinition(Name nameObj, Ref ref) { compiler.report( JSError.make(ref.node, NAMESPACE_REDEFINED_WARNING, nameObj.getFullName())); } /** * Flattens all references to collapsible properties of a global name except * their initial definitions. Recurs on subnames. * * @param n An object representing a global name * @param alias The flattened name for {@code n} */ private void flattenReferencesToCollapsibleDescendantNames( Name n, String alias) { if (n.props == null || n.isCollapsingExplicitlyDenied()) { return; } for (Name p : n.props) { String propAlias = appendPropForAlias(alias, p.getBaseName()); boolean isAllowedToCollapse = propertyCollapseLevel != PropertyCollapseLevel.MODULE_EXPORT || p.isModuleExport(); if (isAllowedToCollapse && (p.canCollapse() || wasCollapsed(propAlias) || shouldCollapse(propAlias))) { flattenReferencesTo(p, propAlias); } else if (isAllowedToCollapse && p.isSimpleStubDeclaration() && !p.isCollapsingExplicitlyDenied()) { flattenSimpleStubDeclaration(p, propAlias); } flattenReferencesToCollapsibleDescendantNames(p, propAlias); } } /** * we should collapse aliases in the module no matter what. * * @param propAlias The alias being considered. * @return true If alias is for a namespace provided in the module. */ private boolean shouldCollapse(String propAlias) { if (providedAliases.contains(propAlias)) { InputId inputId = new InputId( sourceFileName); CompilerInput compilerInput = compiler.getInput(inputId); Node nameNode = IR.name(propAlias); Node child = IR.var(nameNode); compilerInput.getAstRoot(compiler).addChildToBack(child); compiler.reportChangeToEnclosingScope(child); if (!externAliases.contains(propAlias)) externAliases.add(propAlias); return true; } return false; } /** * See if this property was collapse by the loading app. * @param propAlias The alias that might have been collapsed. * @return true If the alias was collapsed in the loading app. */ private boolean wasCollapsed(String propAlias) { if (varRenameMapFile == null) return false; if (renamedVars == null) { List<String> fileLines; renamedVars = new ArrayList<String>(); try { fileLines = Files.readLines(varRenameMapFile, Charset.defaultCharset()); for (String line : fileLines) { int c = line.indexOf(":"); if (c > 0) { renamedVars.add(line.substring(0, c)); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (renamedVars.contains(propAlias) || externAliases.contains(propAlias)) { // if it was collapsed, add a var for it in our source for now. // RemoveUnusedNames will move the var before it gets code-genned. InputId inputId = new InputId( sourceFileName); CompilerInput compilerInput = compiler.getInput(inputId); Node nameNode = IR.name(propAlias); Node child = IR.var(nameNode); compilerInput.getAstRoot(compiler).addChildToBack(child); compiler.reportChangeToEnclosingScope(child); // add it to the list of aliases from the externs so // rename vars can know what variables we created here. if (!externAliases.contains(propAlias)) externAliases.add(propAlias); return true; } return false; } /** * Flattens a stub declaration. * This is mostly a hack to support legacy users. */ private void flattenSimpleStubDeclaration(Name name, String alias) { Ref ref = Iterables.getOnlyElement(name.getRefs()); Node nameNode = NodeUtil.newName( compiler, alias, ref.node, name.getFullName()); Node varNode = IR.var(nameNode).useSourceInfoIfMissingFrom(nameNode); checkState(ref.node.getParent().isExprResult()); Node parent = ref.node.getParent(); Node grandparent = parent.getParent(); grandparent.replaceChild(parent, varNode); compiler.reportChangeToEnclosingScope(varNode); } /** * Flattens all references to a collapsible property of a global name except * its initial definition. * * @param n A global property name (e.g. "a.b" or "a.b.c.d") * @param alias The flattened name (e.g. "a$b" or "a$b$c$d") */ private void flattenReferencesTo(Name n, String alias) { String originalName = n.getFullName(); for (Ref r : n.getRefs()) { if (r == n.getDeclaration()) { // Declarations are handled separately. continue; } Node rParent = r.node.getParent(); // There are two cases when we shouldn't flatten a reference: // 1) Object literal keys, because duplicate keys show up as refs. // 2) References inside a complex assign. (a = x.y = 0). These are // called TWIN references, because they show up twice in the // reference list. Only collapse the set, not the alias. if (!r.node.isFromExterns() && !NodeUtil.isObjectLitKey(r.node) && (r.getTwin() == null || r.isSet())) { flattenNameRef(alias, r.node, rParent, originalName); } } // Flatten all occurrences of a name as a prefix of its subnames. For // example, if {@code n} corresponds to the name "a.b", then "a.b" will be // replaced with "a$b" in all occurrences of "a.b.c", "a.b.c.d", etc. if (n.props != null) { for (Name p : n.props) { flattenPrefixes(alias, p, 1); } } } /** * Flattens all occurrences of a name as a prefix of subnames beginning * with a particular subname. * * @param n A global property name (e.g. "a.b.c.d") * @param alias A flattened prefix name (e.g. "a$b") * @param depth The difference in depth between the property name and * the prefix name (e.g. 2) */ private void flattenPrefixes(String alias, Name n, int depth) { // Only flatten the prefix of a name declaration if the name being // initialized is fully qualified (i.e. not an object literal key). String originalName = n.getFullName(); Ref decl = n.getDeclaration(); if (decl != null && decl.node != null && !decl.node.isFromExterns() && decl.node.isGetProp()) { flattenNameRefAtDepth(alias, decl.node, depth, originalName); } for (Ref r : n.getRefs()) { if (r == decl) { // Declarations are handled separately. continue; } // References inside a complex assign (a = x.y = 0) // have twins. We should only flatten one of the twins. if (r.getTwin() == null || r.isSet()) { if (r.node != null && !r.node.isFromExterns()) flattenNameRefAtDepth(alias, r.node, depth, originalName); } } if (n.props != null) { for (Name p : n.props) { flattenPrefixes(alias, p, depth + 1); } } } /** * Flattens a particular prefix of a single name reference. * * @param alias A flattened prefix name (e.g. "a$b") * @param n The node corresponding to a subproperty name (e.g. "a.b.c.d") * @param depth The difference in depth between the property name and * the prefix name (e.g. 2) * @param originalName String version of the property name. */ private void flattenNameRefAtDepth(String alias, Node n, int depth, String originalName) { // This method has to work for both GETPROP chains and, in rare cases, // OBJLIT keys, possibly nested. That's why we check for children before // proceeding. In the OBJLIT case, we don't need to do anything. Token nType = n.getToken(); boolean isQName = nType == Token.NAME || nType == Token.GETPROP; boolean isObjKey = NodeUtil.isObjectLitKey(n); checkState(isObjKey || isQName); if (isQName) { for (int i = 1; i < depth && n.hasChildren(); i++) { n = n.getFirstChild(); } if (n.isGetProp() && n.getFirstChild().isGetProp()) { flattenNameRef(alias, n.getFirstChild(), n, originalName); } } } /** * Replaces a GETPROP a.b.c with a NAME a$b$c. * * @param alias A flattened prefix name (e.g. "a$b") * @param n The GETPROP node corresponding to the original name (e.g. "a.b") * @param parent {@code n}'s parent * @param originalName String version of the property name. */ private void flattenNameRef(String alias, Node n, Node parent, String originalName) { Preconditions.checkArgument( n.isGetProp(), "Expected GETPROP, found %s. Node: %s", n.getToken(), n); // BEFORE: // getprop // getprop // name a // string b // string c // AFTER: // name a$b$c Node ref = NodeUtil.newName(compiler, alias, n, originalName); NodeUtil.copyNameAnnotations(n.getLastChild(), ref); if (parent != null && parent.isCall() && n == parent.getFirstChild()) { // The node was a call target, we are deliberately flatten these as // we node the "this" isn't provided by the namespace. Mark it as such: parent.putBooleanProp(Node.FREE_CALL, true); } JSType type = n.getJSType(); if (type != null) { ref.setJSType(type); } if (parent == null) { // in some cases parent is null (not sure why) // but ref is a StringNode and a child of n // is a StringNode so replace that StringNode parent = n; n = n.getFirstChild(); parent.replaceChild(n, ref); } else { parent.replaceChild(n, ref); Node enclosingScopeNode = NodeUtil.getEnclosingChangeScopeRoot(n.getParent()); if (enclosingScopeNode != null) compiler.reportChangeToEnclosingScope(ref); } } /** * Collapses definitions of the collapsible properties of a global name. * Recurs on subnames that also represent JavaScript objects with * collapsible properties. * * @param n A node representing a global name * @param alias The flattened name for {@code n} */ private void collapseDeclarationOfNameAndDescendants(Name n, String alias) { boolean canCollapseChildNames = n.canCollapseUnannotatedChildNames(); // Handle this name first so that nested object literals get unrolled. if (canCollapse(n)/* && !externStrings.contains(n.getName())*/) { updateGlobalNameDeclaration(n, alias, canCollapseChildNames); } if (n.props == null) { return; } for (Name p : n.props) { collapseDeclarationOfNameAndDescendants(p, appendPropForAlias(alias, p.getBaseName())); } } /** * Updates the initial assignment to a collapsible property at global scope * by adding a VAR stub and collapsing the property. e.g. c = a.b = 1; => var a$b; c = a$b = 1; * This specifically handles "twinned" assignments, which are those where the assignment is also * used as a reference and which need special handling. * * @param alias The flattened property name (e.g. "a$b") * @param refName The name for the reference being updated. * @param ref An object containing information about the assignment getting updated */ private void updateTwinnedDeclaration(String alias, Name refName, Ref ref) { checkNotNull(ref.getTwin()); // Don't handle declarations of an already flat name, just qualified names. if (!ref.node.isGetProp()) { return; } Node rvalue = ref.node.getNext(); Node parent = ref.node.getParent(); Node grandparent = parent.getParent(); if (rvalue != null && rvalue.isFunction()) { checkForHosedThisReferences(rvalue, refName.docInfo, refName); } // Create the new alias node. Node nameNode = NodeUtil.newName(compiler, alias, grandparent.getFirstChild(), refName.getFullName()); NodeUtil.copyNameAnnotations(ref.node.getLastChild(), nameNode); // BEFORE: // ... (x.y = 3); // // AFTER: // var x$y; // ... (x$y = 3); Node current = grandparent; Node currentParent = grandparent.getParent(); for (; !currentParent.isScript() && !currentParent.isBlock(); current = currentParent, currentParent = currentParent.getParent()) {} // Create a stub variable declaration right // before the current statement. Node stubVar = IR.var(nameNode.cloneTree()).useSourceInfoIfMissingFrom(nameNode); currentParent.addChildBefore(stubVar, current); parent.replaceChild(ref.node, nameNode); compiler.reportChangeToEnclosingScope(nameNode); } /** * Updates the first initialization (a.k.a "declaration") of a global name. * This involves flattening the global name (if it's not just a global * variable name already), collapsing object literal keys into global * variables, declaring stub global variables for properties added later * in a local scope. * * It may seem odd that this function also takes care of declaring stubs * for direct children. The ultimate goal of this function is to eliminate * the global name entirely (when possible), so that "middlemen" namespaces * disappear, and to do that we need to make sure that all the direct children * will be collapsed as well. * * @param n An object representing a global name (e.g. "a", "a.b.c") * @param alias The flattened name for {@code n} (e.g. "a", "a$b$c") * @param canCollapseChildNames Whether it's possible to collapse children of * this name. (This is mostly passed for convenience; it's equivalent to * n.canCollapseChildNames()). */ private void updateGlobalNameDeclaration( Name n, String alias, boolean canCollapseChildNames) { Ref decl = n.getDeclaration(); if (decl == null) { // Some names do not have declarations, because they // are only defined in local scopes. return; } if (decl.node == null) return; // package stubs (org.apache.royale) switch (decl.node.getParent().getToken()) { case ASSIGN: updateGlobalNameDeclarationAtAssignNode( n, alias, canCollapseChildNames); break; case VAR: case LET: case CONST: updateGlobalNameDeclarationAtVariableNode(n, canCollapseChildNames); break; case FUNCTION: updateGlobalNameDeclarationAtFunctionNode(n, canCollapseChildNames); break; case CLASS: updateGlobalNameDeclarationAtClassNode(n, canCollapseChildNames); break; default: break; } } /** * Updates the first initialization (a.k.a "declaration") of a global name * that occurs at an ASSIGN node. See comment for * {@link #updateGlobalNameDeclaration}. * * @param n An object representing a global name (e.g. "a", "a.b.c") * @param alias The flattened name for {@code n} (e.g. "a", "a$b$c") */ private void updateGlobalNameDeclarationAtAssignNode( Name n, String alias, boolean canCollapseChildNames) { // NOTE: It's important that we don't add additional nodes // (e.g. a var node before the exprstmt) because the exprstmt might be // the child of an if statement that's not inside a block). // All qualified names - even for variables that are initially declared as LETS and CONSTS - // are being declared as VAR statements, but this is not incorrect because // we are only collapsing for global names. Ref ref = n.getDeclaration(); Node rvalue = ref.node.getNext(); if (ref.getTwin() != null) { updateTwinnedDeclaration(alias, ref.name, ref); return; } Node varNode = new Node(Token.VAR); Node varParent = ref.node.getAncestor(3); Node grandparent = ref.node.getAncestor(2); boolean isObjLit = rvalue.isObjectLit(); boolean insertedVarNode = false; if (isObjLit && canEliminate(n)) { // Eliminate the object literal altogether. varParent.replaceChild(grandparent, varNode); ref.node = null; insertedVarNode = true; compiler.reportChangeToEnclosingScope(varNode); } else if (!n.isSimpleName()) { // Create a VAR node to declare the name. if (rvalue.isFunction()) { checkForHosedThisReferences(rvalue, n.docInfo, n); } compiler.reportChangeToEnclosingScope(rvalue); ref.node.getParent().removeChild(rvalue); Node nameNode = NodeUtil.newName(compiler, alias, ref.node.getAncestor(2), n.getFullName()); JSDocInfo info = NodeUtil.getBestJSDocInfo(ref.node.getParent()); if (ref.node.getLastChild().getBooleanProp(Node.IS_CONSTANT_NAME) || (info != null && info.isConstant())) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } if (info != null) { varNode.setJSDocInfo(info); } varNode.addChildToBack(nameNode); nameNode.addChildToFront(rvalue); varParent.replaceChild(grandparent, varNode); // Update the node ancestry stored in the reference. ref.node = nameNode; insertedVarNode = true; compiler.reportChangeToEnclosingScope(varNode); } if (canCollapseChildNames) { if (isObjLit) { declareVariablesForObjLitValues( n, alias, rvalue, varNode, varNode.getPrevious(), varParent); } addStubsForUndeclaredProperties(n, alias, varParent, varNode); } if (insertedVarNode) { if (!varNode.hasChildren()) { varParent.removeChild(varNode); } } } /** * Warns about any references to "this" in the given FUNCTION. The function * is getting collapsed, so the references will change. */ private void checkForHosedThisReferences(Node function, JSDocInfo docInfo, final Name name) { // A function is getting collapsed. Make sure that if it refers to "this", // it must be a constructor, interface, record, arrow function, or documented with @this. boolean isAllowedToReferenceThis = (docInfo != null && (docInfo.isConstructorOrInterface() || docInfo.hasThisType())) || function.isArrowFunction(); if (!isAllowedToReferenceThis) { NodeTraversal.traverse(compiler, function.getLastChild(), new NodeTraversal.AbstractShallowCallback() { @Override public void visit(NodeTraversal t, Node n, Node parent) { if (n.isThis()) { compiler.report( JSError.make(n, UNSAFE_THIS, name.getFullName())); } } }); } } /** * Updates the first initialization (a.k.a "declaration") of a global name that occurs at a VAR * node. See comment for {@link #updateGlobalNameDeclaration}. * * @param n An object representing a global name (e.g. "a") */ private void updateGlobalNameDeclarationAtVariableNode( Name n, boolean canCollapseChildNames) { if (!canCollapseChildNames) { return; } Ref ref = n.getDeclaration(); String name = ref.node.getString(); Node rvalue = ref.node.getFirstChild(); Node variableNode = ref.node.getParent(); Node grandparent = variableNode.getParent(); boolean isObjLit = rvalue.isObjectLit(); if (isObjLit) { declareVariablesForObjLitValues( n, name, rvalue, variableNode, variableNode.getPrevious(), grandparent); } addStubsForUndeclaredProperties(n, name, grandparent, variableNode); if (isObjLit && canEliminate(n)) { variableNode.removeChild(ref.node); compiler.reportChangeToEnclosingScope(variableNode); if (!variableNode.hasChildren()) { grandparent.removeChild(variableNode); } // Clear out the object reference, since we've eliminated it from the // parse tree. ref.node = null; } } /** * Updates the first initialization (a.k.a "declaration") of a global name * that occurs at a FUNCTION node. See comment for * {@link #updateGlobalNameDeclaration}. * * @param n An object representing a global name (e.g. "a") */ private void updateGlobalNameDeclarationAtFunctionNode( Name n, boolean canCollapseChildNames) { if (!canCollapseChildNames || !canCollapse(n)) { return; } Ref ref = n.getDeclaration(); String fnName = ref.node.getString(); addStubsForUndeclaredProperties(n, fnName, ref.node.getAncestor(2), ref.node.getParent()); } /** * Updates the first initialization (a.k.a "declaration") of a global name that occurs at a CLASS * node. See comment for {@link #updateGlobalNameDeclaration}. * * @param n An object representing a global name (e.g. "a") */ private void updateGlobalNameDeclarationAtClassNode(Name n, boolean canCollapseChildNames) { if (!canCollapseChildNames || !canCollapse(n)) { return; } Ref ref = n.getDeclaration(); String className = ref.node.getString(); addStubsForUndeclaredProperties( n, className, ref.node.getAncestor(2), ref.node.getParent()); } /** * Declares global variables to serve as aliases for the values in an object literal, optionally * removing all of the object literal's keys and values. * * @param alias The object literal's flattened name (e.g. "a$b$c") * @param objlit The OBJLIT node * @param varNode The VAR node to which new global variables should be added as children * @param nameToAddAfter The child of {@code varNode} after which new variables should be added * (may be null) * @param varParent {@code varNode}'s parent */ private void declareVariablesForObjLitValues( Name objlitName, String alias, Node objlit, Node varNode, Node nameToAddAfter, Node varParent) { int arbitraryNameCounter = 0; boolean discardKeys = !objlitName.shouldKeepKeys(); for (Node key = objlit.getFirstChild(), nextKey; key != null; key = nextKey) { Node value = key.getFirstChild(); nextKey = key.getNext(); // A computed property, or a get or a set can not be rewritten as a VAR. if (key.isGetterDef() || key.isSetterDef() || key.isComputedProp()) { continue; } // We generate arbitrary names for keys that aren't valid JavaScript // identifiers, since those keys are never referenced. (If they were, // this object literal's child names wouldn't be collapsible.) The only // reason that we don't eliminate them entirely is the off chance that // their values are expressions that have side effects. boolean isJsIdentifier = !key.isNumber() && TokenStream.isJSIdentifier(key.getString()); String propName = isJsIdentifier ? key.getString() : String.valueOf(++arbitraryNameCounter); // If the name cannot be collapsed, skip it. String qName = objlitName.getFullName() + '.' + propName; Name p = nameMap.get(qName); if (p != null && !canCollapse(p)) { continue; } String propAlias = appendPropForAlias(alias, propName); Node refNode = null; if (discardKeys) { objlit.removeChild(key); value.detach(); // Don't report a change here because the objlit has already been removed from the tree. } else { // Substitute a reference for the value. refNode = IR.name(propAlias); if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) { refNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } key.replaceChild(value, refNode); compiler.reportChangeToEnclosingScope(refNode); } // Declare the collapsed name as a variable with the original value. Node nameNode = IR.name(propAlias); nameNode.addChildToFront(value); if (key.getBooleanProp(Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); } Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(key); if (nameToAddAfter != null) { varParent.addChildAfter(newVar, nameToAddAfter); } else { varParent.addChildBefore(newVar, varNode); } compiler.reportChangeToEnclosingScope(newVar); nameToAddAfter = newVar; // Update the global name's node ancestry if it hasn't already been // done. (Duplicate keys in an object literal can bring us here twice // for the same global name.) if (isJsIdentifier && p != null) { if (!discardKeys) { Ref newAlias = p.getDeclaration().cloneAndReclassify(Ref.Type.ALIASING_GET); newAlias.node = refNode; p.addRef(newAlias); } p.getDeclaration().node = nameNode; if (value.isFunction()) { checkForHosedThisReferences(value, key.getJSDocInfo(), p); } } } } /** * Adds global variable "stubs" for any properties of a global name that are only set in a local * scope or read but never set. * * @param n An object representing a global name (e.g. "a", "a.b.c") * @param alias The flattened name of the object whose properties we are adding stubs for (e.g. * "a$b$c") * @param parent The node to which new global variables should be added as children * @param addAfter The child of after which new variables should be added */ private void addStubsForUndeclaredProperties(Name n, String alias, Node parent, Node addAfter) { checkState(n.canCollapseUnannotatedChildNames(), n); checkArgument(NodeUtil.isStatementBlock(parent), parent); checkNotNull(addAfter); if (n.props == null) { return; } for (Name p : n.props) { if (p.needsToBeStubbed()) { String propAlias = appendPropForAlias(alias, p.getBaseName()); Node nameNode = IR.name(propAlias); Node newVar = IR.var(nameNode).useSourceInfoIfMissingFromForTree(addAfter); parent.addChildAfter(newVar, addAfter); addAfter = newVar; compiler.reportChangeToEnclosingScope(newVar); // Determine if this is a constant var by checking the first // reference to it. Don't check the declaration, as it might be null. if (p.getRefs().get(0).node.getLastChild().getBooleanProp( Node.IS_CONSTANT_NAME)) { nameNode.putBooleanProp(Node.IS_CONSTANT_NAME, true); compiler.reportChangeToEnclosingScope(nameNode); } } } } private String appendPropForAlias(String root, String prop) { if (prop.indexOf('$') != -1) { // Encode '$' in a property as '$0'. Because '0' cannot be the // start of an identifier, this will never conflict with our // encoding from '.' -> '$'. prop = prop.replace("$", "$0"); } String result = root + '$' + prop; int id = 1; while (nameMap.containsKey(result)) { result = root + '$' + prop + '$' + id; id++; } return result; } }
googleapis/google-api-java-client-services
37,684
clients/google-api-services-appengine/v1/1.31.0/com/google/api/services/appengine/v1/model/Version.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.appengine.v1.model; /** * A Version resource is a specific set of source code and configuration files that are deployed * into a service. * * <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 App Engine Admin 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 Version extends com.google.api.client.json.GenericJson { /** * Serving configuration for Google Cloud Endpoints * (https://cloud.google.com/appengine/docs/python/endpoints/).Only returned in GET requests if * view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private ApiConfigHandler apiConfig; /** * Allows App Engine second generation runtimes to access the legacy bundled services. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean appEngineApis; /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Instances are dynamically created and destroyed as needed in order to handle traffic. * The value may be {@code null}. */ @com.google.api.client.util.Key private AutomaticScaling automaticScaling; /** * A service with basic scaling will create an instance when the application receives a request. * The instance will be turned down when the app becomes idle. Basic scaling is ideal for work * that is intermittent or driven by user activity. * The value may be {@code null}. */ @com.google.api.client.util.Key private BasicScaling basicScaling; /** * Metadata settings that are supplied to this version to enable beta runtime features. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> betaSettings; /** * Environment variables available to the build environment.Only returned in GET requests if * view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> buildEnvVariables; /** * Time that this version was created.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private String createTime; /** * Email address of the user who created this version.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String createdBy; /** * Duration that static files should be cached by web proxies and browsers. Only applicable if the * corresponding StaticFilesHandler (https://cloud.google.com/appengine/docs/admin- * api/reference/rest/v1/apps.services.versions#StaticFilesHandler) does not specify its own * expiration time.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private String defaultExpiration; /** * Code and application artifacts that make up this version.Only returned in GET requests if * view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private Deployment deployment; /** * Total size in bytes of all the files that are included in this version and currently hosted on * the App Engine disk.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long diskUsageBytes; /** * Cloud Endpoints configuration.If endpoints_api_service is set, the Cloud Endpoints Extensible * Service Proxy will be provided to serve the API implemented by the app. * The value may be {@code null}. */ @com.google.api.client.util.Key private EndpointsApiService endpointsApiService; /** * The entrypoint for the application. * The value may be {@code null}. */ @com.google.api.client.util.Key private Entrypoint entrypoint; /** * App Engine execution environment for this version.Defaults to standard. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String env; /** * Environment variables available to the application.Only returned in GET requests if view=FULL * is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> envVariables; /** * Custom static error pages. Limited to 10KB per page.Only returned in GET requests if view=FULL * is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ErrorHandler> errorHandlers; static { // hack to force ProGuard to consider ErrorHandler used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(ErrorHandler.class); } /** * An ordered list of URL-matching patterns that should be applied to incoming requests. The first * matching URL handles the request and other request handlers are not attempted.Only returned in * GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<UrlMap> handlers; static { // hack to force ProGuard to consider UrlMap used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(UrlMap.class); } /** * Configures health checking for instances. Unhealthy instances are stopped and replaced with new * instances. Only applicable in the App Engine flexible environment.Only returned in GET requests * if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private HealthCheck healthCheck; /** * Relative name of the version within the service. Example: v1. Version names can contain only * lowercase letters, numbers, or hyphens. Reserved names: "default", "latest", and any name with * the prefix "ah-". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * Before an application can receive email or XMPP messages, the application must be configured to * enable the service. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> inboundServices; /** * Instance class that is used to run this version. Valid values are: AutomaticScaling: F1, F2, * F4, F4_1G ManualScaling or BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for * AutomaticScaling and B1 for ManualScaling or BasicScaling. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String instanceClass; /** * Configuration for third-party Python runtime libraries that are required by the * application.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Library> libraries; static { // hack to force ProGuard to consider Library used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Library.class); } /** * Configures liveness health checking for instances. Unhealthy instances are stopped and replaced * with new instancesOnly returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private LivenessCheck livenessCheck; /** * A service with manual scaling runs continuously, allowing you to perform complex initialization * and rely on the state of its memory over time. Manually scaled versions are sometimes referred * to as "backends". * The value may be {@code null}. */ @com.google.api.client.util.Key private ManualScaling manualScaling; /** * Full path to the Version resource in the API. Example: * apps/myapp/services/default/versions/v1.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Extra network settings. Only applicable in the App Engine flexible environment. * The value may be {@code null}. */ @com.google.api.client.util.Key private Network network; /** * Files that match this pattern will not be built into this version. Only applicable for Go * runtimes.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String nobuildFilesRegex; /** * Configures readiness health checking for instances. Unhealthy instances are not put into the * backend traffic rotation.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private ReadinessCheck readinessCheck; /** * Machine resources for this version. Only applicable in the App Engine flexible environment. * The value may be {@code null}. */ @com.google.api.client.util.Key private Resources resources; /** * Desired runtime. Example: python27. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtime; /** * The version of the API in the given runtime environment. Please see the app.yaml reference for * valid values at https://cloud.google.com/appengine/docs/standard//config/appref * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtimeApiVersion; /** * The channel of the runtime to use. Only available for some runtimes. Defaults to the default * channel. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtimeChannel; /** * The path or name of the app's main executable. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtimeMainExecutablePath; /** * The identity that the deployed version will run as. Admin API will use the App Engine Appspot * service account as default if this field is neither provided in app.yaml file nor through CLI * flag. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String serviceAccount; /** * Current serving status of this version. Only the versions with a SERVING status create * instances and can be billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to * SERVING. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String servingStatus; /** * Whether multiple requests can be dispatched to this version at once. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean threadsafe; /** * Serving URL for this version. Example: "https://myversion-dot-myservice-dot- * myapp.appspot.com"@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String versionUrl; /** * Whether to deploy this version in a container on a virtual machine. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean vm; /** * Enables VPC connectivity for standard apps. * The value may be {@code null}. */ @com.google.api.client.util.Key private VpcAccessConnector vpcAccessConnector; /** * The Google Compute Engine zones that are supported by this version in the App Engine flexible * environment. Deprecated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> zones; /** * Serving configuration for Google Cloud Endpoints * (https://cloud.google.com/appengine/docs/python/endpoints/).Only returned in GET requests if * view=FULL is set. * @return value or {@code null} for none */ public ApiConfigHandler getApiConfig() { return apiConfig; } /** * Serving configuration for Google Cloud Endpoints * (https://cloud.google.com/appengine/docs/python/endpoints/).Only returned in GET requests if * view=FULL is set. * @param apiConfig apiConfig or {@code null} for none */ public Version setApiConfig(ApiConfigHandler apiConfig) { this.apiConfig = apiConfig; return this; } /** * Allows App Engine second generation runtimes to access the legacy bundled services. * @return value or {@code null} for none */ public java.lang.Boolean getAppEngineApis() { return appEngineApis; } /** * Allows App Engine second generation runtimes to access the legacy bundled services. * @param appEngineApis appEngineApis or {@code null} for none */ public Version setAppEngineApis(java.lang.Boolean appEngineApis) { this.appEngineApis = appEngineApis; return this; } /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Instances are dynamically created and destroyed as needed in order to handle traffic. * @return value or {@code null} for none */ public AutomaticScaling getAutomaticScaling() { return automaticScaling; } /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Instances are dynamically created and destroyed as needed in order to handle traffic. * @param automaticScaling automaticScaling or {@code null} for none */ public Version setAutomaticScaling(AutomaticScaling automaticScaling) { this.automaticScaling = automaticScaling; return this; } /** * A service with basic scaling will create an instance when the application receives a request. * The instance will be turned down when the app becomes idle. Basic scaling is ideal for work * that is intermittent or driven by user activity. * @return value or {@code null} for none */ public BasicScaling getBasicScaling() { return basicScaling; } /** * A service with basic scaling will create an instance when the application receives a request. * The instance will be turned down when the app becomes idle. Basic scaling is ideal for work * that is intermittent or driven by user activity. * @param basicScaling basicScaling or {@code null} for none */ public Version setBasicScaling(BasicScaling basicScaling) { this.basicScaling = basicScaling; return this; } /** * Metadata settings that are supplied to this version to enable beta runtime features. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getBetaSettings() { return betaSettings; } /** * Metadata settings that are supplied to this version to enable beta runtime features. * @param betaSettings betaSettings or {@code null} for none */ public Version setBetaSettings(java.util.Map<String, java.lang.String> betaSettings) { this.betaSettings = betaSettings; return this; } /** * Environment variables available to the build environment.Only returned in GET requests if * view=FULL is set. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getBuildEnvVariables() { return buildEnvVariables; } /** * Environment variables available to the build environment.Only returned in GET requests if * view=FULL is set. * @param buildEnvVariables buildEnvVariables or {@code null} for none */ public Version setBuildEnvVariables(java.util.Map<String, java.lang.String> buildEnvVariables) { this.buildEnvVariables = buildEnvVariables; return this; } /** * Time that this version was created.@OutputOnly * @return value or {@code null} for none */ public String getCreateTime() { return createTime; } /** * Time that this version was created.@OutputOnly * @param createTime createTime or {@code null} for none */ public Version setCreateTime(String createTime) { this.createTime = createTime; return this; } /** * Email address of the user who created this version.@OutputOnly * @return value or {@code null} for none */ public java.lang.String getCreatedBy() { return createdBy; } /** * Email address of the user who created this version.@OutputOnly * @param createdBy createdBy or {@code null} for none */ public Version setCreatedBy(java.lang.String createdBy) { this.createdBy = createdBy; return this; } /** * Duration that static files should be cached by web proxies and browsers. Only applicable if the * corresponding StaticFilesHandler (https://cloud.google.com/appengine/docs/admin- * api/reference/rest/v1/apps.services.versions#StaticFilesHandler) does not specify its own * expiration time.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public String getDefaultExpiration() { return defaultExpiration; } /** * Duration that static files should be cached by web proxies and browsers. Only applicable if the * corresponding StaticFilesHandler (https://cloud.google.com/appengine/docs/admin- * api/reference/rest/v1/apps.services.versions#StaticFilesHandler) does not specify its own * expiration time.Only returned in GET requests if view=FULL is set. * @param defaultExpiration defaultExpiration or {@code null} for none */ public Version setDefaultExpiration(String defaultExpiration) { this.defaultExpiration = defaultExpiration; return this; } /** * Code and application artifacts that make up this version.Only returned in GET requests if * view=FULL is set. * @return value or {@code null} for none */ public Deployment getDeployment() { return deployment; } /** * Code and application artifacts that make up this version.Only returned in GET requests if * view=FULL is set. * @param deployment deployment or {@code null} for none */ public Version setDeployment(Deployment deployment) { this.deployment = deployment; return this; } /** * Total size in bytes of all the files that are included in this version and currently hosted on * the App Engine disk.@OutputOnly * @return value or {@code null} for none */ public java.lang.Long getDiskUsageBytes() { return diskUsageBytes; } /** * Total size in bytes of all the files that are included in this version and currently hosted on * the App Engine disk.@OutputOnly * @param diskUsageBytes diskUsageBytes or {@code null} for none */ public Version setDiskUsageBytes(java.lang.Long diskUsageBytes) { this.diskUsageBytes = diskUsageBytes; return this; } /** * Cloud Endpoints configuration.If endpoints_api_service is set, the Cloud Endpoints Extensible * Service Proxy will be provided to serve the API implemented by the app. * @return value or {@code null} for none */ public EndpointsApiService getEndpointsApiService() { return endpointsApiService; } /** * Cloud Endpoints configuration.If endpoints_api_service is set, the Cloud Endpoints Extensible * Service Proxy will be provided to serve the API implemented by the app. * @param endpointsApiService endpointsApiService or {@code null} for none */ public Version setEndpointsApiService(EndpointsApiService endpointsApiService) { this.endpointsApiService = endpointsApiService; return this; } /** * The entrypoint for the application. * @return value or {@code null} for none */ public Entrypoint getEntrypoint() { return entrypoint; } /** * The entrypoint for the application. * @param entrypoint entrypoint or {@code null} for none */ public Version setEntrypoint(Entrypoint entrypoint) { this.entrypoint = entrypoint; return this; } /** * App Engine execution environment for this version.Defaults to standard. * @return value or {@code null} for none */ public java.lang.String getEnv() { return env; } /** * App Engine execution environment for this version.Defaults to standard. * @param env env or {@code null} for none */ public Version setEnv(java.lang.String env) { this.env = env; return this; } /** * Environment variables available to the application.Only returned in GET requests if view=FULL * is set. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getEnvVariables() { return envVariables; } /** * Environment variables available to the application.Only returned in GET requests if view=FULL * is set. * @param envVariables envVariables or {@code null} for none */ public Version setEnvVariables(java.util.Map<String, java.lang.String> envVariables) { this.envVariables = envVariables; return this; } /** * Custom static error pages. Limited to 10KB per page.Only returned in GET requests if view=FULL * is set. * @return value or {@code null} for none */ public java.util.List<ErrorHandler> getErrorHandlers() { return errorHandlers; } /** * Custom static error pages. Limited to 10KB per page.Only returned in GET requests if view=FULL * is set. * @param errorHandlers errorHandlers or {@code null} for none */ public Version setErrorHandlers(java.util.List<ErrorHandler> errorHandlers) { this.errorHandlers = errorHandlers; return this; } /** * An ordered list of URL-matching patterns that should be applied to incoming requests. The first * matching URL handles the request and other request handlers are not attempted.Only returned in * GET requests if view=FULL is set. * @return value or {@code null} for none */ public java.util.List<UrlMap> getHandlers() { return handlers; } /** * An ordered list of URL-matching patterns that should be applied to incoming requests. The first * matching URL handles the request and other request handlers are not attempted.Only returned in * GET requests if view=FULL is set. * @param handlers handlers or {@code null} for none */ public Version setHandlers(java.util.List<UrlMap> handlers) { this.handlers = handlers; return this; } /** * Configures health checking for instances. Unhealthy instances are stopped and replaced with new * instances. Only applicable in the App Engine flexible environment.Only returned in GET requests * if view=FULL is set. * @return value or {@code null} for none */ public HealthCheck getHealthCheck() { return healthCheck; } /** * Configures health checking for instances. Unhealthy instances are stopped and replaced with new * instances. Only applicable in the App Engine flexible environment.Only returned in GET requests * if view=FULL is set. * @param healthCheck healthCheck or {@code null} for none */ public Version setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; return this; } /** * Relative name of the version within the service. Example: v1. Version names can contain only * lowercase letters, numbers, or hyphens. Reserved names: "default", "latest", and any name with * the prefix "ah-". * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * Relative name of the version within the service. Example: v1. Version names can contain only * lowercase letters, numbers, or hyphens. Reserved names: "default", "latest", and any name with * the prefix "ah-". * @param id id or {@code null} for none */ public Version setId(java.lang.String id) { this.id = id; return this; } /** * Before an application can receive email or XMPP messages, the application must be configured to * enable the service. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getInboundServices() { return inboundServices; } /** * Before an application can receive email or XMPP messages, the application must be configured to * enable the service. * @param inboundServices inboundServices or {@code null} for none */ public Version setInboundServices(java.util.List<java.lang.String> inboundServices) { this.inboundServices = inboundServices; return this; } /** * Instance class that is used to run this version. Valid values are: AutomaticScaling: F1, F2, * F4, F4_1G ManualScaling or BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for * AutomaticScaling and B1 for ManualScaling or BasicScaling. * @return value or {@code null} for none */ public java.lang.String getInstanceClass() { return instanceClass; } /** * Instance class that is used to run this version. Valid values are: AutomaticScaling: F1, F2, * F4, F4_1G ManualScaling or BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for * AutomaticScaling and B1 for ManualScaling or BasicScaling. * @param instanceClass instanceClass or {@code null} for none */ public Version setInstanceClass(java.lang.String instanceClass) { this.instanceClass = instanceClass; return this; } /** * Configuration for third-party Python runtime libraries that are required by the * application.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public java.util.List<Library> getLibraries() { return libraries; } /** * Configuration for third-party Python runtime libraries that are required by the * application.Only returned in GET requests if view=FULL is set. * @param libraries libraries or {@code null} for none */ public Version setLibraries(java.util.List<Library> libraries) { this.libraries = libraries; return this; } /** * Configures liveness health checking for instances. Unhealthy instances are stopped and replaced * with new instancesOnly returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public LivenessCheck getLivenessCheck() { return livenessCheck; } /** * Configures liveness health checking for instances. Unhealthy instances are stopped and replaced * with new instancesOnly returned in GET requests if view=FULL is set. * @param livenessCheck livenessCheck or {@code null} for none */ public Version setLivenessCheck(LivenessCheck livenessCheck) { this.livenessCheck = livenessCheck; return this; } /** * A service with manual scaling runs continuously, allowing you to perform complex initialization * and rely on the state of its memory over time. Manually scaled versions are sometimes referred * to as "backends". * @return value or {@code null} for none */ public ManualScaling getManualScaling() { return manualScaling; } /** * A service with manual scaling runs continuously, allowing you to perform complex initialization * and rely on the state of its memory over time. Manually scaled versions are sometimes referred * to as "backends". * @param manualScaling manualScaling or {@code null} for none */ public Version setManualScaling(ManualScaling manualScaling) { this.manualScaling = manualScaling; return this; } /** * Full path to the Version resource in the API. Example: * apps/myapp/services/default/versions/v1.@OutputOnly * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Full path to the Version resource in the API. Example: * apps/myapp/services/default/versions/v1.@OutputOnly * @param name name or {@code null} for none */ public Version setName(java.lang.String name) { this.name = name; return this; } /** * Extra network settings. Only applicable in the App Engine flexible environment. * @return value or {@code null} for none */ public Network getNetwork() { return network; } /** * Extra network settings. Only applicable in the App Engine flexible environment. * @param network network or {@code null} for none */ public Version setNetwork(Network network) { this.network = network; return this; } /** * Files that match this pattern will not be built into this version. Only applicable for Go * runtimes.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public java.lang.String getNobuildFilesRegex() { return nobuildFilesRegex; } /** * Files that match this pattern will not be built into this version. Only applicable for Go * runtimes.Only returned in GET requests if view=FULL is set. * @param nobuildFilesRegex nobuildFilesRegex or {@code null} for none */ public Version setNobuildFilesRegex(java.lang.String nobuildFilesRegex) { this.nobuildFilesRegex = nobuildFilesRegex; return this; } /** * Configures readiness health checking for instances. Unhealthy instances are not put into the * backend traffic rotation.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public ReadinessCheck getReadinessCheck() { return readinessCheck; } /** * Configures readiness health checking for instances. Unhealthy instances are not put into the * backend traffic rotation.Only returned in GET requests if view=FULL is set. * @param readinessCheck readinessCheck or {@code null} for none */ public Version setReadinessCheck(ReadinessCheck readinessCheck) { this.readinessCheck = readinessCheck; return this; } /** * Machine resources for this version. Only applicable in the App Engine flexible environment. * @return value or {@code null} for none */ public Resources getResources() { return resources; } /** * Machine resources for this version. Only applicable in the App Engine flexible environment. * @param resources resources or {@code null} for none */ public Version setResources(Resources resources) { this.resources = resources; return this; } /** * Desired runtime. Example: python27. * @return value or {@code null} for none */ public java.lang.String getRuntime() { return runtime; } /** * Desired runtime. Example: python27. * @param runtime runtime or {@code null} for none */ public Version setRuntime(java.lang.String runtime) { this.runtime = runtime; return this; } /** * The version of the API in the given runtime environment. Please see the app.yaml reference for * valid values at https://cloud.google.com/appengine/docs/standard//config/appref * @return value or {@code null} for none */ public java.lang.String getRuntimeApiVersion() { return runtimeApiVersion; } /** * The version of the API in the given runtime environment. Please see the app.yaml reference for * valid values at https://cloud.google.com/appengine/docs/standard//config/appref * @param runtimeApiVersion runtimeApiVersion or {@code null} for none */ public Version setRuntimeApiVersion(java.lang.String runtimeApiVersion) { this.runtimeApiVersion = runtimeApiVersion; return this; } /** * The channel of the runtime to use. Only available for some runtimes. Defaults to the default * channel. * @return value or {@code null} for none */ public java.lang.String getRuntimeChannel() { return runtimeChannel; } /** * The channel of the runtime to use. Only available for some runtimes. Defaults to the default * channel. * @param runtimeChannel runtimeChannel or {@code null} for none */ public Version setRuntimeChannel(java.lang.String runtimeChannel) { this.runtimeChannel = runtimeChannel; return this; } /** * The path or name of the app's main executable. * @return value or {@code null} for none */ public java.lang.String getRuntimeMainExecutablePath() { return runtimeMainExecutablePath; } /** * The path or name of the app's main executable. * @param runtimeMainExecutablePath runtimeMainExecutablePath or {@code null} for none */ public Version setRuntimeMainExecutablePath(java.lang.String runtimeMainExecutablePath) { this.runtimeMainExecutablePath = runtimeMainExecutablePath; return this; } /** * The identity that the deployed version will run as. Admin API will use the App Engine Appspot * service account as default if this field is neither provided in app.yaml file nor through CLI * flag. * @return value or {@code null} for none */ public java.lang.String getServiceAccount() { return serviceAccount; } /** * The identity that the deployed version will run as. Admin API will use the App Engine Appspot * service account as default if this field is neither provided in app.yaml file nor through CLI * flag. * @param serviceAccount serviceAccount or {@code null} for none */ public Version setServiceAccount(java.lang.String serviceAccount) { this.serviceAccount = serviceAccount; return this; } /** * Current serving status of this version. Only the versions with a SERVING status create * instances and can be billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to * SERVING. * @return value or {@code null} for none */ public java.lang.String getServingStatus() { return servingStatus; } /** * Current serving status of this version. Only the versions with a SERVING status create * instances and can be billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to * SERVING. * @param servingStatus servingStatus or {@code null} for none */ public Version setServingStatus(java.lang.String servingStatus) { this.servingStatus = servingStatus; return this; } /** * Whether multiple requests can be dispatched to this version at once. * @return value or {@code null} for none */ public java.lang.Boolean getThreadsafe() { return threadsafe; } /** * Whether multiple requests can be dispatched to this version at once. * @param threadsafe threadsafe or {@code null} for none */ public Version setThreadsafe(java.lang.Boolean threadsafe) { this.threadsafe = threadsafe; return this; } /** * Serving URL for this version. Example: "https://myversion-dot-myservice-dot- * myapp.appspot.com"@OutputOnly * @return value or {@code null} for none */ public java.lang.String getVersionUrl() { return versionUrl; } /** * Serving URL for this version. Example: "https://myversion-dot-myservice-dot- * myapp.appspot.com"@OutputOnly * @param versionUrl versionUrl or {@code null} for none */ public Version setVersionUrl(java.lang.String versionUrl) { this.versionUrl = versionUrl; return this; } /** * Whether to deploy this version in a container on a virtual machine. * @return value or {@code null} for none */ public java.lang.Boolean getVm() { return vm; } /** * Whether to deploy this version in a container on a virtual machine. * @param vm vm or {@code null} for none */ public Version setVm(java.lang.Boolean vm) { this.vm = vm; return this; } /** * Enables VPC connectivity for standard apps. * @return value or {@code null} for none */ public VpcAccessConnector getVpcAccessConnector() { return vpcAccessConnector; } /** * Enables VPC connectivity for standard apps. * @param vpcAccessConnector vpcAccessConnector or {@code null} for none */ public Version setVpcAccessConnector(VpcAccessConnector vpcAccessConnector) { this.vpcAccessConnector = vpcAccessConnector; return this; } /** * The Google Compute Engine zones that are supported by this version in the App Engine flexible * environment. Deprecated. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getZones() { return zones; } /** * The Google Compute Engine zones that are supported by this version in the App Engine flexible * environment. Deprecated. * @param zones zones or {@code null} for none */ public Version setZones(java.util.List<java.lang.String> zones) { this.zones = zones; return this; } @Override public Version set(String fieldName, Object value) { return (Version) super.set(fieldName, value); } @Override public Version clone() { return (Version) super.clone(); } }
googleapis/google-cloud-java
37,607
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListMetadataSchemasRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/metadata_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.aiplatform.v1beta1; /** * * * <pre> * Request message for * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest} */ public final class ListMetadataSchemasRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest) ListMetadataSchemasRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListMetadataSchemasRequest.newBuilder() to construct. private ListMetadataSchemasRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListMetadataSchemasRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListMetadataSchemasRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListMetadataSchemasRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListMetadataSchemasRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.class, com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * The maximum number of MetadataSchemas to return. The service may return * fewer. * Must be in range 1-1000, inclusive. Defaults to 100. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest other = (com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest 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.ListMetadataSchemasRequest 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 * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest) com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListMetadataSchemasRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListMetadataSchemasRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.class, com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto .internal_static_google_cloud_aiplatform_v1beta1_ListMetadataSchemasRequest_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest build() { com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest buildPartial() { com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest result = new com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @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.ListMetadataSchemasRequest) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest other) { if (other == com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The MetadataStore whose MetadataSchemas should be listed. * Format: * `projects/{project}/locations/{location}/metadataStores/{metadatastore}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * The maximum number of MetadataSchemas to return. The service may return * fewer. * Must be in range 1-1000, inclusive. Defaults to 100. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * The maximum number of MetadataSchemas to return. The service may return * fewer. * Must be in range 1-1000, inclusive. Defaults to 100. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The maximum number of MetadataSchemas to return. The service may return * fewer. * Must be in range 1-1000, inclusive. Defaults to 100. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A page token, received from a previous * [MetadataService.ListMetadataSchemas][google.cloud.aiplatform.v1beta1.MetadataService.ListMetadataSchemas] * call. Provide this to retrieve the next page. * * When paginating, all other provided parameters must match the call that * provided the page token. (Otherwise the request will fail with * INVALID_ARGUMENT error.) * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * A query to filter available MetadataSchemas for matching results. * </pre> * * <code>string filter = 4;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @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.ListMetadataSchemasRequest) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest) private static final com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest(); } public static com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListMetadataSchemasRequest> PARSER = new com.google.protobuf.AbstractParser<ListMetadataSchemasRequest>() { @java.lang.Override public ListMetadataSchemasRequest 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<ListMetadataSchemasRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListMetadataSchemasRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.ListMetadataSchemasRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/pulsar
38,064
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentStickyKeyDispatcherMultipleConsumers.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.service.persistent; import static org.apache.pulsar.broker.service.StickyKeyConsumerSelector.STICKY_KEY_HASH_NOT_SET; import com.google.common.annotations.VisibleForTesting; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Predicate; import lombok.Getter; import org.apache.bookkeeper.mledger.Entry; import org.apache.bookkeeper.mledger.ManagedCursor; import org.apache.bookkeeper.mledger.Position; import org.apache.commons.lang3.mutable.MutableBoolean; import org.apache.commons.lang3.mutable.MutableInt; import org.apache.pulsar.broker.ServiceConfiguration; import org.apache.pulsar.broker.service.BrokerServiceException; import org.apache.pulsar.broker.service.ConsistentHashingStickyKeyConsumerSelector; import org.apache.pulsar.broker.service.Consumer; import org.apache.pulsar.broker.service.DrainingHashesTracker; import org.apache.pulsar.broker.service.EntryAndMetadata; import org.apache.pulsar.broker.service.EntryBatchIndexesAcks; import org.apache.pulsar.broker.service.EntryBatchSizes; import org.apache.pulsar.broker.service.HashRangeAutoSplitStickyKeyConsumerSelector; import org.apache.pulsar.broker.service.HashRangeExclusiveStickyKeyConsumerSelector; import org.apache.pulsar.broker.service.ImpactedConsumersResult; import org.apache.pulsar.broker.service.PendingAcksMap; import org.apache.pulsar.broker.service.SendMessageInfo; import org.apache.pulsar.broker.service.StickyKeyConsumerSelector; import org.apache.pulsar.broker.service.StickyKeyDispatcher; import org.apache.pulsar.broker.service.Subscription; import org.apache.pulsar.client.api.Range; import org.apache.pulsar.common.api.proto.CommandSubscribe.SubType; import org.apache.pulsar.common.api.proto.KeySharedMeta; import org.apache.pulsar.common.api.proto.KeySharedMode; import org.apache.pulsar.common.util.FutureUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PersistentStickyKeyDispatcherMultipleConsumers extends PersistentDispatcherMultipleConsumers implements StickyKeyDispatcher { private final boolean allowOutOfOrderDelivery; private final StickyKeyConsumerSelector selector; private final boolean drainingHashesRequired; private boolean skipNextReplayToTriggerLookAhead = false; private final KeySharedMode keySharedMode; @Getter private final DrainingHashesTracker drainingHashesTracker; private final RescheduleReadHandler rescheduleReadHandler; PersistentStickyKeyDispatcherMultipleConsumers(PersistentTopic topic, ManagedCursor cursor, Subscription subscription, ServiceConfiguration conf, KeySharedMeta ksm) { super(topic, cursor, subscription, ksm.isAllowOutOfOrderDelivery()); this.allowOutOfOrderDelivery = ksm.isAllowOutOfOrderDelivery(); this.keySharedMode = ksm.getKeySharedMode(); // recent joined consumer tracking is required only for AUTO_SPLIT mode when out-of-order delivery is disabled this.drainingHashesRequired = keySharedMode == KeySharedMode.AUTO_SPLIT && !allowOutOfOrderDelivery; this.drainingHashesTracker = drainingHashesRequired ? new DrainingHashesTracker(this.getName(), this::stickyKeyHashUnblocked) : null; this.rescheduleReadHandler = new RescheduleReadHandler(conf::getKeySharedUnblockingIntervalMs, topic.getBrokerService().executor(), this::cancelPendingRead, () -> reScheduleReadInMs(0), () -> havePendingRead, this::getReadMoreEntriesCallCount, () -> !redeliveryMessages.isEmpty()); switch (this.keySharedMode) { case AUTO_SPLIT: if (conf.isSubscriptionKeySharedUseConsistentHashing()) { selector = new ConsistentHashingStickyKeyConsumerSelector( conf.getSubscriptionKeySharedConsistentHashingReplicaPoints(), drainingHashesRequired); } else { selector = new HashRangeAutoSplitStickyKeyConsumerSelector(drainingHashesRequired); } break; case STICKY: this.selector = new HashRangeExclusiveStickyKeyConsumerSelector(); break; default: throw new IllegalArgumentException("Invalid key-shared mode: " + keySharedMode); } } private void stickyKeyHashUnblocked(int stickyKeyHash) { if (log.isDebugEnabled()) { if (stickyKeyHash > -1) { log.debug("[{}] Sticky key hash {} is unblocked", getName(), stickyKeyHash); } else { log.debug("[{}] Some sticky key hashes are unblocked", getName()); } } reScheduleReadWithKeySharedUnblockingInterval(); } private void reScheduleReadWithKeySharedUnblockingInterval() { rescheduleReadHandler.rescheduleRead(); } @VisibleForTesting public StickyKeyConsumerSelector getSelector() { return selector; } @Override public synchronized CompletableFuture<Void> addConsumer(Consumer consumer) { if (IS_CLOSED_UPDATER.get(this) == TRUE) { log.warn("[{}] Dispatcher is already closed. Closing consumer {}", name, consumer); consumer.disconnect(); return CompletableFuture.completedFuture(null); } return super.addConsumer(consumer).thenCompose(__ -> selector.addConsumer(consumer)) .thenAccept(impactedConsumers -> { // TODO: Add some way to prevent changes in between the time the consumer is added and the // time the draining hashes are applied. It might be fine for ConsistentHashingStickyKeyConsumerSelector // since it's not really asynchronous, although it returns a CompletableFuture if (drainingHashesRequired) { consumer.setPendingAcksAddHandler(this::handleAddingPendingAck); consumer.setPendingAcksRemoveHandler(new PendingAcksMap.PendingAcksRemoveHandler() { @Override public void handleRemoving(Consumer consumer, long ledgerId, long entryId, int stickyKeyHash, boolean closing) { drainingHashesTracker.reduceRefCount(consumer, stickyKeyHash, closing); } @Override public void startBatch() { drainingHashesTracker.startBatch(); } @Override public void endBatch() { drainingHashesTracker.endBatch(); } }); consumer.setDrainingHashesConsumerStatsUpdater(drainingHashesTracker::updateConsumerStats); registerDrainingHashes(consumer, impactedConsumers.orElseThrow()); } }).exceptionally(ex -> { internalRemoveConsumer(consumer); throw FutureUtil.wrapToCompletionException(ex); }); } private synchronized void registerDrainingHashes(Consumer skipConsumer, ImpactedConsumersResult impactedConsumers) { impactedConsumers.processUpdatedHashRanges((c, updatedHashRanges, opType) -> { if (c != skipConsumer) { c.getPendingAcks().forEach((ledgerId, entryId, batchSize, stickyKeyHash) -> { if (stickyKeyHash == STICKY_KEY_HASH_NOT_SET) { log.warn("[{}] Sticky key hash was missing for {}:{}", getName(), ledgerId, entryId); return; } if (updatedHashRanges.containsStickyKey(stickyKeyHash)) { switch (opType) { //reduce ref count in case the stickyKeyHash was re-assigned to the original consumer case ADD -> { var entry = drainingHashesTracker.getEntry(stickyKeyHash); if (entry != null && entry.getConsumer() == c) { drainingHashesTracker.reduceRefCount(c, stickyKeyHash, false); } } // add the pending ack to the draining hashes tracker if the hash is in the range case REMOVE -> drainingHashesTracker.addEntry(c, stickyKeyHash); } } }); } }); } @Override public synchronized void removeConsumer(Consumer consumer) throws BrokerServiceException { // The consumer must be removed from the selector before calling the superclass removeConsumer method. Optional<ImpactedConsumersResult> impactedConsumers = selector.removeConsumer(consumer); super.removeConsumer(consumer); if (drainingHashesRequired) { // register draining hashes for the impacted consumers and ranges, in case a hash switched from one // consumer to another. This will handle the case where a hash gets switched from an existing // consumer to another existing consumer during removal. registerDrainingHashes(consumer, impactedConsumers.orElseThrow()); drainingHashesTracker.consumerRemoved(consumer); } } @Override protected synchronized void clearComponentsAfterRemovedAllConsumers() { super.clearComponentsAfterRemovedAllConsumers(); if (drainingHashesRequired) { drainingHashesTracker.clear(); } } @Override protected synchronized boolean trySendMessagesToConsumers(ReadType readType, List<Entry> entries) { lastNumberOfEntriesProcessed = 0; long totalMessagesSent = 0; long totalBytesSent = 0; long totalEntries = 0; long totalEntriesProcessed = 0; int entriesCount = entries.size(); // Trigger read more messages if (entriesCount == 0) { return true; } if (consumerSet.isEmpty()) { entries.forEach(Entry::release); cursor.rewind(); return false; } if (!allowOutOfOrderDelivery) { // A corner case that we have to retry a readMoreEntries in order to preserver order delivery. // This may happen when consumer closed. See issue #12885 for details. Optional<Position> firstReplayPosition = getFirstPositionInReplay(); if (firstReplayPosition.isPresent()) { Position replayPosition = firstReplayPosition.get(); if (this.minReplayedPosition != null) { // If relayPosition is a new entry wither smaller position is inserted for redelivery during this // async read, it is possible that this relayPosition should dispatch to consumer first. So in // order to preserver order delivery, we need to discard this read result, and try to trigger a // replay read, that containing "relayPosition", by calling readMoreEntries. if (replayPosition.compareTo(minReplayedPosition) < 0) { if (log.isDebugEnabled()) { log.debug("[{}] Position {} (<{}) is inserted for relay during current {} read, " + "discard this read and retry with readMoreEntries.", name, replayPosition, minReplayedPosition, readType); } if (readType == ReadType.Normal) { entries.forEach(this::addEntryToReplay); } else if (readType == ReadType.Replay) { entries.forEach(Entry::release); } skipNextBackoff = true; return true; } } } } // returns a boolean indicating whether look-ahead could be useful, when there's a consumer // with available permits, and it's not able to make progress because of blocked hashes. MutableBoolean triggerLookAhead = new MutableBoolean(); // filter and group the entries by consumer for dispatching final Map<Consumer, List<Entry>> entriesByConsumerForDispatching = filterAndGroupEntriesForDispatching(entries, readType, triggerLookAhead); AtomicInteger remainingConsumersToFinishSending = new AtomicInteger(entriesByConsumerForDispatching.size()); for (Map.Entry<Consumer, List<Entry>> current : entriesByConsumerForDispatching.entrySet()) { Consumer consumer = current.getKey(); List<Entry> entriesForConsumer = current.getValue(); if (log.isDebugEnabled()) { log.debug("[{}] select consumer {} with messages num {}, read type is {}", name, consumer.consumerName(), entriesForConsumer.size(), readType); } // remove positions first from replay list first : sendMessages recycles entries if (readType == ReadType.Replay) { for (Entry entry : entriesForConsumer) { redeliveryMessages.remove(entry.getLedgerId(), entry.getEntryId()); } } SendMessageInfo sendMessageInfo = SendMessageInfo.getThreadLocal(); EntryBatchSizes batchSizes = EntryBatchSizes.get(entriesForConsumer.size()); EntryBatchIndexesAcks batchIndexesAcks = EntryBatchIndexesAcks.get(entriesForConsumer.size()); totalEntries += filterEntriesForConsumer(entriesForConsumer, batchSizes, sendMessageInfo, batchIndexesAcks, cursor, readType == ReadType.Replay, consumer); totalEntriesProcessed += entriesForConsumer.size(); consumer.sendMessages(entriesForConsumer, batchSizes, batchIndexesAcks, sendMessageInfo.getTotalMessages(), sendMessageInfo.getTotalBytes(), sendMessageInfo.getTotalChunkedMessages(), getRedeliveryTracker()).addListener(future -> { if (future.isDone() && remainingConsumersToFinishSending.decrementAndGet() == 0) { readMoreEntriesAsync(); } }); TOTAL_AVAILABLE_PERMITS_UPDATER.getAndAdd(this, -(sendMessageInfo.getTotalMessages() - batchIndexesAcks.getTotalAckedIndexCount())); totalMessagesSent += sendMessageInfo.getTotalMessages(); totalBytesSent += sendMessageInfo.getTotalBytes(); } lastNumberOfEntriesProcessed = (int) totalEntriesProcessed; // acquire message-dispatch permits for already delivered messages acquirePermitsForDeliveredMessages(topic, cursor, totalEntries, totalMessagesSent, totalBytesSent); // trigger read more messages if necessary if (triggerLookAhead.booleanValue()) { // When all messages get filtered and no messages are sent, we should read more entries, "look ahead" // so that a possible next batch of messages might contain messages that can be dispatched. // This is done only when there's a consumer with available permits, and it's not able to make progress // because of blocked hashes. Without this rule we would be looking ahead in the stream while the // new consumers are not ready to accept the new messages, // therefore would be most likely only increase the distance between read-position and mark-delete position. skipNextReplayToTriggerLookAhead = true; // skip backoff delay before reading ahead in the "look ahead" mode to prevent any additional latency // only skip the delay if there are more entries to read skipNextBackoff = cursor.hasMoreEntries(); return true; } // if no messages were sent to consumers, we should retry if (totalEntries == 0) { return true; } return false; } /** * Check if the sticky hash is already draining or blocked in the replay queue. * If it is, add the message to replay and return false so that the message isn't sent to a consumer. * * @param ledgerId the ledger id of the message * @param entryId the entry id of the message * @param stickyKeyHash the sticky hash of the message * @return true if the message should be added to pending acks and allow sending, false otherwise */ private boolean handleAddingPendingAck(Consumer consumer, long ledgerId, long entryId, int stickyKeyHash) { if (stickyKeyHash == STICKY_KEY_HASH_NOT_SET) { log.warn("[{}] Sticky key hash is missing for {}:{}", getName(), ledgerId, entryId); throw new IllegalArgumentException("Sticky key hash is missing for " + ledgerId + ":" + entryId); } DrainingHashesTracker.DrainingHashEntry drainingHashEntry = drainingHashesTracker.getEntry(stickyKeyHash); if (drainingHashEntry != null && drainingHashEntry.getConsumer() != consumer) { log.warn("[{}] Another consumer id {} is already draining hash {}. Skipping adding {}:{} to pending acks " + "for consumer {}. Adding the message to replay.", getName(), drainingHashEntry.getConsumer(), stickyKeyHash, ledgerId, entryId, consumer); addMessageToReplay(ledgerId, entryId, stickyKeyHash); // block message from sending return false; } if (log.isDebugEnabled()) { log.debug("[{}] Adding {}:{} to pending acks for consumer id:{} name:{} with sticky key hash {}", getName(), ledgerId, entryId, consumer.consumerId(), consumer.consumerName(), stickyKeyHash); } // allow adding the message to pending acks and sending the message to the consumer return true; } private boolean isReplayQueueSizeBelowLimit() { return redeliveryMessages.size() < getEffectiveLookAheadLimit(); } private int getEffectiveLookAheadLimit() { return getEffectiveLookAheadLimit(serviceConfig, consumerList.size()); } static int getEffectiveLookAheadLimit(ServiceConfiguration serviceConfig, int consumerCount) { int perConsumerLimit = serviceConfig.getKeySharedLookAheadMsgInReplayThresholdPerConsumer(); int perSubscriptionLimit = serviceConfig.getKeySharedLookAheadMsgInReplayThresholdPerSubscription(); int effectiveLimit; if (perConsumerLimit <= 0) { effectiveLimit = perSubscriptionLimit; } else { effectiveLimit = perConsumerLimit * consumerCount; if (perSubscriptionLimit > 0 && perSubscriptionLimit < effectiveLimit) { effectiveLimit = perSubscriptionLimit; } } if (effectiveLimit <= 0) { // use max unacked messages limits if key shared look-ahead limits are disabled int maxUnackedMessagesPerSubscription = serviceConfig.getMaxUnackedMessagesPerSubscription(); if (maxUnackedMessagesPerSubscription <= 0) { maxUnackedMessagesPerSubscription = Integer.MAX_VALUE; } int maxUnackedMessagesByConsumers = consumerCount * serviceConfig.getMaxUnackedMessagesPerConsumer(); if (maxUnackedMessagesByConsumers <= 0) { maxUnackedMessagesByConsumers = Integer.MAX_VALUE; } effectiveLimit = Math.min(maxUnackedMessagesPerSubscription, maxUnackedMessagesByConsumers); } return effectiveLimit; } // groups the entries by consumer and filters out the entries that should not be dispatched // the entries are handled in the order they are received instead of first grouping them by consumer and // then filtering them private Map<Consumer, List<Entry>> filterAndGroupEntriesForDispatching(List<Entry> entries, ReadType readType, MutableBoolean triggerLookAhead) { // entries grouped by consumer Map<Consumer, List<Entry>> entriesGroupedByConsumer = new HashMap<>(); // permits for consumer, permits are for entries/batches Map<Consumer, MutableInt> permitsForConsumer = new HashMap<>(); boolean lookAheadAllowed = isReplayQueueSizeBelowLimit(); // in normal read mode, keep track of consumers that are blocked by hash, to check if look-ahead could be useful Set<Consumer> blockedByHashConsumers = lookAheadAllowed && readType == ReadType.Normal ? new HashSet<>() : null; // in replay read mode, keep track of consumers for entries, used for look-ahead check Set<Consumer> consumersForEntriesForLookaheadCheck = lookAheadAllowed ? new HashSet<>() : null; // track already blocked hashes to block any further messages with the same hash IntSet alreadyBlockedHashes = new IntOpenHashSet(); for (Entry inputEntry : entries) { EntryAndMetadata entry; if (inputEntry instanceof EntryAndMetadata entryAndMetadataInstance) { entry = entryAndMetadataInstance; } else { // replace the input entry with EntryAndMetadata instance. In addition to the entry and metadata, // it will also carry the calculated sticky key hash entry = EntryAndMetadata.create(inputEntry); } int stickyKeyHash = getStickyKeyHash(entry); Consumer consumer = null; boolean blockedByHash = false; boolean dispatchEntry = false; // check if the hash is already blocked boolean hashIsAlreadyBlocked = alreadyBlockedHashes.contains(stickyKeyHash); if (!hashIsAlreadyBlocked) { consumer = selector.select(stickyKeyHash); if (consumer != null) { if (lookAheadAllowed) { consumersForEntriesForLookaheadCheck.add(consumer); } final var canUpdateBlockedByHash = lookAheadAllowed && readType == ReadType.Normal; MutableInt permits = permitsForConsumer.computeIfAbsent(consumer, k -> new MutableInt(getAvailablePermits(k))); // a consumer was found for the sticky key hash and the entry can be dispatched if (permits.intValue() > 0) { boolean canDispatchEntry = canDispatchEntry(consumer, entry, readType, stickyKeyHash); if (canDispatchEntry) { // decrement the permits for the consumer permits.decrement(); // allow the entry to be dispatched dispatchEntry = true; } else if (canUpdateBlockedByHash) { blockedByHash = true; } } } } if (dispatchEntry) { // add the entry to consumer's entry list for dispatching List<Entry> consumerEntries = entriesGroupedByConsumer.computeIfAbsent(consumer, k -> new ArrayList<>()); consumerEntries.add(entry); } else { if (!hashIsAlreadyBlocked) { // the hash is blocked, add it to the set of blocked hashes alreadyBlockedHashes.add(stickyKeyHash); } if (blockedByHash) { // the entry is blocked by hash, add the consumer to the blocked set blockedByHashConsumers.add(consumer); } if (entry.getReadCountHandler() != null) { // increment the expected read count for the entry, so that it can be cached for a longer time entry.getReadCountHandler().incrementExpectedReadCount(); } // add the message to replay addMessageToReplay(entry.getLedgerId(), entry.getEntryId(), stickyKeyHash); // release the entry as it will not be dispatched entry.release(); } } // // determine whether look-ahead could be useful for making more progress // if (lookAheadAllowed && entriesGroupedByConsumer.isEmpty()) { // check if look-ahead could be useful for the consumers that are blocked by a hash that is in the replay // queue. This check applies only to the normal read mode. if (readType == ReadType.Normal) { for (Consumer consumer : blockedByHashConsumers) { // if the consumer isn't in the entriesGroupedByConsumer, it means that it won't receive any // messages // if it has available permits, then look-ahead could be useful for this particular consumer // to make further progress if (!entriesGroupedByConsumer.containsKey(consumer) && permitsForConsumer.get(consumer).intValue() > 0) { triggerLookAhead.setTrue(); break; } } } // check if look-ahead could be useful for other consumers if (!triggerLookAhead.booleanValue()) { for (Consumer consumer : getConsumers()) { // filter out the consumers that are already checked when the entries were processed for entries if (!consumersForEntriesForLookaheadCheck.contains(consumer)) { // if another consumer has available permits, then look-ahead could be useful if (getAvailablePermits(consumer) > 0) { triggerLookAhead.setTrue(); break; } } } } } return entriesGroupedByConsumer; } // checks if the entry can be dispatched to the consumer private boolean canDispatchEntry(Consumer consumer, Entry entry, ReadType readType, int stickyKeyHash) { // If redeliveryMessages contains messages that correspond to the same hash as the entry to be dispatched // do not send those messages for order guarantee if (readType == ReadType.Normal && redeliveryMessages.containsStickyKeyHash(stickyKeyHash)) { return false; } if (drainingHashesRequired) { // If the hash is draining, do not send the message if (drainingHashesTracker.shouldBlockStickyKeyHash(consumer, stickyKeyHash)) { return false; } } return true; } /** * Creates a filter for replaying messages. The filter is stateful and shouldn't be cached or reused. * @see PersistentDispatcherMultipleConsumers#createFilterForReplay() */ @Override protected Predicate<Position> createFilterForReplay() { return new ReplayPositionFilter(); } /** * Filter for replaying messages. The filter is stateful for a single invocation and shouldn't be cached, shared * or reused. This is a short-lived object, and optimizing it for the "no garbage" coding style of Pulsar is * unnecessary since the JVM can optimize allocations for short-lived objects. */ private class ReplayPositionFilter implements Predicate<Position> { // tracks the available permits for each consumer for the duration of the filter usage // the filter is stateful and shouldn't be shared or reused later private final Map<Consumer, MutableInt> availablePermitsMap = new HashMap<>(); // tracks the hashes that have been blocked during the filtering // it is necessary to block all later messages after a hash gets blocked so that ordering is preserved private final Set<Long> alreadyBlockedHashes = new HashSet<>(); @Override public boolean test(Position position) { // if out of order delivery is allowed, then any position will be replayed if (isAllowOutOfOrderDelivery()) { return true; } // lookup the sticky key hash for the entry at the replay position Long stickyKeyHash = redeliveryMessages.getHash(position.getLedgerId(), position.getEntryId()); if (stickyKeyHash == null) { // the sticky key hash is missing for delayed messages, the filtering will happen at the time of // dispatch after reading the entry from the ledger if (log.isDebugEnabled()) { log.debug("[{}] replay of entry at position {} doesn't contain sticky key hash.", name, position); } return true; } // check if the hash is already blocked, if so, then replaying of the position should be skipped // to preserve ordering if (alreadyBlockedHashes.contains(stickyKeyHash)) { return false; } // find the consumer for the sticky key hash Consumer consumer = selector.select(stickyKeyHash.intValue()); // skip replaying the message position if there's no assigned consumer if (consumer == null) { alreadyBlockedHashes.add(stickyKeyHash); return false; } // lookup the available permits for the consumer MutableInt availablePermits = availablePermitsMap.computeIfAbsent(consumer, k -> new MutableInt(getAvailablePermits(consumer))); // skip replaying the message position if the consumer has no available permits if (availablePermits.intValue() <= 0) { alreadyBlockedHashes.add(stickyKeyHash); return false; } if (drainingHashesRequired && drainingHashesTracker.shouldBlockStickyKeyHash(consumer, stickyKeyHash.intValue())) { // the hash is draining and the consumer is not the draining consumer alreadyBlockedHashes.add(stickyKeyHash); return false; } availablePermits.decrement(); return true; } } @Override protected int getStickyKeyHash(Entry entry) { if (entry instanceof EntryAndMetadata entryAndMetadata) { // use the cached sticky key hash if available, otherwise calculate the sticky key hash and cache it return entryAndMetadata.getOrUpdateCachedStickyKeyHash(selector::makeStickyKeyHash); } return selector.makeStickyKeyHash(peekStickyKey(entry)); } @Override public void markDeletePositionMoveForward() { // reschedule a read with a backoff after moving the mark-delete position forward since there might have // been consumers that were blocked by hash and couldn't make progress reScheduleReadWithKeySharedUnblockingInterval(); } /** * The dispatcher will skip replaying messages when all messages in the replay queue are filtered out when * skipNextReplayToTriggerLookAhead=true. The flag gets resetted after the call. * * If we're stuck on replay, we want to move forward reading on the topic (until the configured look ahead * limits kick in), instead of keep replaying the same old messages, since the consumer that these * messages are routing to might be busy at the moment. * * Please see {@link ServiceConfiguration#getKeySharedLookAheadMsgInReplayThresholdPerConsumer} and * {@link ServiceConfiguration#getKeySharedLookAheadMsgInReplayThresholdPerSubscription} for configuring the limits. */ @Override protected synchronized boolean canReplayMessages() { if (skipNextReplayToTriggerLookAhead) { skipNextReplayToTriggerLookAhead = false; return false; } return true; } private int getAvailablePermits(Consumer c) { // skip consumers that are currently closing if (!c.cnx().isActive()) { return 0; } int availablePermits = Math.max(c.getAvailablePermits(), 0); if (availablePermits > 0 && c.getMaxUnackedMessages() > 0) { // Calculate the maximum number of additional unacked messages allowed int maxAdditionalUnackedMessages = Math.max(c.getMaxUnackedMessages() - c.getUnackedMessages(), 0); if (maxAdditionalUnackedMessages == 0) { // if the consumer has reached the max unacked messages, then no more messages can be dispatched return 0; } // Estimate the remaining permits based on the average messages per entry // add "avgMessagesPerEntry - 1" to round up the division to the next integer without the need to use // floating point arithmetic int avgMessagesPerEntry = Math.max(c.getAvgMessagesPerEntry(), 1); int estimatedRemainingPermits = (maxAdditionalUnackedMessages + avgMessagesPerEntry - 1) / avgMessagesPerEntry; // return the minimum of current available permits and estimated remaining permits return Math.min(availablePermits, estimatedRemainingPermits); } else { return availablePermits; } } /** * For Key_Shared subscription, the dispatcher will not read more entries while there are pending reads * or pending replay reads. * @return true if there are no pending reads or pending replay reads */ @Override protected boolean doesntHavePendingRead() { return !havePendingRead && !havePendingReplayRead; } /** * For Key_Shared subscription, the dispatcher will not attempt to read more entries if the replay queue size * has reached the limit or if there are no consumers with permits. */ @Override protected boolean isNormalReadAllowed() { // don't allow reading more if the replay queue size has reached the limit if (!isReplayQueueSizeBelowLimit()) { return false; } for (Consumer consumer : consumerList) { // skip blocked consumers if (consumer == null || consumer.isBlocked()) { continue; } // before reading more, check that there's at least one consumer that has permits if (getAvailablePermits(consumer) > 0) { return true; } } return false; } @Override protected int getMaxEntriesReadLimit() { // prevent the redelivery queue from growing over the limit by limiting the number of entries to read // to the maximum number of entries that can be added to the redelivery queue return Math.max(getEffectiveLookAheadLimit() - redeliveryMessages.size(), 1); } /** * When a normal read is not allowed, the dispatcher will reschedule a read with a backoff. */ @Override protected void handleNormalReadNotAllowed() { if (log.isDebugEnabled()) { log.debug("[{}] [{}] Skipping read for the topic since normal read isn't allowed. " + "Rescheduling a read with a backoff.", topic.getName(), getSubscriptionName()); } reScheduleReadWithBackoff(); } @Override public SubType getType() { return SubType.Key_Shared; } @Override protected Set<? extends Position> asyncReplayEntries(Set<? extends Position> positions) { return cursor.asyncReplayEntries(positions, this, ReadType.Replay, true); } public KeySharedMode getKeySharedMode() { return this.keySharedMode; } public boolean isAllowOutOfOrderDelivery() { return this.allowOutOfOrderDelivery; } public boolean hasSameKeySharedPolicy(KeySharedMeta ksm) { return (ksm.getKeySharedMode() == this.keySharedMode && ksm.isAllowOutOfOrderDelivery() == this.allowOutOfOrderDelivery); } public Map<Consumer, List<Range>> getConsumerKeyHashRanges() { return selector.getConsumerKeyHashRanges(); } private static final Logger log = LoggerFactory.getLogger(PersistentStickyKeyDispatcherMultipleConsumers.class); }
apache/tomcat80
37,444
test/org/apache/catalina/core/TestStandardContext.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.core; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.HttpConstraintElement; import javax.servlet.HttpMethodConstraintElement; import javax.servlet.MultipartConfigElement; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.ServletSecurityElement; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.HttpMethodConstraint; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.catalina.Wrapper; import org.apache.catalina.authenticator.BasicAuthenticator; import org.apache.catalina.loader.WebappLoader; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.TesterMapRealm; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.jasper.servlet.JasperInitializer; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.descriptor.web.FilterDef; import org.apache.tomcat.util.descriptor.web.FilterMap; import org.apache.tomcat.util.descriptor.web.LoginConfig; public class TestStandardContext extends TomcatBaseTest { private static final String REQUEST = "GET / HTTP/1.1\r\n" + "Host: anything\r\n" + "Connection: close\r\n" + "\r\n"; @Test public void testBug46243() throws Exception { // This tests that if a Filter init() fails then the web application // is not put into service. (BZ 46243) // This also tests that if the cause of the failure is gone, // the context can be started without a need to redeploy it. // Set up a container Tomcat tomcat = getTomcatInstance(); File docBase = new File(tomcat.getHost().getAppBaseFile(), "ROOT"); if (!docBase.mkdirs() && !docBase.isDirectory()) { Assert.fail("Unable to create docBase"); } Context root = tomcat.addContext("", "ROOT"); configureTest46243Context(root, true); tomcat.start(); // Configure the client Bug46243Client client = new Bug46243Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] { REQUEST }); client.connect(); client.processRequest(); Assert.assertTrue(client.isResponse404()); // Context failed to start. This checks that automatic transition // from FAILED to STOPPED state was successful. Assert.assertEquals(LifecycleState.STOPPED, root.getState()); // Prepare context for the second attempt // Configuration was cleared on stop() thanks to // StandardContext.resetContext(), so we need to configure it again // from scratch. configureTest46243Context(root, false); root.start(); // The same request is processed successfully client.connect(); client.processRequest(); Assert.assertTrue(client.isResponse200()); Assert.assertEquals(Bug46243Filter.class.getName() + HelloWorldServlet.RESPONSE_TEXT, client.getResponseBody()); } private static void configureTest46243Context(Context context, boolean fail) { // Add a test filter that fails FilterDef filterDef = new FilterDef(); filterDef.setFilterClass(Bug46243Filter.class.getName()); filterDef.setFilterName("Bug46243"); filterDef.addInitParameter("fail", Boolean.toString(fail)); context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName("Bug46243"); filterMap.addURLPatternDecoded("*"); context.addFilterMap(filterMap); // Add a test servlet so there is something to generate a response if // it works (although it shouldn't) Tomcat.addServlet(context, "Bug46243", new HelloWorldServlet()); context.addServletMappingDecoded("/", "Bug46243"); } private static final class Bug46243Client extends SimpleHttpClient { public Bug46243Client(int port) { setPort(port); } @Override public boolean isResponseBodyOK() { // Don't care about the body in this test return true; } } public static final class Bug46243Filter implements Filter { @Override public void destroy() { // NOOP } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { PrintWriter out = response.getWriter(); out.print(getClass().getName()); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { boolean fail = filterConfig.getInitParameter("fail").equals("true"); if (fail) { throw new ServletException("Init fail (test)", new ClassNotFoundException()); } } } @Test public void testWebappLoaderStartFail() throws Exception { // Test that if WebappLoader start() fails and if the cause of // the failure is gone, the context can be started without // a need to redeploy it. // Set up a container Tomcat tomcat = getTomcatInstance(); tomcat.start(); // To not start Context automatically, as we have to configure it first ((ContainerBase) tomcat.getHost()).setStartChildren(false); FailingWebappLoader loader = new FailingWebappLoader(); File root = new File("test/webapp"); Context context = tomcat.addWebapp("", root.getAbsolutePath()); context.setLoader(loader); try { context.start(); Assert.fail(); } catch (LifecycleException ex) { // As expected } Assert.assertEquals(LifecycleState.FAILED, context.getState()); // The second attempt loader.setFail(false); context.start(); Assert.assertEquals(LifecycleState.STARTED, context.getState()); // Using a test from testBug49922() to check that the webapp is running ByteChunk result = getUrl("http://localhost:" + getPort() + "/bug49922/target"); Assert.assertEquals("Target", result.toString()); } @Test public void testWebappListenerConfigureFail() throws Exception { // Test that if LifecycleListener on webapp fails during // configure_start event and if the cause of the failure is gone, // the context can be started without a need to redeploy it. // Set up a container Tomcat tomcat = getTomcatInstance(); tomcat.start(); // To not start Context automatically, as we have to configure it first ((ContainerBase) tomcat.getHost()).setStartChildren(false); FailingLifecycleListener listener = new FailingLifecycleListener(); File root = new File("test/webapp"); Context context = tomcat.addWebapp("", root.getAbsolutePath()); context.addLifecycleListener(listener); try { context.start(); Assert.fail(); } catch (LifecycleException ex) { // As expected } Assert.assertEquals(LifecycleState.FAILED, context.getState()); // The second attempt listener.setFail(false); context.start(); Assert.assertEquals(LifecycleState.STARTED, context.getState()); // Using a test from testBug49922() to check that the webapp is running ByteChunk result = getUrl("http://localhost:" + getPort() + "/bug49922/target"); Assert.assertEquals("Target", result.toString()); } private static class FailingWebappLoader extends WebappLoader { private boolean fail = true; protected void setFail(boolean fail) { this.fail = fail; } @Override protected void startInternal() throws LifecycleException { if (fail) { throw new RuntimeException("Start fail (test)"); } super.startInternal(); } } private static class FailingLifecycleListener implements LifecycleListener { private final String failEvent = Lifecycle.CONFIGURE_START_EVENT; private boolean fail = true; protected void setFail(boolean fail) { this.fail = fail; } @Override public void lifecycleEvent(LifecycleEvent event) { if (fail && event.getType().equals(failEvent)) { throw new RuntimeException(failEvent + " fail (test)"); } } } @Test public void testBug49922() throws Exception { // Test that filter mapping works. Test that the same filter is // called only once, even if is selected by several mapping // url-patterns or by both a url-pattern and a servlet-name. getTomcatInstanceTestWebapp(false, true); ByteChunk result = new ByteChunk(); // Check filter and servlet aren't called int rc = getUrl("http://localhost:" + getPort() + "/test/bug49922/foo", result, null); Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); Assert.assertTrue(result.getLength() > 0); // Check extension mapping works result = getUrl("http://localhost:" + getPort() + "/test/foo.do"); Assert.assertEquals("FilterServlet", result.toString()); // Check path mapping works result = getUrl("http://localhost:" + getPort() + "/test/bug49922/servlet"); Assert.assertEquals("FilterServlet", result.toString()); // Check servlet name mapping works result = getUrl("http://localhost:" + getPort() + "/test/foo.od"); Assert.assertEquals("FilterServlet", result.toString()); // Check filter is only called once result = getUrl("http://localhost:" + getPort() + "/test/bug49922/servlet/foo.do"); Assert.assertEquals("FilterServlet", result.toString()); result = getUrl("http://localhost:" + getPort() + "/test/bug49922/servlet/foo.od"); Assert.assertEquals("FilterServlet", result.toString()); // Check dispatcher mapping result = getUrl("http://localhost:" + getPort() + "/test/bug49922/target"); Assert.assertEquals("Target", result.toString()); result = getUrl("http://localhost:" + getPort() + "/test/bug49922/forward"); Assert.assertEquals("FilterTarget", result.toString()); result = getUrl("http://localhost:" + getPort() + "/test/bug49922/include"); Assert.assertEquals("IncludeFilterTarget", result.toString()); } public static final class Bug49922Filter implements Filter { @Override public void destroy() { // NOOP } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.setContentType("text/plain"); response.getWriter().print("Filter"); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { // NOOP } } public static final class Bug49922ForwardServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/bug49922/target").forward(req, resp); } } public static final class Bug49922IncludeServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("Include"); req.getRequestDispatcher("/bug49922/target").include(req, resp); } } public static final class Bug49922TargetServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("Target"); } } public static final class Bug49922Servlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("Servlet"); } } @Test public void testBug50015() throws Exception { // Test that configuring servlet security constraints programmatically // does work. // Set up a container Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); // Setup realm TesterMapRealm realm = new TesterMapRealm(); realm.addUser("tomcat", "tomcat"); realm.addUserRole("tomcat", "tomcat"); ctx.setRealm(realm); // Configure app for BASIC auth LoginConfig lc = new LoginConfig(); lc.setAuthMethod("BASIC"); ctx.setLoginConfig(lc); ctx.getPipeline().addValve(new BasicAuthenticator()); // Add ServletContainerInitializer ServletContainerInitializer sci = new Bug50015SCI(); ctx.addServletContainerInitializer(sci, null); // Start the context tomcat.start(); // Request the first servlet ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/bug50015", bc, null); // Check for a 401 Assert.assertNotSame("OK", bc.toString()); Assert.assertEquals(401, rc); } public static final class Bug50015SCI implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // Register and map servlet Servlet s = new TesterServlet(); ServletRegistration.Dynamic sr = ctx.addServlet("bug50015", s); sr.addMapping("/bug50015"); // Limit access to users in the Tomcat role HttpConstraintElement hce = new HttpConstraintElement( TransportGuarantee.NONE, "tomcat"); ServletSecurityElement sse = new ServletSecurityElement(hce); sr.setServletSecurity(sse); } } @Test public void testDenyUncoveredHttpMethodsSCITrue() throws Exception { doTestDenyUncoveredHttpMethodsSCI(true); } @Test public void testDenyUncoveredHttpMethodsSCIFalse() throws Exception { doTestDenyUncoveredHttpMethodsSCI(false); } private void doTestDenyUncoveredHttpMethodsSCI(boolean enableDeny) throws Exception { // Test that denying uncovered HTTP methods when adding servlet security // constraints programmatically does work. // Set up a container Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); ctx.setDenyUncoveredHttpMethods(enableDeny); // Setup realm TesterMapRealm realm = new TesterMapRealm(); realm.addUser("tomcat", "tomcat"); realm.addUserRole("tomcat", "tomcat"); ctx.setRealm(realm); // Configure app for BASIC auth LoginConfig lc = new LoginConfig(); lc.setAuthMethod("BASIC"); ctx.setLoginConfig(lc); ctx.getPipeline().addValve(new BasicAuthenticator()); // Add ServletContainerInitializer ServletContainerInitializer sci = new DenyUncoveredHttpMethodsSCI(); ctx.addServletContainerInitializer(sci, null); // Start the context tomcat.start(); // Request the first servlet ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test", bc, null); // Check for a 401 if (enableDeny) { // Should be default error page Assert.assertTrue(bc.toString().contains("403")); Assert.assertEquals(403, rc); } else { Assert.assertEquals("OK", bc.toString()); Assert.assertEquals(200, rc); } } public static final class DenyUncoveredHttpMethodsSCI implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // Register and map servlet Servlet s = new TesterServlet(); ServletRegistration.Dynamic sr = ctx.addServlet("test", s); sr.addMapping("/test"); // Add a constraint with uncovered methods HttpConstraintElement hce = new HttpConstraintElement( TransportGuarantee.NONE, "tomcat"); HttpMethodConstraintElement hmce = new HttpMethodConstraintElement("POST", hce); Set<HttpMethodConstraintElement> hmces = new HashSet<>(); hmces.add(hmce); ServletSecurityElement sse = new ServletSecurityElement(hmces); sr.setServletSecurity(sse); } } @Test public void testBug51376a() throws Exception { doTestBug51376(false); } @Test public void testBug51376b() throws Exception { doTestBug51376(true); } private void doTestBug51376(boolean loadOnStartUp) throws Exception { // Test that for a servlet that was added programmatically its // loadOnStartup property is honored and its init() and destroy() // methods are called. // Set up a container Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); // Add ServletContainerInitializer Bug51376SCI sci = new Bug51376SCI(loadOnStartUp); ctx.addServletContainerInitializer(sci, null); // Start the context tomcat.start(); // Stop the context ctx.stop(); // Make sure that init() and destroy() were called correctly Assert.assertTrue(sci.getServlet().isOk()); Assert.assertTrue(loadOnStartUp == sci.getServlet().isInitCalled()); } public static final class Bug51376SCI implements ServletContainerInitializer { private Bug51376Servlet s = null; private boolean loadOnStartUp; public Bug51376SCI(boolean loadOnStartUp) { this.loadOnStartUp = loadOnStartUp; } private Bug51376Servlet getServlet() { return s; } @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { // Register and map servlet s = new Bug51376Servlet(); ServletRegistration.Dynamic sr = ctx.addServlet("bug51376", s); sr.addMapping("/bug51376"); if (loadOnStartUp) { sr.setLoadOnStartup(1); } } } public static final class Bug51376Servlet extends HttpServlet { private static final long serialVersionUID = 1L; private Boolean initOk = null; private Boolean destroyOk = null; @Override public void init() { if (initOk == null && destroyOk == null) { initOk = Boolean.TRUE; } else { initOk = Boolean.FALSE; } } @Override public void destroy() { if (initOk.booleanValue() && destroyOk == null) { destroyOk = Boolean.TRUE; } else { destroyOk = Boolean.FALSE; } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().write("OK"); } protected boolean isOk() { if (initOk != null && initOk.booleanValue() && destroyOk != null && destroyOk.booleanValue()) { return true; } else if (initOk == null && destroyOk == null) { return true; } else { return false; } } protected boolean isInitCalled() { return initOk != null && initOk.booleanValue(); } } /** * Test case for bug 49711: HttpServletRequest.getParts does not work * in a filter. */ @Test public void testBug49711() { Bug49711Client client = new Bug49711Client(); // Make sure non-multipart works properly client.doRequest("/regular", false, false); // Servlet attempts to read parts which will trigger an ISE Assert.assertTrue(client.isResponse500()); client.reset(); // Make sure regular multipart works properly client.doRequest("/multipart", false, true); // send multipart request Assert.assertEquals("Regular multipart doesn't work", "parts=1", client.getResponseBody()); client.reset(); // Make casual multipart request to "regular" servlet w/o config // We expect an error client.doRequest("/regular", false, true); // send multipart request // Servlet attempts to read parts which will trigger an ISE Assert.assertTrue(client.isResponse500()); client.reset(); // Make casual multipart request to "regular" servlet w/config // We expect that the server /will/ parse the parts, even though // there is no @MultipartConfig client.doRequest("/regular", true, true); // send multipart request Assert.assertEquals("Incorrect response for configured casual multipart request", "parts=1", client.getResponseBody()); client.reset(); } private static class Bug49711Servlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the parameters and values back as plain text resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); out.println("parts=" + (null == req.getParts() ? "null" : Integer.valueOf(req.getParts().size()))); } } @MultipartConfig private static class Bug49711Servlet_multipart extends Bug49711Servlet { private static final long serialVersionUID = 1L; } /** * Bug 49711 test client: test for casual getParts calls. */ private class Bug49711Client extends SimpleHttpClient { private boolean init; private Context context; private synchronized void init() throws Exception { if (init) return; Tomcat tomcat = getTomcatInstance(); context = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(context, "regular", new Bug49711Servlet()); Wrapper w = Tomcat.addServlet(context, "multipart", new Bug49711Servlet_multipart()); // Tomcat.addServlet does not respect annotations, so we have // to set our own MultipartConfigElement. w.setMultipartConfigElement(new MultipartConfigElement("")); context.addServletMappingDecoded("/regular", "regular"); context.addServletMappingDecoded("/multipart", "multipart"); tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); init = true; } private Exception doRequest(String uri, boolean allowCasualMultipart, boolean makeMultipartRequest) { try { init(); context.setAllowCasualMultipartParsing(allowCasualMultipart); // Open connection connect(); // Send specified request body using method String[] request; if(makeMultipartRequest) { String boundary = "--simpleboundary"; String content = "--" + boundary + CRLF + "Content-Disposition: form-data; name=\"name\"" + CRLF + CRLF + "value" + CRLF + "--" + boundary + "--" + CRLF; // Re-encode the content so that bytes = characters content = new String(content.getBytes("UTF-8"), "ASCII"); request = new String[] { "POST http://localhost:" + getPort() + uri + " HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: close" + CRLF + "Content-Type: multipart/form-data; boundary=" + boundary + CRLF + "Content-Length: " + content.length() + CRLF + CRLF + content + CRLF }; } else { request = new String[] { "GET http://localhost:" + getPort() + uri + " HTTP/1.1" + CRLF + "Host: localhost" + CRLF + "Connection: close" + CRLF + CRLF }; } setRequest(request); processRequest(); // blocks until response has been read // Close the connection disconnect(); } catch (Exception e) { return e; } return null; } @Override public boolean isResponseBodyOK() { return false; // Don't care } } @Test(expected = IllegalArgumentException.class) public void testAddPostConstructMethodNullClassName() { new StandardContext().addPostConstructMethod(null, ""); } @Test(expected = IllegalArgumentException.class) public void testAddPostConstructMethodNullMethodName() { new StandardContext().addPostConstructMethod("", null); } @Test(expected = IllegalArgumentException.class) public void testAddPostConstructMethodConflicts() { StandardContext standardContext = new StandardContext(); standardContext.addPostConstructMethod("a", "a"); standardContext.addPostConstructMethod("a", "b"); } @Test(expected = IllegalArgumentException.class) public void testAddPreDestroyMethodNullClassName() { new StandardContext().addPreDestroyMethod(null, ""); } @Test(expected = IllegalArgumentException.class) public void testAddPreDestroyMethodNullMethodName() { new StandardContext().addPreDestroyMethod("", null); } @Test(expected = IllegalArgumentException.class) public void testAddPreDestroyMethodConflicts() { StandardContext standardContext = new StandardContext(); standardContext.addPreDestroyMethod("a", "a"); standardContext.addPreDestroyMethod("a", "b"); } @Test public void testTldListener() throws Exception { // Set up a container Tomcat tomcat = getTomcatInstance(); File docBase = new File("test/webapp-3.0"); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); ctx.addServletContainerInitializer(new JasperInitializer(), null); // Start the context tomcat.start(); // Stop the context ctx.stop(); String log = TesterTldListener.getLog(); Assert.assertTrue(log, log.contains("PASS-01")); Assert.assertTrue(log, log.contains("PASS-02")); Assert.assertFalse(log, log.contains("FAIL")); } @Test public void testFlagFailCtxIfServletStartFails() throws Exception { Tomcat tomcat = getTomcatInstance(); File docBase = new File(System.getProperty("java.io.tmpdir")); StandardContext context = (StandardContext) tomcat.addContext("", docBase.getAbsolutePath()); // first we test the flag itself, which can be set on the Host and // Context Assert.assertFalse(context.getComputedFailCtxIfServletStartFails()); StandardHost host = (StandardHost) tomcat.getHost(); host.setFailCtxIfServletStartFails(true); Assert.assertTrue(context.getComputedFailCtxIfServletStartFails()); context.setFailCtxIfServletStartFails(Boolean.FALSE); Assert.assertFalse("flag on Context should override Host config", context.getComputedFailCtxIfServletStartFails()); // second, we test the actual effect of the flag on the startup Wrapper servlet = Tomcat.addServlet(context, "myservlet", new FailingStartupServlet()); servlet.setLoadOnStartup(1); tomcat.start(); Assert.assertTrue("flag false should not fail deployment", context.getState() .isAvailable()); tomcat.stop(); Assert.assertFalse(context.getState().isAvailable()); host.removeChild(context); context = (StandardContext) tomcat.addContext("", docBase.getAbsolutePath()); servlet = Tomcat.addServlet(context, "myservlet", new FailingStartupServlet()); servlet.setLoadOnStartup(1); tomcat.start(); Assert.assertFalse("flag true should fail deployment", context.getState() .isAvailable()); } private class FailingStartupServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void init() throws ServletException { throw new ServletException("failing on purpose"); } } @Test public void testBug56085() throws Exception { Tomcat tomcat = getTomcatInstanceTestWebapp(false, true); String realPath = ((Context) tomcat.getHost().findChildren()[0]).getRealPath("\\"); Assert.assertNull(realPath); } /* * Check real path for directories ends with File.separator for consistency * with previous major versions. */ @Test public void testBug57556a() throws Exception { Tomcat tomcat = getTomcatInstanceTestWebapp(false, true); Context testContext = ((Context) tomcat.getHost().findChildren()[0]); File f = new File(testContext.getDocBase()); if (!f.isAbsolute()) { f = new File(((Host) testContext.getParent()).getAppBaseFile(), f.getPath()); } String base = f.getCanonicalPath(); doTestBug57556(testContext, "", base + File.separatorChar); doTestBug57556(testContext, "/", base + File.separatorChar); doTestBug57556(testContext, "/jsp", base + File.separatorChar+ "jsp"); doTestBug57556(testContext, "/jsp/", base + File.separatorChar+ "jsp" + File.separatorChar); doTestBug57556(testContext, "/index.html", base + File.separatorChar + "index.html"); doTestBug57556(testContext, "/foo", base + File.separatorChar + "foo"); doTestBug57556(testContext, "/foo/", base + File.separatorChar + "foo" + File.separatorChar); } @Test public void testBug57556b() throws Exception { Tomcat tomcat = getTomcatInstance(); File docBase = new File("/"); Context testContext = tomcat.addContext("", docBase.getAbsolutePath()); tomcat.start(); File f = new File(testContext.getDocBase()); if (!f.isAbsolute()) { f = new File(((Host) testContext.getParent()).getAppBaseFile(), f.getPath()); } String base = f.getCanonicalPath(); doTestBug57556(testContext, "", base); doTestBug57556(testContext, "/", base); } private void doTestBug57556(Context testContext, String path, String expected) throws Exception { String realPath = testContext.getRealPath(path); Assert.assertNotNull(realPath); Assert.assertEquals(expected, realPath); } @Test public void testBug56903() { Context context = new StandardContext(); context.setResourceOnlyServlets("a,b,c"); Assert.assertThat(Arrays.asList(context.getResourceOnlyServlets().split(",")), CoreMatchers.hasItems("a", "b", "c")); } @Test public void testSetPath() { testSetPath("", ""); testSetPath("/foo", "/foo"); testSetPath("/foo/bar", "/foo/bar"); testSetPath(null, ""); testSetPath("/", ""); testSetPath("foo", "/foo"); testSetPath("/foo/bar/", "/foo/bar"); testSetPath("foo/bar/", "/foo/bar"); } private void testSetPath(String value, String expectedValue) { StandardContext context = new StandardContext(); context.setPath(value); Assert.assertEquals(expectedValue, context.getPath()); } @Test public void testUncoveredMethods() throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("/test", null); ctx.setDenyUncoveredHttpMethods(true); ServletContainerInitializer sci = new SCI(); ctx.addServletContainerInitializer(sci, null); tomcat.start(); ByteChunk bc = new ByteChunk(); int rc; rc = getUrl("http://localhost:" + getPort() + "/test/foo", bc, false); Assert.assertEquals(403, rc); } public static class SCI implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { ServletRegistration.Dynamic sr = ctx.addServlet("Foo", Foo.class.getName()); sr.addMapping("/foo"); } } @ServletSecurity(value=@HttpConstraint(ServletSecurity.EmptyRoleSemantic.DENY), httpMethodConstraints=@HttpMethodConstraint("POST")) public static class Foo extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("OK"); } } }
googleads/google-ads-java
37,803
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/AdGroupAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/resources/ad_group_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.resources; /** * <pre> * AdGroupAssetSet is the linkage between an ad group and an asset set. * Creating an AdGroupAssetSet links an asset set with an ad group. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.AdGroupAssetSet} */ public final class AdGroupAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.resources.AdGroupAssetSet) AdGroupAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use AdGroupAssetSet.newBuilder() to construct. private AdGroupAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AdGroupAssetSet() { resourceName_ = ""; adGroup_ = ""; assetSet_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new AdGroupAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v19_resources_AdGroupAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v19_resources_AdGroupAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.AdGroupAssetSet.class, com.google.ads.googleads.v19.resources.AdGroupAssetSet.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; 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(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AD_GROUP_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object adGroup_ = ""; /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ @java.lang.Override public java.lang.String getAdGroup() { java.lang.Object ref = adGroup_; 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(); adGroup_ = s; return s; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ @java.lang.Override public com.google.protobuf.ByteString getAdGroupBytes() { java.lang.Object ref = adGroup_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); adGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; 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(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.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(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(adGroup_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, adGroup_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, assetSet_); } if (status_ != com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } 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(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(adGroup_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, adGroup_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, assetSet_); } if (status_ != com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } 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.resources.AdGroupAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v19.resources.AdGroupAssetSet other = (com.google.ads.googleads.v19.resources.AdGroupAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getAdGroup() .equals(other.getAdGroup())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (status_ != other.status_) 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_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + AD_GROUP_FIELD_NUMBER; hash = (53 * hash) + getAdGroup().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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> * AdGroupAssetSet is the linkage between an ad group and an asset set. * Creating an AdGroupAssetSet links an asset set with an ad group. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.AdGroupAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.resources.AdGroupAssetSet) com.google.ads.googleads.v19.resources.AdGroupAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v19_resources_AdGroupAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v19_resources_AdGroupAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.AdGroupAssetSet.class, com.google.ads.googleads.v19.resources.AdGroupAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v19.resources.AdGroupAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; adGroup_ = ""; assetSet_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v19_resources_AdGroupAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.resources.AdGroupAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v19.resources.AdGroupAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.resources.AdGroupAssetSet build() { com.google.ads.googleads.v19.resources.AdGroupAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.resources.AdGroupAssetSet buildPartial() { com.google.ads.googleads.v19.resources.AdGroupAssetSet result = new com.google.ads.googleads.v19.resources.AdGroupAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.resources.AdGroupAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.adGroup_ = adGroup_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @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.resources.AdGroupAssetSet) { return mergeFrom((com.google.ads.googleads.v19.resources.AdGroupAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.resources.AdGroupAssetSet other) { if (other == com.google.ads.googleads.v19.resources.AdGroupAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAdGroup().isEmpty()) { adGroup_ = other.adGroup_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } 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: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { adGroup_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = 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 resourceName_ = ""; /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object adGroup_ = ""; /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ public java.lang.String getAdGroup() { java.lang.Object ref = adGroup_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); adGroup_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ public com.google.protobuf.ByteString getAdGroupBytes() { java.lang.Object ref = adGroup_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); adGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The adGroup to set. * @return This builder for chaining. */ public Builder setAdGroup( java.lang.String value) { if (value == null) { throw new NullPointerException(); } adGroup_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAdGroup() { adGroup_ = getDefaultInstance().getAdGroup(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for adGroup to set. * @return This builder for chaining. */ public Builder setAdGroupBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); adGroup_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 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.ads.googleads.v19.resources.AdGroupAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.resources.AdGroupAssetSet) private static final com.google.ads.googleads.v19.resources.AdGroupAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.resources.AdGroupAssetSet(); } public static com.google.ads.googleads.v19.resources.AdGroupAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AdGroupAssetSet> PARSER = new com.google.protobuf.AbstractParser<AdGroupAssetSet>() { @java.lang.Override public AdGroupAssetSet 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<AdGroupAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AdGroupAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.resources.AdGroupAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,803
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/AdGroupAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/resources/ad_group_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.resources; /** * <pre> * AdGroupAssetSet is the linkage between an ad group and an asset set. * Creating an AdGroupAssetSet links an asset set with an ad group. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.AdGroupAssetSet} */ public final class AdGroupAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.resources.AdGroupAssetSet) AdGroupAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use AdGroupAssetSet.newBuilder() to construct. private AdGroupAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AdGroupAssetSet() { resourceName_ = ""; adGroup_ = ""; assetSet_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new AdGroupAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v20_resources_AdGroupAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v20_resources_AdGroupAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.AdGroupAssetSet.class, com.google.ads.googleads.v20.resources.AdGroupAssetSet.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; 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(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AD_GROUP_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object adGroup_ = ""; /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ @java.lang.Override public java.lang.String getAdGroup() { java.lang.Object ref = adGroup_; 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(); adGroup_ = s; return s; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ @java.lang.Override public com.google.protobuf.ByteString getAdGroupBytes() { java.lang.Object ref = adGroup_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); adGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; 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(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.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(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(adGroup_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, adGroup_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, assetSet_); } if (status_ != com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } 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(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(adGroup_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, adGroup_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, assetSet_); } if (status_ != com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } 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.resources.AdGroupAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v20.resources.AdGroupAssetSet other = (com.google.ads.googleads.v20.resources.AdGroupAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getAdGroup() .equals(other.getAdGroup())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (status_ != other.status_) 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_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + AD_GROUP_FIELD_NUMBER; hash = (53 * hash) + getAdGroup().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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> * AdGroupAssetSet is the linkage between an ad group and an asset set. * Creating an AdGroupAssetSet links an asset set with an ad group. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.AdGroupAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.resources.AdGroupAssetSet) com.google.ads.googleads.v20.resources.AdGroupAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v20_resources_AdGroupAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v20_resources_AdGroupAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.AdGroupAssetSet.class, com.google.ads.googleads.v20.resources.AdGroupAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v20.resources.AdGroupAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; adGroup_ = ""; assetSet_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v20_resources_AdGroupAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.resources.AdGroupAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v20.resources.AdGroupAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.resources.AdGroupAssetSet build() { com.google.ads.googleads.v20.resources.AdGroupAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.resources.AdGroupAssetSet buildPartial() { com.google.ads.googleads.v20.resources.AdGroupAssetSet result = new com.google.ads.googleads.v20.resources.AdGroupAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.resources.AdGroupAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.adGroup_ = adGroup_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @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.resources.AdGroupAssetSet) { return mergeFrom((com.google.ads.googleads.v20.resources.AdGroupAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.resources.AdGroupAssetSet other) { if (other == com.google.ads.googleads.v20.resources.AdGroupAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAdGroup().isEmpty()) { adGroup_ = other.adGroup_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } 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: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { adGroup_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = 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 resourceName_ = ""; /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object adGroup_ = ""; /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ public java.lang.String getAdGroup() { java.lang.Object ref = adGroup_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); adGroup_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ public com.google.protobuf.ByteString getAdGroupBytes() { java.lang.Object ref = adGroup_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); adGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The adGroup to set. * @return This builder for chaining. */ public Builder setAdGroup( java.lang.String value) { if (value == null) { throw new NullPointerException(); } adGroup_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAdGroup() { adGroup_ = getDefaultInstance().getAdGroup(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for adGroup to set. * @return This builder for chaining. */ public Builder setAdGroupBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); adGroup_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 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.ads.googleads.v20.resources.AdGroupAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.resources.AdGroupAssetSet) private static final com.google.ads.googleads.v20.resources.AdGroupAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.resources.AdGroupAssetSet(); } public static com.google.ads.googleads.v20.resources.AdGroupAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AdGroupAssetSet> PARSER = new com.google.protobuf.AbstractParser<AdGroupAssetSet>() { @java.lang.Override public AdGroupAssetSet 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<AdGroupAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AdGroupAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.resources.AdGroupAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,803
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/AdGroupAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/resources/ad_group_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.resources; /** * <pre> * AdGroupAssetSet is the linkage between an ad group and an asset set. * Creating an AdGroupAssetSet links an asset set with an ad group. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.AdGroupAssetSet} */ public final class AdGroupAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.AdGroupAssetSet) AdGroupAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use AdGroupAssetSet.newBuilder() to construct. private AdGroupAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AdGroupAssetSet() { resourceName_ = ""; adGroup_ = ""; assetSet_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new AdGroupAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v21_resources_AdGroupAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v21_resources_AdGroupAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.AdGroupAssetSet.class, com.google.ads.googleads.v21.resources.AdGroupAssetSet.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; 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(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AD_GROUP_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object adGroup_ = ""; /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ @java.lang.Override public java.lang.String getAdGroup() { java.lang.Object ref = adGroup_; 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(); adGroup_ = s; return s; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ @java.lang.Override public com.google.protobuf.ByteString getAdGroupBytes() { java.lang.Object ref = adGroup_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); adGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; 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(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.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(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(adGroup_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, adGroup_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, assetSet_); } if (status_ != com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } 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(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(adGroup_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, adGroup_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, assetSet_); } if (status_ != com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } 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.resources.AdGroupAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v21.resources.AdGroupAssetSet other = (com.google.ads.googleads.v21.resources.AdGroupAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getAdGroup() .equals(other.getAdGroup())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (status_ != other.status_) 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_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + AD_GROUP_FIELD_NUMBER; hash = (53 * hash) + getAdGroup().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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.resources.AdGroupAssetSet 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> * AdGroupAssetSet is the linkage between an ad group and an asset set. * Creating an AdGroupAssetSet links an asset set with an ad group. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.AdGroupAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.AdGroupAssetSet) com.google.ads.googleads.v21.resources.AdGroupAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v21_resources_AdGroupAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v21_resources_AdGroupAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.AdGroupAssetSet.class, com.google.ads.googleads.v21.resources.AdGroupAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v21.resources.AdGroupAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; adGroup_ = ""; assetSet_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.resources.AdGroupAssetSetProto.internal_static_google_ads_googleads_v21_resources_AdGroupAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.resources.AdGroupAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v21.resources.AdGroupAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.resources.AdGroupAssetSet build() { com.google.ads.googleads.v21.resources.AdGroupAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.resources.AdGroupAssetSet buildPartial() { com.google.ads.googleads.v21.resources.AdGroupAssetSet result = new com.google.ads.googleads.v21.resources.AdGroupAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.resources.AdGroupAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.adGroup_ = adGroup_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @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.resources.AdGroupAssetSet) { return mergeFrom((com.google.ads.googleads.v21.resources.AdGroupAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.resources.AdGroupAssetSet other) { if (other == com.google.ads.googleads.v21.resources.AdGroupAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAdGroup().isEmpty()) { adGroup_ = other.adGroup_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } 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: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { adGroup_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = 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 resourceName_ = ""; /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the ad group asset set. * Ad group asset set resource names have the form: * * `customers/{customer_id}/adGroupAssetSets/{ad_group_id}~{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object adGroup_ = ""; /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The adGroup. */ public java.lang.String getAdGroup() { java.lang.Object ref = adGroup_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); adGroup_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for adGroup. */ public com.google.protobuf.ByteString getAdGroupBytes() { java.lang.Object ref = adGroup_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); adGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The adGroup to set. * @return This builder for chaining. */ public Builder setAdGroup( java.lang.String value) { if (value == null) { throw new NullPointerException(); } adGroup_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAdGroup() { adGroup_ = getDefaultInstance().getAdGroup(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The ad group to which this asset set is linked. * </pre> * * <code>string ad_group = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for adGroup to set. * @return This builder for chaining. */ public Builder setAdGroupBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); adGroup_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the ad group. * </pre> * * <code>string asset_set = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the ad group asset set. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 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.ads.googleads.v21.resources.AdGroupAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.AdGroupAssetSet) private static final com.google.ads.googleads.v21.resources.AdGroupAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.AdGroupAssetSet(); } public static com.google.ads.googleads.v21.resources.AdGroupAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AdGroupAssetSet> PARSER = new com.google.protobuf.AbstractParser<AdGroupAssetSet>() { @java.lang.Override public AdGroupAssetSet 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<AdGroupAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AdGroupAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.resources.AdGroupAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,622
java-meet/proto-google-cloud-meet-v2beta/src/main/java/com/google/apps/meet/v2beta/ListParticipantSessionsRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/meet/v2beta/service.proto // Protobuf Java Version: 3.25.8 package com.google.apps.meet.v2beta; /** * * * <pre> * Request to fetch list of participant sessions per conference record, per * participant. * </pre> * * Protobuf type {@code google.apps.meet.v2beta.ListParticipantSessionsRequest} */ public final class ListParticipantSessionsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.meet.v2beta.ListParticipantSessionsRequest) ListParticipantSessionsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListParticipantSessionsRequest.newBuilder() to construct. private ListParticipantSessionsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListParticipantSessionsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListParticipantSessionsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2beta.ServiceProto .internal_static_google_apps_meet_v2beta_ListParticipantSessionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2beta.ServiceProto .internal_static_google_apps_meet_v2beta_ListParticipantSessionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2beta.ListParticipantSessionsRequest.class, com.google.apps.meet.v2beta.ListParticipantSessionsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Format: * `conferenceRecords/{conference_record}/participants/{participant}` * </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: * `conferenceRecords/{conference_record}/participants/{participant}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. Maximum number of participant sessions to return. The service * might return fewer than this value. If unspecified, at most 100 * participants are returned. The maximum value is 250; values above 250 are * coerced to 250. Maximum might change in the future. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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.apps.meet.v2beta.ListParticipantSessionsRequest)) { return super.equals(obj); } com.google.apps.meet.v2beta.ListParticipantSessionsRequest other = (com.google.apps.meet.v2beta.ListParticipantSessionsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.apps.meet.v2beta.ListParticipantSessionsRequest 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 fetch list of participant sessions per conference record, per * participant. * </pre> * * Protobuf type {@code google.apps.meet.v2beta.ListParticipantSessionsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.meet.v2beta.ListParticipantSessionsRequest) com.google.apps.meet.v2beta.ListParticipantSessionsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2beta.ServiceProto .internal_static_google_apps_meet_v2beta_ListParticipantSessionsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2beta.ServiceProto .internal_static_google_apps_meet_v2beta_ListParticipantSessionsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2beta.ListParticipantSessionsRequest.class, com.google.apps.meet.v2beta.ListParticipantSessionsRequest.Builder.class); } // Construct using com.google.apps.meet.v2beta.ListParticipantSessionsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.meet.v2beta.ServiceProto .internal_static_google_apps_meet_v2beta_ListParticipantSessionsRequest_descriptor; } @java.lang.Override public com.google.apps.meet.v2beta.ListParticipantSessionsRequest getDefaultInstanceForType() { return com.google.apps.meet.v2beta.ListParticipantSessionsRequest.getDefaultInstance(); } @java.lang.Override public com.google.apps.meet.v2beta.ListParticipantSessionsRequest build() { com.google.apps.meet.v2beta.ListParticipantSessionsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.meet.v2beta.ListParticipantSessionsRequest buildPartial() { com.google.apps.meet.v2beta.ListParticipantSessionsRequest result = new com.google.apps.meet.v2beta.ListParticipantSessionsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.apps.meet.v2beta.ListParticipantSessionsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.apps.meet.v2beta.ListParticipantSessionsRequest) { return mergeFrom((com.google.apps.meet.v2beta.ListParticipantSessionsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.meet.v2beta.ListParticipantSessionsRequest other) { if (other == com.google.apps.meet.v2beta.ListParticipantSessionsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 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: * `conferenceRecords/{conference_record}/participants/{participant}` * </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: * `conferenceRecords/{conference_record}/participants/{participant}` * </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: * `conferenceRecords/{conference_record}/participants/{participant}` * </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: * `conferenceRecords/{conference_record}/participants/{participant}` * </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: * `conferenceRecords/{conference_record}/participants/{participant}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Maximum number of participant sessions to return. The service * might return fewer than this value. If unspecified, at most 100 * participants are returned. The maximum value is 250; values above 250 are * coerced to 250. Maximum might change in the future. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Maximum number of participant sessions to return. The service * might return fewer than this value. If unspecified, at most 100 * participants are returned. The maximum value is 250; values above 250 are * coerced to 250. Maximum might change in the future. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Maximum number of participant sessions to return. The service * might return fewer than this value. If unspecified, at most 100 * participants are returned. The maximum value is 250; values above 250 are * coerced to 250. Maximum might change in the future. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. Page token returned from previous List Call. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. User specified filtering condition in [EBNF * format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form). * The following are the filterable fields: * * * `start_time` * * `end_time` * * For example, `end_time IS NULL` returns active participant sessions in * the conference record. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 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.apps.meet.v2beta.ListParticipantSessionsRequest) } // @@protoc_insertion_point(class_scope:google.apps.meet.v2beta.ListParticipantSessionsRequest) private static final com.google.apps.meet.v2beta.ListParticipantSessionsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.meet.v2beta.ListParticipantSessionsRequest(); } public static com.google.apps.meet.v2beta.ListParticipantSessionsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListParticipantSessionsRequest> PARSER = new com.google.protobuf.AbstractParser<ListParticipantSessionsRequest>() { @java.lang.Override public ListParticipantSessionsRequest 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<ListParticipantSessionsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListParticipantSessionsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.meet.v2beta.ListParticipantSessionsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,626
java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/ListAnnotatedDatasetsRequest.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/datalabeling/v1beta1/data_labeling_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datalabeling.v1beta1; /** * * * <pre> * Request message for ListAnnotatedDatasets. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest} */ public final class ListAnnotatedDatasetsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) ListAnnotatedDatasetsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListAnnotatedDatasetsRequest.newBuilder() to construct. private ListAnnotatedDatasetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListAnnotatedDatasetsRequest() { parent_ = ""; filter_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListAnnotatedDatasetsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListAnnotatedDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListAnnotatedDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest.class, com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </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. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 3; private int pageSize_ = 0; /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_); } if (pageSize_ != 0) { output.writeInt32(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest other = (com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) 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.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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.datalabeling.v1beta1.ListAnnotatedDatasetsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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 ListAnnotatedDatasets. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListAnnotatedDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListAnnotatedDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest.class, com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest.Builder.class); } // Construct using // com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest.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.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListAnnotatedDatasetsRequest_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest build() { com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest buildPartial() { com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest result = new com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest 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.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) { return mergeFrom( (com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest other) { if (other == com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000002; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { pageToken_ = 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 java.lang.Object parent_ = ""; /** * * * <pre> * Required. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </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. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </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. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </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. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </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. Name of the dataset to list annotated datasets, format: * projects/{project_id}/datasets/{dataset_id} * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. Filter is not supported at this moment. * </pre> * * <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Requested page size. Server may return fewer results than * requested. Default value is 100. * </pre> * * <code>int32 page_size = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000004); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. A token identifying a page of results for the server to return. * Typically obtained by * [ListAnnotatedDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListAnnotatedDatasets] call. * Return first page if empty. * </pre> * * <code>string page_token = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest) private static final com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest(); } public static com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListAnnotatedDatasetsRequest> PARSER = new com.google.protobuf.AbstractParser<ListAnnotatedDatasetsRequest>() { @java.lang.Override public ListAnnotatedDatasetsRequest 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<ListAnnotatedDatasetsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListAnnotatedDatasetsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListAnnotatedDatasetsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,671
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/SearchIndexEndpointResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/visionai/v1/warehouse.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.visionai.v1; /** * * * <pre> * Response message for SearchIndexEndpoint. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.SearchIndexEndpointResponse} */ public final class SearchIndexEndpointResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.SearchIndexEndpointResponse) SearchIndexEndpointResponseOrBuilder { private static final long serialVersionUID = 0L; // Use SearchIndexEndpointResponse.newBuilder() to construct. private SearchIndexEndpointResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SearchIndexEndpointResponse() { searchResultItems_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SearchIndexEndpointResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_SearchIndexEndpointResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_SearchIndexEndpointResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.SearchIndexEndpointResponse.class, com.google.cloud.visionai.v1.SearchIndexEndpointResponse.Builder.class); } public static final int SEARCH_RESULT_ITEMS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.visionai.v1.SearchResultItem> searchResultItems_; /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.visionai.v1.SearchResultItem> getSearchResultItemsList() { return searchResultItems_; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.visionai.v1.SearchResultItemOrBuilder> getSearchResultItemsOrBuilderList() { return searchResultItems_; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ @java.lang.Override public int getSearchResultItemsCount() { return searchResultItems_.size(); } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.SearchResultItem getSearchResultItems(int index) { return searchResultItems_.get(index); } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.SearchResultItemOrBuilder getSearchResultItemsOrBuilder( int index) { return searchResultItems_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The next-page continuation token. * 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> * The next-page continuation token. * 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 < searchResultItems_.size(); i++) { output.writeMessage(1, searchResultItems_.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 < searchResultItems_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, searchResultItems_.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.visionai.v1.SearchIndexEndpointResponse)) { return super.equals(obj); } com.google.cloud.visionai.v1.SearchIndexEndpointResponse other = (com.google.cloud.visionai.v1.SearchIndexEndpointResponse) obj; if (!getSearchResultItemsList().equals(other.getSearchResultItemsList())) 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 (getSearchResultItemsCount() > 0) { hash = (37 * hash) + SEARCH_RESULT_ITEMS_FIELD_NUMBER; hash = (53 * hash) + getSearchResultItemsList().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.visionai.v1.SearchIndexEndpointResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse 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.SearchIndexEndpointResponse 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 SearchIndexEndpoint. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.SearchIndexEndpointResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.SearchIndexEndpointResponse) com.google.cloud.visionai.v1.SearchIndexEndpointResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_SearchIndexEndpointResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_SearchIndexEndpointResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.SearchIndexEndpointResponse.class, com.google.cloud.visionai.v1.SearchIndexEndpointResponse.Builder.class); } // Construct using com.google.cloud.visionai.v1.SearchIndexEndpointResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (searchResultItemsBuilder_ == null) { searchResultItems_ = java.util.Collections.emptyList(); } else { searchResultItems_ = null; searchResultItemsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_SearchIndexEndpointResponse_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.SearchIndexEndpointResponse getDefaultInstanceForType() { return com.google.cloud.visionai.v1.SearchIndexEndpointResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.SearchIndexEndpointResponse build() { com.google.cloud.visionai.v1.SearchIndexEndpointResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.SearchIndexEndpointResponse buildPartial() { com.google.cloud.visionai.v1.SearchIndexEndpointResponse result = new com.google.cloud.visionai.v1.SearchIndexEndpointResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.visionai.v1.SearchIndexEndpointResponse result) { if (searchResultItemsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { searchResultItems_ = java.util.Collections.unmodifiableList(searchResultItems_); bitField0_ = (bitField0_ & ~0x00000001); } result.searchResultItems_ = searchResultItems_; } else { result.searchResultItems_ = searchResultItemsBuilder_.build(); } } private void buildPartial0(com.google.cloud.visionai.v1.SearchIndexEndpointResponse 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.visionai.v1.SearchIndexEndpointResponse) { return mergeFrom((com.google.cloud.visionai.v1.SearchIndexEndpointResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.SearchIndexEndpointResponse other) { if (other == com.google.cloud.visionai.v1.SearchIndexEndpointResponse.getDefaultInstance()) return this; if (searchResultItemsBuilder_ == null) { if (!other.searchResultItems_.isEmpty()) { if (searchResultItems_.isEmpty()) { searchResultItems_ = other.searchResultItems_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSearchResultItemsIsMutable(); searchResultItems_.addAll(other.searchResultItems_); } onChanged(); } } else { if (!other.searchResultItems_.isEmpty()) { if (searchResultItemsBuilder_.isEmpty()) { searchResultItemsBuilder_.dispose(); searchResultItemsBuilder_ = null; searchResultItems_ = other.searchResultItems_; bitField0_ = (bitField0_ & ~0x00000001); searchResultItemsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSearchResultItemsFieldBuilder() : null; } else { searchResultItemsBuilder_.addAllMessages(other.searchResultItems_); } } } 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.visionai.v1.SearchResultItem m = input.readMessage( com.google.cloud.visionai.v1.SearchResultItem.parser(), extensionRegistry); if (searchResultItemsBuilder_ == null) { ensureSearchResultItemsIsMutable(); searchResultItems_.add(m); } else { searchResultItemsBuilder_.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.visionai.v1.SearchResultItem> searchResultItems_ = java.util.Collections.emptyList(); private void ensureSearchResultItemsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { searchResultItems_ = new java.util.ArrayList<com.google.cloud.visionai.v1.SearchResultItem>( searchResultItems_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.visionai.v1.SearchResultItem, com.google.cloud.visionai.v1.SearchResultItem.Builder, com.google.cloud.visionai.v1.SearchResultItemOrBuilder> searchResultItemsBuilder_; /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public java.util.List<com.google.cloud.visionai.v1.SearchResultItem> getSearchResultItemsList() { if (searchResultItemsBuilder_ == null) { return java.util.Collections.unmodifiableList(searchResultItems_); } else { return searchResultItemsBuilder_.getMessageList(); } } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public int getSearchResultItemsCount() { if (searchResultItemsBuilder_ == null) { return searchResultItems_.size(); } else { return searchResultItemsBuilder_.getCount(); } } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public com.google.cloud.visionai.v1.SearchResultItem getSearchResultItems(int index) { if (searchResultItemsBuilder_ == null) { return searchResultItems_.get(index); } else { return searchResultItemsBuilder_.getMessage(index); } } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder setSearchResultItems( int index, com.google.cloud.visionai.v1.SearchResultItem value) { if (searchResultItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSearchResultItemsIsMutable(); searchResultItems_.set(index, value); onChanged(); } else { searchResultItemsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder setSearchResultItems( int index, com.google.cloud.visionai.v1.SearchResultItem.Builder builderForValue) { if (searchResultItemsBuilder_ == null) { ensureSearchResultItemsIsMutable(); searchResultItems_.set(index, builderForValue.build()); onChanged(); } else { searchResultItemsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder addSearchResultItems(com.google.cloud.visionai.v1.SearchResultItem value) { if (searchResultItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSearchResultItemsIsMutable(); searchResultItems_.add(value); onChanged(); } else { searchResultItemsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder addSearchResultItems( int index, com.google.cloud.visionai.v1.SearchResultItem value) { if (searchResultItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSearchResultItemsIsMutable(); searchResultItems_.add(index, value); onChanged(); } else { searchResultItemsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder addSearchResultItems( com.google.cloud.visionai.v1.SearchResultItem.Builder builderForValue) { if (searchResultItemsBuilder_ == null) { ensureSearchResultItemsIsMutable(); searchResultItems_.add(builderForValue.build()); onChanged(); } else { searchResultItemsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder addSearchResultItems( int index, com.google.cloud.visionai.v1.SearchResultItem.Builder builderForValue) { if (searchResultItemsBuilder_ == null) { ensureSearchResultItemsIsMutable(); searchResultItems_.add(index, builderForValue.build()); onChanged(); } else { searchResultItemsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder addAllSearchResultItems( java.lang.Iterable<? extends com.google.cloud.visionai.v1.SearchResultItem> values) { if (searchResultItemsBuilder_ == null) { ensureSearchResultItemsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, searchResultItems_); onChanged(); } else { searchResultItemsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder clearSearchResultItems() { if (searchResultItemsBuilder_ == null) { searchResultItems_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { searchResultItemsBuilder_.clear(); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public Builder removeSearchResultItems(int index) { if (searchResultItemsBuilder_ == null) { ensureSearchResultItemsIsMutable(); searchResultItems_.remove(index); onChanged(); } else { searchResultItemsBuilder_.remove(index); } return this; } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public com.google.cloud.visionai.v1.SearchResultItem.Builder getSearchResultItemsBuilder( int index) { return getSearchResultItemsFieldBuilder().getBuilder(index); } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public com.google.cloud.visionai.v1.SearchResultItemOrBuilder getSearchResultItemsOrBuilder( int index) { if (searchResultItemsBuilder_ == null) { return searchResultItems_.get(index); } else { return searchResultItemsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public java.util.List<? extends com.google.cloud.visionai.v1.SearchResultItemOrBuilder> getSearchResultItemsOrBuilderList() { if (searchResultItemsBuilder_ != null) { return searchResultItemsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(searchResultItems_); } } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public com.google.cloud.visionai.v1.SearchResultItem.Builder addSearchResultItemsBuilder() { return getSearchResultItemsFieldBuilder() .addBuilder(com.google.cloud.visionai.v1.SearchResultItem.getDefaultInstance()); } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public com.google.cloud.visionai.v1.SearchResultItem.Builder addSearchResultItemsBuilder( int index) { return getSearchResultItemsFieldBuilder() .addBuilder(index, com.google.cloud.visionai.v1.SearchResultItem.getDefaultInstance()); } /** * * * <pre> * Returned search results. * </pre> * * <code>repeated .google.cloud.visionai.v1.SearchResultItem search_result_items = 1;</code> */ public java.util.List<com.google.cloud.visionai.v1.SearchResultItem.Builder> getSearchResultItemsBuilderList() { return getSearchResultItemsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.visionai.v1.SearchResultItem, com.google.cloud.visionai.v1.SearchResultItem.Builder, com.google.cloud.visionai.v1.SearchResultItemOrBuilder> getSearchResultItemsFieldBuilder() { if (searchResultItemsBuilder_ == null) { searchResultItemsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.visionai.v1.SearchResultItem, com.google.cloud.visionai.v1.SearchResultItem.Builder, com.google.cloud.visionai.v1.SearchResultItemOrBuilder>( searchResultItems_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); searchResultItems_ = null; } return searchResultItemsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * The next-page continuation token. * 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> * The next-page continuation token. * 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> * The next-page continuation token. * 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> * The next-page continuation token. * 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> * The next-page continuation token. * 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.visionai.v1.SearchIndexEndpointResponse) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.SearchIndexEndpointResponse) private static final com.google.cloud.visionai.v1.SearchIndexEndpointResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.SearchIndexEndpointResponse(); } public static com.google.cloud.visionai.v1.SearchIndexEndpointResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SearchIndexEndpointResponse> PARSER = new com.google.protobuf.AbstractParser<SearchIndexEndpointResponse>() { @java.lang.Override public SearchIndexEndpointResponse 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<SearchIndexEndpointResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SearchIndexEndpointResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.SearchIndexEndpointResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,682
java-analytics-admin/proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/UpdateConversionEventRequest.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 UpdateConversionEvent RPC * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.UpdateConversionEventRequest} */ public final class UpdateConversionEventRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.UpdateConversionEventRequest) UpdateConversionEventRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateConversionEventRequest.newBuilder() to construct. private UpdateConversionEventRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateConversionEventRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateConversionEventRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdateConversionEventRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdateConversionEventRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.UpdateConversionEventRequest.class, com.google.analytics.admin.v1beta.UpdateConversionEventRequest.Builder.class); } private int bitField0_; public static final int CONVERSION_EVENT_FIELD_NUMBER = 1; private com.google.analytics.admin.v1beta.ConversionEvent conversionEvent_; /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the conversionEvent field is set. */ @java.lang.Override public boolean hasConversionEvent() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The conversionEvent. */ @java.lang.Override public com.google.analytics.admin.v1beta.ConversionEvent getConversionEvent() { return conversionEvent_ == null ? com.google.analytics.admin.v1beta.ConversionEvent.getDefaultInstance() : conversionEvent_; } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.analytics.admin.v1beta.ConversionEventOrBuilder getConversionEventOrBuilder() { return conversionEvent_ == null ? com.google.analytics.admin.v1beta.ConversionEvent.getDefaultInstance() : conversionEvent_; } 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, getConversionEvent()); } 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, getConversionEvent()); } 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.UpdateConversionEventRequest)) { return super.equals(obj); } com.google.analytics.admin.v1beta.UpdateConversionEventRequest other = (com.google.analytics.admin.v1beta.UpdateConversionEventRequest) obj; if (hasConversionEvent() != other.hasConversionEvent()) return false; if (hasConversionEvent()) { if (!getConversionEvent().equals(other.getConversionEvent())) 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 (hasConversionEvent()) { hash = (37 * hash) + CONVERSION_EVENT_FIELD_NUMBER; hash = (53 * hash) + getConversionEvent().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.UpdateConversionEventRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.UpdateConversionEventRequest 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.UpdateConversionEventRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.UpdateConversionEventRequest 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.UpdateConversionEventRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.UpdateConversionEventRequest 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.UpdateConversionEventRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.UpdateConversionEventRequest 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.UpdateConversionEventRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.UpdateConversionEventRequest 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.UpdateConversionEventRequest 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.UpdateConversionEventRequest 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.UpdateConversionEventRequest 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 UpdateConversionEvent RPC * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.UpdateConversionEventRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.UpdateConversionEventRequest) com.google.analytics.admin.v1beta.UpdateConversionEventRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdateConversionEventRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_UpdateConversionEventRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.UpdateConversionEventRequest.class, com.google.analytics.admin.v1beta.UpdateConversionEventRequest.Builder.class); } // Construct using com.google.analytics.admin.v1beta.UpdateConversionEventRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getConversionEventFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; conversionEvent_ = null; if (conversionEventBuilder_ != null) { conversionEventBuilder_.dispose(); conversionEventBuilder_ = 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_UpdateConversionEventRequest_descriptor; } @java.lang.Override public com.google.analytics.admin.v1beta.UpdateConversionEventRequest getDefaultInstanceForType() { return com.google.analytics.admin.v1beta.UpdateConversionEventRequest.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1beta.UpdateConversionEventRequest build() { com.google.analytics.admin.v1beta.UpdateConversionEventRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1beta.UpdateConversionEventRequest buildPartial() { com.google.analytics.admin.v1beta.UpdateConversionEventRequest result = new com.google.analytics.admin.v1beta.UpdateConversionEventRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.analytics.admin.v1beta.UpdateConversionEventRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.conversionEvent_ = conversionEventBuilder_ == null ? conversionEvent_ : conversionEventBuilder_.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.UpdateConversionEventRequest) { return mergeFrom((com.google.analytics.admin.v1beta.UpdateConversionEventRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1beta.UpdateConversionEventRequest other) { if (other == com.google.analytics.admin.v1beta.UpdateConversionEventRequest.getDefaultInstance()) return this; if (other.hasConversionEvent()) { mergeConversionEvent(other.getConversionEvent()); } 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(getConversionEventFieldBuilder().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.ConversionEvent conversionEvent_; private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.ConversionEvent, com.google.analytics.admin.v1beta.ConversionEvent.Builder, com.google.analytics.admin.v1beta.ConversionEventOrBuilder> conversionEventBuilder_; /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the conversionEvent field is set. */ public boolean hasConversionEvent() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The conversionEvent. */ public com.google.analytics.admin.v1beta.ConversionEvent getConversionEvent() { if (conversionEventBuilder_ == null) { return conversionEvent_ == null ? com.google.analytics.admin.v1beta.ConversionEvent.getDefaultInstance() : conversionEvent_; } else { return conversionEventBuilder_.getMessage(); } } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConversionEvent(com.google.analytics.admin.v1beta.ConversionEvent value) { if (conversionEventBuilder_ == null) { if (value == null) { throw new NullPointerException(); } conversionEvent_ = value; } else { conversionEventBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConversionEvent( com.google.analytics.admin.v1beta.ConversionEvent.Builder builderForValue) { if (conversionEventBuilder_ == null) { conversionEvent_ = builderForValue.build(); } else { conversionEventBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeConversionEvent(com.google.analytics.admin.v1beta.ConversionEvent value) { if (conversionEventBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && conversionEvent_ != null && conversionEvent_ != com.google.analytics.admin.v1beta.ConversionEvent.getDefaultInstance()) { getConversionEventBuilder().mergeFrom(value); } else { conversionEvent_ = value; } } else { conversionEventBuilder_.mergeFrom(value); } if (conversionEvent_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearConversionEvent() { bitField0_ = (bitField0_ & ~0x00000001); conversionEvent_ = null; if (conversionEventBuilder_ != null) { conversionEventBuilder_.dispose(); conversionEventBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1beta.ConversionEvent.Builder getConversionEventBuilder() { bitField0_ |= 0x00000001; onChanged(); return getConversionEventFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1beta.ConversionEventOrBuilder getConversionEventOrBuilder() { if (conversionEventBuilder_ != null) { return conversionEventBuilder_.getMessageOrBuilder(); } else { return conversionEvent_ == null ? com.google.analytics.admin.v1beta.ConversionEvent.getDefaultInstance() : conversionEvent_; } } /** * * * <pre> * Required. The conversion event to update. * The `name` field is used to identify the settings to be updated. * </pre> * * <code> * .google.analytics.admin.v1beta.ConversionEvent conversion_event = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.ConversionEvent, com.google.analytics.admin.v1beta.ConversionEvent.Builder, com.google.analytics.admin.v1beta.ConversionEventOrBuilder> getConversionEventFieldBuilder() { if (conversionEventBuilder_ == null) { conversionEventBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.ConversionEvent, com.google.analytics.admin.v1beta.ConversionEvent.Builder, com.google.analytics.admin.v1beta.ConversionEventOrBuilder>( getConversionEvent(), getParentForChildren(), isClean()); conversionEvent_ = null; } return conversionEventBuilder_; } 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.UpdateConversionEventRequest) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.UpdateConversionEventRequest) private static final com.google.analytics.admin.v1beta.UpdateConversionEventRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.UpdateConversionEventRequest(); } public static com.google.analytics.admin.v1beta.UpdateConversionEventRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateConversionEventRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateConversionEventRequest>() { @java.lang.Override public UpdateConversionEventRequest 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<UpdateConversionEventRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateConversionEventRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1beta.UpdateConversionEventRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,693
java-discoveryengine/proto-google-cloud-discoveryengine-v1alpha/src/main/java/com/google/cloud/discoveryengine/v1alpha/UpdateControlRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/discoveryengine/v1alpha/control_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1alpha; /** * * * <pre> * Request for UpdateControl method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1alpha.UpdateControlRequest} */ public final class UpdateControlRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1alpha.UpdateControlRequest) UpdateControlRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateControlRequest.newBuilder() to construct. private UpdateControlRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateControlRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateControlRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1alpha.ControlServiceProto .internal_static_google_cloud_discoveryengine_v1alpha_UpdateControlRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1alpha.ControlServiceProto .internal_static_google_cloud_discoveryengine_v1alpha_UpdateControlRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.class, com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.Builder.class); } private int bitField0_; public static final int CONTROL_FIELD_NUMBER = 1; private com.google.cloud.discoveryengine.v1alpha.Control control_; /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the control field is set. */ @java.lang.Override public boolean hasControl() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The control. */ @java.lang.Override public com.google.cloud.discoveryengine.v1alpha.Control getControl() { return control_ == null ? com.google.cloud.discoveryengine.v1alpha.Control.getDefaultInstance() : control_; } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.discoveryengine.v1alpha.ControlOrBuilder getControlOrBuilder() { return control_ == null ? com.google.cloud.discoveryengine.v1alpha.Control.getDefaultInstance() : control_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Optional. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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, getControl()); } 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, getControl()); } 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.discoveryengine.v1alpha.UpdateControlRequest)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest other = (com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest) obj; if (hasControl() != other.hasControl()) return false; if (hasControl()) { if (!getControl().equals(other.getControl())) 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 (hasControl()) { hash = (37 * hash) + CONTROL_FIELD_NUMBER; hash = (53 * hash) + getControl().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.discoveryengine.v1alpha.UpdateControlRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest 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 UpdateControl method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1alpha.UpdateControlRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1alpha.UpdateControlRequest) com.google.cloud.discoveryengine.v1alpha.UpdateControlRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1alpha.ControlServiceProto .internal_static_google_cloud_discoveryengine_v1alpha_UpdateControlRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1alpha.ControlServiceProto .internal_static_google_cloud_discoveryengine_v1alpha_UpdateControlRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.class, com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getControlFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; control_ = null; if (controlBuilder_ != null) { controlBuilder_.dispose(); controlBuilder_ = 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.discoveryengine.v1alpha.ControlServiceProto .internal_static_google_cloud_discoveryengine_v1alpha_UpdateControlRequest_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest build() { com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest buildPartial() { com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest result = new com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.control_ = controlBuilder_ == null ? control_ : controlBuilder_.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.discoveryengine.v1alpha.UpdateControlRequest) { return mergeFrom((com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest other) { if (other == com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest.getDefaultInstance()) return this; if (other.hasControl()) { mergeControl(other.getControl()); } 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(getControlFieldBuilder().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.discoveryengine.v1alpha.Control control_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.discoveryengine.v1alpha.Control, com.google.cloud.discoveryengine.v1alpha.Control.Builder, com.google.cloud.discoveryengine.v1alpha.ControlOrBuilder> controlBuilder_; /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the control field is set. */ public boolean hasControl() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The control. */ public com.google.cloud.discoveryengine.v1alpha.Control getControl() { if (controlBuilder_ == null) { return control_ == null ? com.google.cloud.discoveryengine.v1alpha.Control.getDefaultInstance() : control_; } else { return controlBuilder_.getMessage(); } } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setControl(com.google.cloud.discoveryengine.v1alpha.Control value) { if (controlBuilder_ == null) { if (value == null) { throw new NullPointerException(); } control_ = value; } else { controlBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setControl( com.google.cloud.discoveryengine.v1alpha.Control.Builder builderForValue) { if (controlBuilder_ == null) { control_ = builderForValue.build(); } else { controlBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeControl(com.google.cloud.discoveryengine.v1alpha.Control value) { if (controlBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && control_ != null && control_ != com.google.cloud.discoveryengine.v1alpha.Control.getDefaultInstance()) { getControlBuilder().mergeFrom(value); } else { control_ = value; } } else { controlBuilder_.mergeFrom(value); } if (control_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearControl() { bitField0_ = (bitField0_ & ~0x00000001); control_ = null; if (controlBuilder_ != null) { controlBuilder_.dispose(); controlBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.discoveryengine.v1alpha.Control.Builder getControlBuilder() { bitField0_ |= 0x00000001; onChanged(); return getControlFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.discoveryengine.v1alpha.ControlOrBuilder getControlOrBuilder() { if (controlBuilder_ != null) { return controlBuilder_.getMessageOrBuilder(); } else { return control_ == null ? com.google.cloud.discoveryengine.v1alpha.Control.getDefaultInstance() : control_; } } /** * * * <pre> * Required. The Control to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1alpha.Control control = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.discoveryengine.v1alpha.Control, com.google.cloud.discoveryengine.v1alpha.Control.Builder, com.google.cloud.discoveryengine.v1alpha.ControlOrBuilder> getControlFieldBuilder() { if (controlBuilder_ == null) { controlBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.discoveryengine.v1alpha.Control, com.google.cloud.discoveryengine.v1alpha.Control.Builder, com.google.cloud.discoveryengine.v1alpha.ControlOrBuilder>( getControl(), getParentForChildren(), isClean()); control_ = null; } return controlBuilder_; } 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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. Indicates which fields in the provided * [Control][google.cloud.discoveryengine.v1alpha.Control] to update. The * following are NOT supported: * * * [Control.name][google.cloud.discoveryengine.v1alpha.Control.name] * * [Control.solution_type][google.cloud.discoveryengine.v1alpha.Control.solution_type] * * If not set or empty, all supported fields are 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.discoveryengine.v1alpha.UpdateControlRequest) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1alpha.UpdateControlRequest) private static final com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest(); } public static com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateControlRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateControlRequest>() { @java.lang.Override public UpdateControlRequest 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<UpdateControlRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateControlRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1alpha.UpdateControlRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,723
java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/SuggestKnowledgeAssistResponse.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/participant.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The response message for * [Participants.SuggestKnowledgeAssist][google.cloud.dialogflow.v2beta1.Participants.SuggestKnowledgeAssist]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse} */ public final class SuggestKnowledgeAssistResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse) SuggestKnowledgeAssistResponseOrBuilder { private static final long serialVersionUID = 0L; // Use SuggestKnowledgeAssistResponse.newBuilder() to construct. private SuggestKnowledgeAssistResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SuggestKnowledgeAssistResponse() { latestMessage_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SuggestKnowledgeAssistResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.ParticipantProto .internal_static_google_cloud_dialogflow_v2beta1_SuggestKnowledgeAssistResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.ParticipantProto .internal_static_google_cloud_dialogflow_v2beta1_SuggestKnowledgeAssistResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.class, com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.Builder.class); } private int bitField0_; public static final int KNOWLEDGE_ASSIST_ANSWER_FIELD_NUMBER = 1; private com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledgeAssistAnswer_; /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the knowledgeAssistAnswer field is set. */ @java.lang.Override public boolean hasKnowledgeAssistAnswer() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The knowledgeAssistAnswer. */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer getKnowledgeAssistAnswer() { return knowledgeAssistAnswer_ == null ? com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.getDefaultInstance() : knowledgeAssistAnswer_; } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswerOrBuilder getKnowledgeAssistAnswerOrBuilder() { return knowledgeAssistAnswer_ == null ? com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.getDefaultInstance() : knowledgeAssistAnswer_; } public static final int LATEST_MESSAGE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object latestMessage_ = ""; /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @return The latestMessage. */ @java.lang.Override public java.lang.String getLatestMessage() { java.lang.Object ref = latestMessage_; 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(); latestMessage_ = s; return s; } } /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @return The bytes for latestMessage. */ @java.lang.Override public com.google.protobuf.ByteString getLatestMessageBytes() { java.lang.Object ref = latestMessage_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); latestMessage_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONTEXT_SIZE_FIELD_NUMBER = 3; private int contextSize_ = 0; /** * * * <pre> * Number of messages prior to and including * [latest_message][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.latest_message] * to compile the suggestion. It may be smaller than the * [SuggestKnowledgeAssistRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistRequest.context_size] * field in the request if there are fewer messages in the conversation. * </pre> * * <code>int32 context_size = 3;</code> * * @return The contextSize. */ @java.lang.Override public int getContextSize() { return contextSize_; } 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, getKnowledgeAssistAnswer()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(latestMessage_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, latestMessage_); } if (contextSize_ != 0) { output.writeInt32(3, contextSize_); } 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, getKnowledgeAssistAnswer()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(latestMessage_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, latestMessage_); } if (contextSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, contextSize_); } 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.SuggestKnowledgeAssistResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse other = (com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse) obj; if (hasKnowledgeAssistAnswer() != other.hasKnowledgeAssistAnswer()) return false; if (hasKnowledgeAssistAnswer()) { if (!getKnowledgeAssistAnswer().equals(other.getKnowledgeAssistAnswer())) return false; } if (!getLatestMessage().equals(other.getLatestMessage())) return false; if (getContextSize() != other.getContextSize()) 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 (hasKnowledgeAssistAnswer()) { hash = (37 * hash) + KNOWLEDGE_ASSIST_ANSWER_FIELD_NUMBER; hash = (53 * hash) + getKnowledgeAssistAnswer().hashCode(); } hash = (37 * hash) + LATEST_MESSAGE_FIELD_NUMBER; hash = (53 * hash) + getLatestMessage().hashCode(); hash = (37 * hash) + CONTEXT_SIZE_FIELD_NUMBER; hash = (53 * hash) + getContextSize(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse 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.SuggestKnowledgeAssistResponse 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 * [Participants.SuggestKnowledgeAssist][google.cloud.dialogflow.v2beta1.Participants.SuggestKnowledgeAssist]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse) com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.ParticipantProto .internal_static_google_cloud_dialogflow_v2beta1_SuggestKnowledgeAssistResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.ParticipantProto .internal_static_google_cloud_dialogflow_v2beta1_SuggestKnowledgeAssistResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.class, com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.Builder.class); } // Construct using // com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getKnowledgeAssistAnswerFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; knowledgeAssistAnswer_ = null; if (knowledgeAssistAnswerBuilder_ != null) { knowledgeAssistAnswerBuilder_.dispose(); knowledgeAssistAnswerBuilder_ = null; } latestMessage_ = ""; contextSize_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.ParticipantProto .internal_static_google_cloud_dialogflow_v2beta1_SuggestKnowledgeAssistResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse build() { com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse buildPartial() { com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse result = new com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.knowledgeAssistAnswer_ = knowledgeAssistAnswerBuilder_ == null ? knowledgeAssistAnswer_ : knowledgeAssistAnswerBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.latestMessage_ = latestMessage_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.contextSize_ = contextSize_; } 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.SuggestKnowledgeAssistResponse) { return mergeFrom( (com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse other) { if (other == com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse .getDefaultInstance()) return this; if (other.hasKnowledgeAssistAnswer()) { mergeKnowledgeAssistAnswer(other.getKnowledgeAssistAnswer()); } if (!other.getLatestMessage().isEmpty()) { latestMessage_ = other.latestMessage_; bitField0_ |= 0x00000002; onChanged(); } if (other.getContextSize() != 0) { setContextSize(other.getContextSize()); } 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( getKnowledgeAssistAnswerFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { latestMessage_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { contextSize_ = input.readInt32(); 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 com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledgeAssistAnswer_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer, com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.Builder, com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswerOrBuilder> knowledgeAssistAnswerBuilder_; /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the knowledgeAssistAnswer field is set. */ public boolean hasKnowledgeAssistAnswer() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The knowledgeAssistAnswer. */ public com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer getKnowledgeAssistAnswer() { if (knowledgeAssistAnswerBuilder_ == null) { return knowledgeAssistAnswer_ == null ? com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.getDefaultInstance() : knowledgeAssistAnswer_; } else { return knowledgeAssistAnswerBuilder_.getMessage(); } } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setKnowledgeAssistAnswer( com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer value) { if (knowledgeAssistAnswerBuilder_ == null) { if (value == null) { throw new NullPointerException(); } knowledgeAssistAnswer_ = value; } else { knowledgeAssistAnswerBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setKnowledgeAssistAnswer( com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.Builder builderForValue) { if (knowledgeAssistAnswerBuilder_ == null) { knowledgeAssistAnswer_ = builderForValue.build(); } else { knowledgeAssistAnswerBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeKnowledgeAssistAnswer( com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer value) { if (knowledgeAssistAnswerBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && knowledgeAssistAnswer_ != null && knowledgeAssistAnswer_ != com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.getDefaultInstance()) { getKnowledgeAssistAnswerBuilder().mergeFrom(value); } else { knowledgeAssistAnswer_ = value; } } else { knowledgeAssistAnswerBuilder_.mergeFrom(value); } if (knowledgeAssistAnswer_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearKnowledgeAssistAnswer() { bitField0_ = (bitField0_ & ~0x00000001); knowledgeAssistAnswer_ = null; if (knowledgeAssistAnswerBuilder_ != null) { knowledgeAssistAnswerBuilder_.dispose(); knowledgeAssistAnswerBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.Builder getKnowledgeAssistAnswerBuilder() { bitField0_ |= 0x00000001; onChanged(); return getKnowledgeAssistAnswerFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswerOrBuilder getKnowledgeAssistAnswerOrBuilder() { if (knowledgeAssistAnswerBuilder_ != null) { return knowledgeAssistAnswerBuilder_.getMessageOrBuilder(); } else { return knowledgeAssistAnswer_ == null ? com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.getDefaultInstance() : knowledgeAssistAnswer_; } } /** * * * <pre> * Output only. Knowledge Assist suggestion. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer knowledge_assist_answer = 1 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer, com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.Builder, com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswerOrBuilder> getKnowledgeAssistAnswerFieldBuilder() { if (knowledgeAssistAnswerBuilder_ == null) { knowledgeAssistAnswerBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer, com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswer.Builder, com.google.cloud.dialogflow.v2beta1.KnowledgeAssistAnswerOrBuilder>( getKnowledgeAssistAnswer(), getParentForChildren(), isClean()); knowledgeAssistAnswer_ = null; } return knowledgeAssistAnswerBuilder_; } private java.lang.Object latestMessage_ = ""; /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @return The latestMessage. */ public java.lang.String getLatestMessage() { java.lang.Object ref = latestMessage_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); latestMessage_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @return The bytes for latestMessage. */ public com.google.protobuf.ByteString getLatestMessageBytes() { java.lang.Object ref = latestMessage_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); latestMessage_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @param value The latestMessage to set. * @return This builder for chaining. */ public Builder setLatestMessage(java.lang.String value) { if (value == null) { throw new NullPointerException(); } latestMessage_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @return This builder for chaining. */ public Builder clearLatestMessage() { latestMessage_ = getDefaultInstance().getLatestMessage(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The name of the latest conversation message used to compile suggestion for. * Format: `projects/&lt;Project ID&gt;/locations/&lt;Location * ID&gt;/conversations/&lt;Conversation ID&gt;/messages/&lt;Message ID&gt;`. * </pre> * * <code>string latest_message = 2;</code> * * @param value The bytes for latestMessage to set. * @return This builder for chaining. */ public Builder setLatestMessageBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); latestMessage_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private int contextSize_; /** * * * <pre> * Number of messages prior to and including * [latest_message][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.latest_message] * to compile the suggestion. It may be smaller than the * [SuggestKnowledgeAssistRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistRequest.context_size] * field in the request if there are fewer messages in the conversation. * </pre> * * <code>int32 context_size = 3;</code> * * @return The contextSize. */ @java.lang.Override public int getContextSize() { return contextSize_; } /** * * * <pre> * Number of messages prior to and including * [latest_message][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.latest_message] * to compile the suggestion. It may be smaller than the * [SuggestKnowledgeAssistRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistRequest.context_size] * field in the request if there are fewer messages in the conversation. * </pre> * * <code>int32 context_size = 3;</code> * * @param value The contextSize to set. * @return This builder for chaining. */ public Builder setContextSize(int value) { contextSize_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Number of messages prior to and including * [latest_message][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse.latest_message] * to compile the suggestion. It may be smaller than the * [SuggestKnowledgeAssistRequest.context_size][google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistRequest.context_size] * field in the request if there are fewer messages in the conversation. * </pre> * * <code>int32 context_size = 3;</code> * * @return This builder for chaining. */ public Builder clearContextSize() { bitField0_ = (bitField0_ & ~0x00000004); contextSize_ = 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.dialogflow.v2beta1.SuggestKnowledgeAssistResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse) private static final com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse(); } public static com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SuggestKnowledgeAssistResponse> PARSER = new com.google.protobuf.AbstractParser<SuggestKnowledgeAssistResponse>() { @java.lang.Override public SuggestKnowledgeAssistResponse 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<SuggestKnowledgeAssistResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SuggestKnowledgeAssistResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.SuggestKnowledgeAssistResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,756
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteLicenseRequest.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 Licenses.Delete. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.DeleteLicenseRequest} */ public final class DeleteLicenseRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteLicenseRequest) DeleteLicenseRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteLicenseRequest.newBuilder() to construct. private DeleteLicenseRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteLicenseRequest() { license_ = ""; project_ = ""; requestId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteLicenseRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteLicenseRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteLicenseRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.DeleteLicenseRequest.class, com.google.cloud.compute.v1.DeleteLicenseRequest.Builder.class); } private int bitField0_; public static final int LICENSE_FIELD_NUMBER = 166757441; @SuppressWarnings("serial") private volatile java.lang.Object license_ = ""; /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The license. */ @java.lang.Override public java.lang.String getLicense() { java.lang.Object ref = license_; 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(); license_ = s; return s; } } /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for license. */ @java.lang.Override public com.google.protobuf.ByteString getLicenseBytes() { java.lang.Object ref = license_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); license_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROJECT_FIELD_NUMBER = 227560217; @SuppressWarnings("serial") private volatile java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The project. */ @java.lang.Override public java.lang.String getProject() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The bytes for project. */ @java.lang.Override public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUEST_ID_FIELD_NUMBER = 37109963; @SuppressWarnings("serial") private volatile java.lang.Object requestId_ = ""; /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return Whether the requestId field is set. */ @java.lang.Override public boolean hasRequestId() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The requestId. */ @java.lang.Override public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The bytes for requestId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(license_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 166757441, license_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(license_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(166757441, license_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.DeleteLicenseRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.DeleteLicenseRequest other = (com.google.cloud.compute.v1.DeleteLicenseRequest) obj; if (!getLicense().equals(other.getLicense())) return false; if (!getProject().equals(other.getProject())) return false; if (hasRequestId() != other.hasRequestId()) return false; if (hasRequestId()) { if (!getRequestId().equals(other.getRequestId())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + LICENSE_FIELD_NUMBER; hash = (53 * hash) + getLicense().hashCode(); hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().hashCode(); if (hasRequestId()) { hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.DeleteLicenseRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.DeleteLicenseRequest 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.DeleteLicenseRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.DeleteLicenseRequest 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.DeleteLicenseRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.DeleteLicenseRequest 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.DeleteLicenseRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.DeleteLicenseRequest 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.DeleteLicenseRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.DeleteLicenseRequest 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.DeleteLicenseRequest 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.DeleteLicenseRequest 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.DeleteLicenseRequest 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 Licenses.Delete. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.DeleteLicenseRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteLicenseRequest) com.google.cloud.compute.v1.DeleteLicenseRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteLicenseRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteLicenseRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.DeleteLicenseRequest.class, com.google.cloud.compute.v1.DeleteLicenseRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.DeleteLicenseRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; license_ = ""; project_ = ""; requestId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_DeleteLicenseRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.DeleteLicenseRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.DeleteLicenseRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.DeleteLicenseRequest build() { com.google.cloud.compute.v1.DeleteLicenseRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.DeleteLicenseRequest buildPartial() { com.google.cloud.compute.v1.DeleteLicenseRequest result = new com.google.cloud.compute.v1.DeleteLicenseRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.DeleteLicenseRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.license_ = license_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.project_ = project_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.requestId_ = requestId_; to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.DeleteLicenseRequest) { return mergeFrom((com.google.cloud.compute.v1.DeleteLicenseRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.DeleteLicenseRequest other) { if (other == com.google.cloud.compute.v1.DeleteLicenseRequest.getDefaultInstance()) return this; if (!other.getLicense().isEmpty()) { license_ = other.license_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasRequestId()) { requestId_ = other.requestId_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 296879706: { requestId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 296879706 case 1334059530: { license_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 1334059530 case 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 1820481738 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object license_ = ""; /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The license. */ public java.lang.String getLicense() { java.lang.Object ref = license_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); license_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for license. */ public com.google.protobuf.ByteString getLicenseBytes() { java.lang.Object ref = license_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); license_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The license to set. * @return This builder for chaining. */ public Builder setLicense(java.lang.String value) { if (value == null) { throw new NullPointerException(); } license_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearLicense() { license_ = getDefaultInstance().getLicense(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of the license resource to delete. * </pre> * * <code>string license = 166757441 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for license to set. * @return This builder for chaining. */ public Builder setLicenseBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); license_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object project_ = ""; /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The project. */ public java.lang.String getProject() { java.lang.Object ref = project_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); project_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return The bytes for project. */ public com.google.protobuf.ByteString getProjectBytes() { java.lang.Object ref = project_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); project_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @param value The project to set. * @return This builder for chaining. */ public Builder setProject(java.lang.String value) { if (value == null) { throw new NullPointerException(); } project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @return This builder for chaining. */ public Builder clearProject() { project_ = getDefaultInstance().getProject(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Project ID for this request. * </pre> * * <code> * string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"]; * </code> * * @param value The bytes for project to set. * @return This builder for chaining. */ public Builder setProjectBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); project_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object requestId_ = ""; /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return Whether the requestId field is set. */ public boolean hasRequestId() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The requestId. */ public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return The bytes for requestId. */ public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @param value The requestId to set. * @return This builder for chaining. */ public Builder setRequestId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @return This builder for chaining. */ public Builder clearRequestId() { requestId_ = getDefaultInstance().getRequestId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000). * </pre> * * <code>optional string request_id = 37109963;</code> * * @param value The bytes for requestId to set. * @return This builder for chaining. */ public Builder setRequestIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.DeleteLicenseRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteLicenseRequest) private static final com.google.cloud.compute.v1.DeleteLicenseRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteLicenseRequest(); } public static com.google.cloud.compute.v1.DeleteLicenseRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteLicenseRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteLicenseRequest>() { @java.lang.Override public DeleteLicenseRequest 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<DeleteLicenseRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteLicenseRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.DeleteLicenseRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,666
java-dialogflow/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/ListContextsResponse.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/v2/context.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2; /** * * * <pre> * The response message for * [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.ListContextsResponse} */ public final class ListContextsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.ListContextsResponse) ListContextsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListContextsResponse.newBuilder() to construct. private ListContextsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListContextsResponse() { contexts_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListContextsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.ContextProto .internal_static_google_cloud_dialogflow_v2_ListContextsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.ContextProto .internal_static_google_cloud_dialogflow_v2_ListContextsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.ListContextsResponse.class, com.google.cloud.dialogflow.v2.ListContextsResponse.Builder.class); } public static final int CONTEXTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.v2.Context> contexts_; /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.v2.Context> getContextsList() { return contexts_; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.v2.ContextOrBuilder> getContextsOrBuilderList() { return contexts_; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ @java.lang.Override public int getContextsCount() { return contexts_.size(); } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.Context getContexts(int index) { return contexts_.get(index); } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2.ContextOrBuilder getContextsOrBuilder(int index) { return contexts_.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 < contexts_.size(); i++) { output.writeMessage(1, contexts_.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 < contexts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, contexts_.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.dialogflow.v2.ListContextsResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2.ListContextsResponse other = (com.google.cloud.dialogflow.v2.ListContextsResponse) obj; if (!getContextsList().equals(other.getContextsList())) 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 (getContextsCount() > 0) { hash = (37 * hash) + CONTEXTS_FIELD_NUMBER; hash = (53 * hash) + getContextsList().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.dialogflow.v2.ListContextsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.ListContextsResponse 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.v2.ListContextsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.ListContextsResponse 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.v2.ListContextsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2.ListContextsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dialogflow.v2.ListContextsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.ListContextsResponse 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.v2.ListContextsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.ListContextsResponse 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.v2.ListContextsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2.ListContextsResponse 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.v2.ListContextsResponse 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 * [Contexts.ListContexts][google.cloud.dialogflow.v2.Contexts.ListContexts]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2.ListContextsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.ListContextsResponse) com.google.cloud.dialogflow.v2.ListContextsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2.ContextProto .internal_static_google_cloud_dialogflow_v2_ListContextsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2.ContextProto .internal_static_google_cloud_dialogflow_v2_ListContextsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2.ListContextsResponse.class, com.google.cloud.dialogflow.v2.ListContextsResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.v2.ListContextsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (contextsBuilder_ == null) { contexts_ = java.util.Collections.emptyList(); } else { contexts_ = null; contextsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2.ContextProto .internal_static_google_cloud_dialogflow_v2_ListContextsResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2.ListContextsResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2.ListContextsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2.ListContextsResponse build() { com.google.cloud.dialogflow.v2.ListContextsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2.ListContextsResponse buildPartial() { com.google.cloud.dialogflow.v2.ListContextsResponse result = new com.google.cloud.dialogflow.v2.ListContextsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.v2.ListContextsResponse result) { if (contextsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { contexts_ = java.util.Collections.unmodifiableList(contexts_); bitField0_ = (bitField0_ & ~0x00000001); } result.contexts_ = contexts_; } else { result.contexts_ = contextsBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.v2.ListContextsResponse 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.dialogflow.v2.ListContextsResponse) { return mergeFrom((com.google.cloud.dialogflow.v2.ListContextsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2.ListContextsResponse other) { if (other == com.google.cloud.dialogflow.v2.ListContextsResponse.getDefaultInstance()) return this; if (contextsBuilder_ == null) { if (!other.contexts_.isEmpty()) { if (contexts_.isEmpty()) { contexts_ = other.contexts_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureContextsIsMutable(); contexts_.addAll(other.contexts_); } onChanged(); } } else { if (!other.contexts_.isEmpty()) { if (contextsBuilder_.isEmpty()) { contextsBuilder_.dispose(); contextsBuilder_ = null; contexts_ = other.contexts_; bitField0_ = (bitField0_ & ~0x00000001); contextsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getContextsFieldBuilder() : null; } else { contextsBuilder_.addAllMessages(other.contexts_); } } } 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.dialogflow.v2.Context m = input.readMessage( com.google.cloud.dialogflow.v2.Context.parser(), extensionRegistry); if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.add(m); } else { contextsBuilder_.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.dialogflow.v2.Context> contexts_ = java.util.Collections.emptyList(); private void ensureContextsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { contexts_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2.Context>(contexts_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Context, com.google.cloud.dialogflow.v2.Context.Builder, com.google.cloud.dialogflow.v2.ContextOrBuilder> contextsBuilder_; /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2.Context> getContextsList() { if (contextsBuilder_ == null) { return java.util.Collections.unmodifiableList(contexts_); } else { return contextsBuilder_.getMessageList(); } } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public int getContextsCount() { if (contextsBuilder_ == null) { return contexts_.size(); } else { return contextsBuilder_.getCount(); } } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public com.google.cloud.dialogflow.v2.Context getContexts(int index) { if (contextsBuilder_ == null) { return contexts_.get(index); } else { return contextsBuilder_.getMessage(index); } } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder setContexts(int index, com.google.cloud.dialogflow.v2.Context value) { if (contextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContextsIsMutable(); contexts_.set(index, value); onChanged(); } else { contextsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder setContexts( int index, com.google.cloud.dialogflow.v2.Context.Builder builderForValue) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.set(index, builderForValue.build()); onChanged(); } else { contextsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder addContexts(com.google.cloud.dialogflow.v2.Context value) { if (contextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContextsIsMutable(); contexts_.add(value); onChanged(); } else { contextsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder addContexts(int index, com.google.cloud.dialogflow.v2.Context value) { if (contextsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureContextsIsMutable(); contexts_.add(index, value); onChanged(); } else { contextsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder addContexts(com.google.cloud.dialogflow.v2.Context.Builder builderForValue) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.add(builderForValue.build()); onChanged(); } else { contextsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder addContexts( int index, com.google.cloud.dialogflow.v2.Context.Builder builderForValue) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.add(index, builderForValue.build()); onChanged(); } else { contextsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder addAllContexts( java.lang.Iterable<? extends com.google.cloud.dialogflow.v2.Context> values) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, contexts_); onChanged(); } else { contextsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder clearContexts() { if (contextsBuilder_ == null) { contexts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { contextsBuilder_.clear(); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public Builder removeContexts(int index) { if (contextsBuilder_ == null) { ensureContextsIsMutable(); contexts_.remove(index); onChanged(); } else { contextsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public com.google.cloud.dialogflow.v2.Context.Builder getContextsBuilder(int index) { return getContextsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public com.google.cloud.dialogflow.v2.ContextOrBuilder getContextsOrBuilder(int index) { if (contextsBuilder_ == null) { return contexts_.get(index); } else { return contextsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.v2.ContextOrBuilder> getContextsOrBuilderList() { if (contextsBuilder_ != null) { return contextsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(contexts_); } } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public com.google.cloud.dialogflow.v2.Context.Builder addContextsBuilder() { return getContextsFieldBuilder() .addBuilder(com.google.cloud.dialogflow.v2.Context.getDefaultInstance()); } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public com.google.cloud.dialogflow.v2.Context.Builder addContextsBuilder(int index) { return getContextsFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.v2.Context.getDefaultInstance()); } /** * * * <pre> * The list of contexts. There will be a maximum number of items * returned based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.v2.Context contexts = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2.Context.Builder> getContextsBuilderList() { return getContextsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Context, com.google.cloud.dialogflow.v2.Context.Builder, com.google.cloud.dialogflow.v2.ContextOrBuilder> getContextsFieldBuilder() { if (contextsBuilder_ == null) { contextsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2.Context, com.google.cloud.dialogflow.v2.Context.Builder, com.google.cloud.dialogflow.v2.ContextOrBuilder>( contexts_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); contexts_ = null; } return contextsBuilder_; } 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.dialogflow.v2.ListContextsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.ListContextsResponse) private static final com.google.cloud.dialogflow.v2.ListContextsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.ListContextsResponse(); } public static com.google.cloud.dialogflow.v2.ListContextsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListContextsResponse> PARSER = new com.google.protobuf.AbstractParser<ListContextsResponse>() { @java.lang.Override public ListContextsResponse 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<ListContextsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListContextsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2.ListContextsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
37,923
jdk/src/share/classes/java/lang/Float.java
/* * Copyright (c) 1994, 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 java.lang; import sun.misc.FloatingDecimal; import sun.misc.FloatConsts; import sun.misc.DoubleConsts; /** * The {@code Float} class wraps a value of primitive type * {@code float} in an object. An object of type * {@code Float} contains a single field whose type is * {@code float}. * * <p>In addition, this class provides several methods for converting a * {@code float} to a {@code String} and a * {@code String} to a {@code float}, as well as other * constants and methods useful when dealing with a * {@code float}. * * @author Lee Boynton * @author Arthur van Hoff * @author Joseph D. Darcy * @since JDK1.0 */ public final class Float extends Number implements Comparable<Float> { /** * A constant holding the positive infinity of type * {@code float}. It is equal to the value returned by * {@code Float.intBitsToFloat(0x7f800000)}. */ public static final float POSITIVE_INFINITY = 1.0f / 0.0f; /** * A constant holding the negative infinity of type * {@code float}. It is equal to the value returned by * {@code Float.intBitsToFloat(0xff800000)}. */ public static final float NEGATIVE_INFINITY = -1.0f / 0.0f; /** * A constant holding a Not-a-Number (NaN) value of type * {@code float}. It is equivalent to the value returned by * {@code Float.intBitsToFloat(0x7fc00000)}. */ public static final float NaN = 0.0f / 0.0f; /** * A constant holding the largest positive finite value of type * {@code float}, (2-2<sup>-23</sup>)&middot;2<sup>127</sup>. * It is equal to the hexadecimal floating-point literal * {@code 0x1.fffffeP+127f} and also equal to * {@code Float.intBitsToFloat(0x7f7fffff)}. */ public static final float MAX_VALUE = 0x1.fffffeP+127f; // 3.4028235e+38f /** * A constant holding the smallest positive normal value of type * {@code float}, 2<sup>-126</sup>. It is equal to the * hexadecimal floating-point literal {@code 0x1.0p-126f} and also * equal to {@code Float.intBitsToFloat(0x00800000)}. * * @since 1.6 */ public static final float MIN_NORMAL = 0x1.0p-126f; // 1.17549435E-38f /** * A constant holding the smallest positive nonzero value of type * {@code float}, 2<sup>-149</sup>. It is equal to the * hexadecimal floating-point literal {@code 0x0.000002P-126f} * and also equal to {@code Float.intBitsToFloat(0x1)}. */ public static final float MIN_VALUE = 0x0.000002P-126f; // 1.4e-45f /** * Maximum exponent a finite {@code float} variable may have. It * is equal to the value returned by {@code * Math.getExponent(Float.MAX_VALUE)}. * * @since 1.6 */ public static final int MAX_EXPONENT = 127; /** * Minimum exponent a normalized {@code float} variable may have. * It is equal to the value returned by {@code * Math.getExponent(Float.MIN_NORMAL)}. * * @since 1.6 */ public static final int MIN_EXPONENT = -126; /** * The number of bits used to represent a {@code float} value. * * @since 1.5 */ public static final int SIZE = 32; /** * The number of bytes used to represent a {@code float} value. * * @since 1.8 */ public static final int BYTES = SIZE / Byte.SIZE; /** * The {@code Class} instance representing the primitive type * {@code float}. * * @since JDK1.1 */ @SuppressWarnings("unchecked") public static final Class<Float> TYPE = (Class<Float>) Class.getPrimitiveClass("float"); /** * Returns a string representation of the {@code float} * argument. All characters mentioned below are ASCII characters. * <ul> * <li>If the argument is NaN, the result is the string * "{@code NaN}". * <li>Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. If the sign is * negative, the first character of the result is * '{@code -}' ({@code '\u005Cu002D'}); if the sign is * positive, no sign character appears in the result. As for * the magnitude <i>m</i>: * <ul> * <li>If <i>m</i> is infinity, it is represented by the characters * {@code "Infinity"}; thus, positive infinity produces * the result {@code "Infinity"} and negative infinity * produces the result {@code "-Infinity"}. * <li>If <i>m</i> is zero, it is represented by the characters * {@code "0.0"}; thus, negative zero produces the result * {@code "-0.0"} and positive zero produces the result * {@code "0.0"}. * <li> If <i>m</i> is greater than or equal to 10<sup>-3</sup> but * less than 10<sup>7</sup>, then it is represented as the * integer part of <i>m</i>, in decimal form with no leading * zeroes, followed by '{@code .}' * ({@code '\u005Cu002E'}), followed by one or more * decimal digits representing the fractional part of * <i>m</i>. * <li> If <i>m</i> is less than 10<sup>-3</sup> or greater than or * equal to 10<sup>7</sup>, then it is represented in * so-called "computerized scientific notation." Let <i>n</i> * be the unique integer such that 10<sup><i>n</i> </sup>&le; * <i>m</i> {@literal <} 10<sup><i>n</i>+1</sup>; then let <i>a</i> * be the mathematically exact quotient of <i>m</i> and * 10<sup><i>n</i></sup> so that 1 &le; <i>a</i> {@literal <} 10. * The magnitude is then represented as the integer part of * <i>a</i>, as a single decimal digit, followed by * '{@code .}' ({@code '\u005Cu002E'}), followed by * decimal digits representing the fractional part of * <i>a</i>, followed by the letter '{@code E}' * ({@code '\u005Cu0045'}), followed by a representation * of <i>n</i> as a decimal integer, as produced by the * method {@link java.lang.Integer#toString(int)}. * * </ul> * </ul> * How many digits must be printed for the fractional part of * <i>m</i> or <i>a</i>? There must be at least one digit * to represent the fractional part, and beyond that as many, but * only as many, more digits as are needed to uniquely distinguish * the argument value from adjacent values of type * {@code float}. That is, suppose that <i>x</i> is the * exact mathematical value represented by the decimal * representation produced by this method for a finite nonzero * argument <i>f</i>. Then <i>f</i> must be the {@code float} * value nearest to <i>x</i>; or, if two {@code float} values are * equally close to <i>x</i>, then <i>f</i> must be one of * them and the least significant bit of the significand of * <i>f</i> must be {@code 0}. * * <p>To create localized string representations of a floating-point * value, use subclasses of {@link java.text.NumberFormat}. * * @param f the float to be converted. * @return a string representation of the argument. */ public static String toString(float f) { return FloatingDecimal.toJavaFormatString(f); } /** * Returns a hexadecimal string representation of the * {@code float} argument. All characters mentioned below are * ASCII characters. * * <ul> * <li>If the argument is NaN, the result is the string * "{@code NaN}". * <li>Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. If the sign is negative, * the first character of the result is '{@code -}' * ({@code '\u005Cu002D'}); if the sign is positive, no sign character * appears in the result. As for the magnitude <i>m</i>: * * <ul> * <li>If <i>m</i> is infinity, it is represented by the string * {@code "Infinity"}; thus, positive infinity produces the * result {@code "Infinity"} and negative infinity produces * the result {@code "-Infinity"}. * * <li>If <i>m</i> is zero, it is represented by the string * {@code "0x0.0p0"}; thus, negative zero produces the result * {@code "-0x0.0p0"} and positive zero produces the result * {@code "0x0.0p0"}. * * <li>If <i>m</i> is a {@code float} value with a * normalized representation, substrings are used to represent the * significand and exponent fields. The significand is * represented by the characters {@code "0x1."} * followed by a lowercase hexadecimal representation of the rest * of the significand as a fraction. Trailing zeros in the * hexadecimal representation are removed unless all the digits * are zero, in which case a single zero is used. Next, the * exponent is represented by {@code "p"} followed * by a decimal string of the unbiased exponent as if produced by * a call to {@link Integer#toString(int) Integer.toString} on the * exponent value. * * <li>If <i>m</i> is a {@code float} value with a subnormal * representation, the significand is represented by the * characters {@code "0x0."} followed by a * hexadecimal representation of the rest of the significand as a * fraction. Trailing zeros in the hexadecimal representation are * removed. Next, the exponent is represented by * {@code "p-126"}. Note that there must be at * least one nonzero digit in a subnormal significand. * * </ul> * * </ul> * * <table border> * <caption>Examples</caption> * <tr><th>Floating-point Value</th><th>Hexadecimal String</th> * <tr><td>{@code 1.0}</td> <td>{@code 0x1.0p0}</td> * <tr><td>{@code -1.0}</td> <td>{@code -0x1.0p0}</td> * <tr><td>{@code 2.0}</td> <td>{@code 0x1.0p1}</td> * <tr><td>{@code 3.0}</td> <td>{@code 0x1.8p1}</td> * <tr><td>{@code 0.5}</td> <td>{@code 0x1.0p-1}</td> * <tr><td>{@code 0.25}</td> <td>{@code 0x1.0p-2}</td> * <tr><td>{@code Float.MAX_VALUE}</td> * <td>{@code 0x1.fffffep127}</td> * <tr><td>{@code Minimum Normal Value}</td> * <td>{@code 0x1.0p-126}</td> * <tr><td>{@code Maximum Subnormal Value}</td> * <td>{@code 0x0.fffffep-126}</td> * <tr><td>{@code Float.MIN_VALUE}</td> * <td>{@code 0x0.000002p-126}</td> * </table> * @param f the {@code float} to be converted. * @return a hex string representation of the argument. * @since 1.5 * @author Joseph D. Darcy */ public static String toHexString(float f) { if (Math.abs(f) < FloatConsts.MIN_NORMAL && f != 0.0f ) {// float subnormal // Adjust exponent to create subnormal double, then // replace subnormal double exponent with subnormal float // exponent String s = Double.toHexString(Math.scalb((double)f, /* -1022+126 */ DoubleConsts.MIN_EXPONENT- FloatConsts.MIN_EXPONENT)); return s.replaceFirst("p-1022$", "p-126"); } else // double string will be the same as float string return Double.toHexString(f); } /** * Returns a {@code Float} object holding the * {@code float} value represented by the argument string * {@code s}. * * <p>If {@code s} is {@code null}, then a * {@code NullPointerException} is thrown. * * <p>Leading and trailing whitespace characters in {@code s} * are ignored. Whitespace is removed as if by the {@link * String#trim} method; that is, both ASCII space and control * characters are removed. The rest of {@code s} should * constitute a <i>FloatValue</i> as described by the lexical * syntax rules: * * <blockquote> * <dl> * <dt><i>FloatValue:</i> * <dd><i>Sign<sub>opt</sub></i> {@code NaN} * <dd><i>Sign<sub>opt</sub></i> {@code Infinity} * <dd><i>Sign<sub>opt</sub> FloatingPointLiteral</i> * <dd><i>Sign<sub>opt</sub> HexFloatingPointLiteral</i> * <dd><i>SignedInteger</i> * </dl> * * <dl> * <dt><i>HexFloatingPointLiteral</i>: * <dd> <i>HexSignificand BinaryExponent FloatTypeSuffix<sub>opt</sub></i> * </dl> * * <dl> * <dt><i>HexSignificand:</i> * <dd><i>HexNumeral</i> * <dd><i>HexNumeral</i> {@code .} * <dd>{@code 0x} <i>HexDigits<sub>opt</sub> * </i>{@code .}<i> HexDigits</i> * <dd>{@code 0X}<i> HexDigits<sub>opt</sub> * </i>{@code .} <i>HexDigits</i> * </dl> * * <dl> * <dt><i>BinaryExponent:</i> * <dd><i>BinaryExponentIndicator SignedInteger</i> * </dl> * * <dl> * <dt><i>BinaryExponentIndicator:</i> * <dd>{@code p} * <dd>{@code P} * </dl> * * </blockquote> * * where <i>Sign</i>, <i>FloatingPointLiteral</i>, * <i>HexNumeral</i>, <i>HexDigits</i>, <i>SignedInteger</i> and * <i>FloatTypeSuffix</i> are as defined in the lexical structure * sections of * <cite>The Java&trade; Language Specification</cite>, * except that underscores are not accepted between digits. * If {@code s} does not have the form of * a <i>FloatValue</i>, then a {@code NumberFormatException} * is thrown. Otherwise, {@code s} is regarded as * representing an exact decimal value in the usual * "computerized scientific notation" or as an exact * hexadecimal value; this exact numerical value is then * conceptually converted to an "infinitely precise" * binary value that is then rounded to type {@code float} * by the usual round-to-nearest rule of IEEE 754 floating-point * arithmetic, which includes preserving the sign of a zero * value. * * Note that the round-to-nearest rule also implies overflow and * underflow behaviour; if the exact value of {@code s} is large * enough in magnitude (greater than or equal to ({@link * #MAX_VALUE} + {@link Math#ulp(float) ulp(MAX_VALUE)}/2), * rounding to {@code float} will result in an infinity and if the * exact value of {@code s} is small enough in magnitude (less * than or equal to {@link #MIN_VALUE}/2), rounding to float will * result in a zero. * * Finally, after rounding a {@code Float} object representing * this {@code float} value is returned. * * <p>To interpret localized string representations of a * floating-point value, use subclasses of {@link * java.text.NumberFormat}. * * <p>Note that trailing format specifiers, specifiers that * determine the type of a floating-point literal * ({@code 1.0f} is a {@code float} value; * {@code 1.0d} is a {@code double} value), do * <em>not</em> influence the results of this method. In other * words, the numerical value of the input string is converted * directly to the target floating-point type. In general, the * two-step sequence of conversions, string to {@code double} * followed by {@code double} to {@code float}, is * <em>not</em> equivalent to converting a string directly to * {@code float}. For example, if first converted to an * intermediate {@code double} and then to * {@code float}, the string<br> * {@code "1.00000017881393421514957253748434595763683319091796875001d"}<br> * results in the {@code float} value * {@code 1.0000002f}; if the string is converted directly to * {@code float}, <code>1.000000<b>1</b>f</code> results. * * <p>To avoid calling this method on an invalid string and having * a {@code NumberFormatException} be thrown, the documentation * for {@link Double#valueOf Double.valueOf} lists a regular * expression which can be used to screen the input. * * @param s the string to be parsed. * @return a {@code Float} object holding the value * represented by the {@code String} argument. * @throws NumberFormatException if the string does not contain a * parsable number. */ public static Float valueOf(String s) throws NumberFormatException { return new Float(parseFloat(s)); } /** * Returns a {@code Float} instance representing the specified * {@code float} value. * If a new {@code Float} instance is not required, this method * should generally be used in preference to the constructor * {@link #Float(float)}, as this method is likely to yield * significantly better space and time performance by caching * frequently requested values. * * @param f a float value. * @return a {@code Float} instance representing {@code f}. * @since 1.5 */ public static Float valueOf(float f) { return new Float(f); } /** * Returns a new {@code float} initialized to the value * represented by the specified {@code String}, as performed * by the {@code valueOf} method of class {@code Float}. * * @param s the string to be parsed. * @return the {@code float} value represented by the string * argument. * @throws NullPointerException if the string is null * @throws NumberFormatException if the string does not contain a * parsable {@code float}. * @see java.lang.Float#valueOf(String) * @since 1.2 */ public static float parseFloat(String s) throws NumberFormatException { return FloatingDecimal.parseFloat(s); } /** * Returns {@code true} if the specified number is a * Not-a-Number (NaN) value, {@code false} otherwise. * * @param v the value to be tested. * @return {@code true} if the argument is NaN; * {@code false} otherwise. */ public static boolean isNaN(float v) { return (v != v); } /** * Returns {@code true} if the specified number is infinitely * large in magnitude, {@code false} otherwise. * * @param v the value to be tested. * @return {@code true} if the argument is positive infinity or * negative infinity; {@code false} otherwise. */ public static boolean isInfinite(float v) { return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY); } /** * Returns {@code true} if the argument is a finite floating-point * value; returns {@code false} otherwise (for NaN and infinity * arguments). * * @param f the {@code float} value to be tested * @return {@code true} if the argument is a finite * floating-point value, {@code false} otherwise. * @since 1.8 */ public static boolean isFinite(float f) { return Math.abs(f) <= FloatConsts.MAX_VALUE; } /** * The value of the Float. * * @serial */ private final float value; /** * Constructs a newly allocated {@code Float} object that * represents the primitive {@code float} argument. * * @param value the value to be represented by the {@code Float}. */ public Float(float value) { this.value = value; } /** * Constructs a newly allocated {@code Float} object that * represents the argument converted to type {@code float}. * * @param value the value to be represented by the {@code Float}. */ public Float(double value) { this.value = (float)value; } /** * Constructs a newly allocated {@code Float} object that * represents the floating-point value of type {@code float} * represented by the string. The string is converted to a * {@code float} value as if by the {@code valueOf} method. * * @param s a string to be converted to a {@code Float}. * @throws NumberFormatException if the string does not contain a * parsable number. * @see java.lang.Float#valueOf(java.lang.String) */ public Float(String s) throws NumberFormatException { value = parseFloat(s); } /** * Returns {@code true} if this {@code Float} value is a * Not-a-Number (NaN), {@code false} otherwise. * * @return {@code true} if the value represented by this object is * NaN; {@code false} otherwise. */ public boolean isNaN() { return isNaN(value); } /** * Returns {@code true} if this {@code Float} value is * infinitely large in magnitude, {@code false} otherwise. * * @return {@code true} if the value represented by this object is * positive infinity or negative infinity; * {@code false} otherwise. */ public boolean isInfinite() { return isInfinite(value); } /** * Returns a string representation of this {@code Float} object. * The primitive {@code float} value represented by this object * is converted to a {@code String} exactly as if by the method * {@code toString} of one argument. * * @return a {@code String} representation of this object. * @see java.lang.Float#toString(float) */ public String toString() { return Float.toString(value); } /** * Returns the value of this {@code Float} as a {@code byte} after * a narrowing primitive conversion. * * @return the {@code float} value represented by this object * converted to type {@code byte} * @jls 5.1.3 Narrowing Primitive Conversions */ public byte byteValue() { return (byte)value; } /** * Returns the value of this {@code Float} as a {@code short} * after a narrowing primitive conversion. * * @return the {@code float} value represented by this object * converted to type {@code short} * @jls 5.1.3 Narrowing Primitive Conversions * @since JDK1.1 */ public short shortValue() { return (short)value; } /** * Returns the value of this {@code Float} as an {@code int} after * a narrowing primitive conversion. * * @return the {@code float} value represented by this object * converted to type {@code int} * @jls 5.1.3 Narrowing Primitive Conversions */ public int intValue() { return (int)value; } /** * Returns value of this {@code Float} as a {@code long} after a * narrowing primitive conversion. * * @return the {@code float} value represented by this object * converted to type {@code long} * @jls 5.1.3 Narrowing Primitive Conversions */ public long longValue() { return (long)value; } /** * Returns the {@code float} value of this {@code Float} object. * * @return the {@code float} value represented by this object */ public float floatValue() { return value; } /** * Returns the value of this {@code Float} as a {@code double} * after a widening primitive conversion. * * @return the {@code float} value represented by this * object converted to type {@code double} * @jls 5.1.2 Widening Primitive Conversions */ public double doubleValue() { return (double)value; } /** * Returns a hash code for this {@code Float} object. The * result is the integer bit representation, exactly as produced * by the method {@link #floatToIntBits(float)}, of the primitive * {@code float} value represented by this {@code Float} * object. * * @return a hash code value for this object. */ @Override public int hashCode() { return Float.hashCode(value); } /** * Returns a hash code for a {@code float} value; compatible with * {@code Float.hashCode()}. * * @param value the value to hash * @return a hash code value for a {@code float} value. * @since 1.8 */ public static int hashCode(float value) { return floatToIntBits(value); } /** * Compares this object against the specified object. The result * is {@code true} if and only if the argument is not * {@code null} and is a {@code Float} object that * represents a {@code float} with the same value as the * {@code float} represented by this object. For this * purpose, two {@code float} values are considered to be the * same if and only if the method {@link #floatToIntBits(float)} * returns the identical {@code int} value when applied to * each. * * <p>Note that in most cases, for two instances of class * {@code Float}, {@code f1} and {@code f2}, the value * of {@code f1.equals(f2)} is {@code true} if and only if * * <blockquote><pre> * f1.floatValue() == f2.floatValue() * </pre></blockquote> * * <p>also has the value {@code true}. However, there are two exceptions: * <ul> * <li>If {@code f1} and {@code f2} both represent * {@code Float.NaN}, then the {@code equals} method returns * {@code true}, even though {@code Float.NaN==Float.NaN} * has the value {@code false}. * <li>If {@code f1} represents {@code +0.0f} while * {@code f2} represents {@code -0.0f}, or vice * versa, the {@code equal} test has the value * {@code false}, even though {@code 0.0f==-0.0f} * has the value {@code true}. * </ul> * * This definition allows hash tables to operate properly. * * @param obj the object to be compared * @return {@code true} if the objects are the same; * {@code false} otherwise. * @see java.lang.Float#floatToIntBits(float) */ public boolean equals(Object obj) { return (obj instanceof Float) && (floatToIntBits(((Float)obj).value) == floatToIntBits(value)); } /** * Returns a representation of the specified floating-point value * according to the IEEE 754 floating-point "single format" bit * layout. * * <p>Bit 31 (the bit that is selected by the mask * {@code 0x80000000}) represents the sign of the floating-point * number. * Bits 30-23 (the bits that are selected by the mask * {@code 0x7f800000}) represent the exponent. * Bits 22-0 (the bits that are selected by the mask * {@code 0x007fffff}) represent the significand (sometimes called * the mantissa) of the floating-point number. * * <p>If the argument is positive infinity, the result is * {@code 0x7f800000}. * * <p>If the argument is negative infinity, the result is * {@code 0xff800000}. * * <p>If the argument is NaN, the result is {@code 0x7fc00000}. * * <p>In all cases, the result is an integer that, when given to the * {@link #intBitsToFloat(int)} method, will produce a floating-point * value the same as the argument to {@code floatToIntBits} * (except all NaN values are collapsed to a single * "canonical" NaN value). * * @param value a floating-point number. * @return the bits that represent the floating-point number. */ public static int floatToIntBits(float value) { int result = floatToRawIntBits(value); // Check for NaN based on values of bit fields, maximum // exponent and nonzero significand. if ( ((result & FloatConsts.EXP_BIT_MASK) == FloatConsts.EXP_BIT_MASK) && (result & FloatConsts.SIGNIF_BIT_MASK) != 0) result = 0x7fc00000; return result; } /** * Returns a representation of the specified floating-point value * according to the IEEE 754 floating-point "single format" bit * layout, preserving Not-a-Number (NaN) values. * * <p>Bit 31 (the bit that is selected by the mask * {@code 0x80000000}) represents the sign of the floating-point * number. * Bits 30-23 (the bits that are selected by the mask * {@code 0x7f800000}) represent the exponent. * Bits 22-0 (the bits that are selected by the mask * {@code 0x007fffff}) represent the significand (sometimes called * the mantissa) of the floating-point number. * * <p>If the argument is positive infinity, the result is * {@code 0x7f800000}. * * <p>If the argument is negative infinity, the result is * {@code 0xff800000}. * * <p>If the argument is NaN, the result is the integer representing * the actual NaN value. Unlike the {@code floatToIntBits} * method, {@code floatToRawIntBits} does not collapse all the * bit patterns encoding a NaN to a single "canonical" * NaN value. * * <p>In all cases, the result is an integer that, when given to the * {@link #intBitsToFloat(int)} method, will produce a * floating-point value the same as the argument to * {@code floatToRawIntBits}. * * @param value a floating-point number. * @return the bits that represent the floating-point number. * @since 1.3 */ public static native int floatToRawIntBits(float value); /** * Returns the {@code float} value corresponding to a given * bit representation. * The argument is considered to be a representation of a * floating-point value according to the IEEE 754 floating-point * "single format" bit layout. * * <p>If the argument is {@code 0x7f800000}, the result is positive * infinity. * * <p>If the argument is {@code 0xff800000}, the result is negative * infinity. * * <p>If the argument is any value in the range * {@code 0x7f800001} through {@code 0x7fffffff} or in * the range {@code 0xff800001} through * {@code 0xffffffff}, the result is a NaN. No IEEE 754 * floating-point operation provided by Java can distinguish * between two NaN values of the same type with different bit * patterns. Distinct values of NaN are only distinguishable by * use of the {@code Float.floatToRawIntBits} method. * * <p>In all other cases, let <i>s</i>, <i>e</i>, and <i>m</i> be three * values that can be computed from the argument: * * <blockquote><pre>{@code * int s = ((bits >> 31) == 0) ? 1 : -1; * int e = ((bits >> 23) & 0xff); * int m = (e == 0) ? * (bits & 0x7fffff) << 1 : * (bits & 0x7fffff) | 0x800000; * }</pre></blockquote> * * Then the floating-point result equals the value of the mathematical * expression <i>s</i>&middot;<i>m</i>&middot;2<sup><i>e</i>-150</sup>. * * <p>Note that this method may not be able to return a * {@code float} NaN with exactly same bit pattern as the * {@code int} argument. IEEE 754 distinguishes between two * kinds of NaNs, quiet NaNs and <i>signaling NaNs</i>. The * differences between the two kinds of NaN are generally not * visible in Java. Arithmetic operations on signaling NaNs turn * them into quiet NaNs with a different, but often similar, bit * pattern. However, on some processors merely copying a * signaling NaN also performs that conversion. In particular, * copying a signaling NaN to return it to the calling method may * perform this conversion. So {@code intBitsToFloat} may * not be able to return a {@code float} with a signaling NaN * bit pattern. Consequently, for some {@code int} values, * {@code floatToRawIntBits(intBitsToFloat(start))} may * <i>not</i> equal {@code start}. Moreover, which * particular bit patterns represent signaling NaNs is platform * dependent; although all NaN bit patterns, quiet or signaling, * must be in the NaN range identified above. * * @param bits an integer. * @return the {@code float} floating-point value with the same bit * pattern. */ public static native float intBitsToFloat(int bits); /** * Compares two {@code Float} objects numerically. There are * two ways in which comparisons performed by this method differ * from those performed by the Java language numerical comparison * operators ({@code <, <=, ==, >=, >}) when * applied to primitive {@code float} values: * * <ul><li> * {@code Float.NaN} is considered by this method to * be equal to itself and greater than all other * {@code float} values * (including {@code Float.POSITIVE_INFINITY}). * <li> * {@code 0.0f} is considered by this method to be greater * than {@code -0.0f}. * </ul> * * This ensures that the <i>natural ordering</i> of {@code Float} * objects imposed by this method is <i>consistent with equals</i>. * * @param anotherFloat the {@code Float} to be compared. * @return the value {@code 0} if {@code anotherFloat} is * numerically equal to this {@code Float}; a value * less than {@code 0} if this {@code Float} * is numerically less than {@code anotherFloat}; * and a value greater than {@code 0} if this * {@code Float} is numerically greater than * {@code anotherFloat}. * * @since 1.2 * @see Comparable#compareTo(Object) */ public int compareTo(Float anotherFloat) { return Float.compare(value, anotherFloat.value); } /** * Compares the two specified {@code float} values. The sign * of the integer value returned is the same as that of the * integer that would be returned by the call: * <pre> * new Float(f1).compareTo(new Float(f2)) * </pre> * * @param f1 the first {@code float} to compare. * @param f2 the second {@code float} to compare. * @return the value {@code 0} if {@code f1} is * numerically equal to {@code f2}; a value less than * {@code 0} if {@code f1} is numerically less than * {@code f2}; and a value greater than {@code 0} * if {@code f1} is numerically greater than * {@code f2}. * @since 1.4 */ public static int compare(float f1, float f2) { if (f1 < f2) return -1; // Neither val is NaN, thisVal is smaller if (f1 > f2) return 1; // Neither val is NaN, thisVal is larger // Cannot use floatToRawIntBits because of possibility of NaNs. int thisBits = Float.floatToIntBits(f1); int anotherBits = Float.floatToIntBits(f2); return (thisBits == anotherBits ? 0 : // Values are equal (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1)); // (0.0, -0.0) or (NaN, !NaN) } /** * Adds two {@code float} values together as per the + operator. * * @param a the first operand * @param b the second operand * @return the sum of {@code a} and {@code b} * @jls 4.2.4 Floating-Point Operations * @see java.util.function.BinaryOperator * @since 1.8 */ public static float sum(float a, float b) { return a + b; } /** * Returns the greater of two {@code float} values * as if by calling {@link Math#max(float, float) Math.max}. * * @param a the first operand * @param b the second operand * @return the greater of {@code a} and {@code b} * @see java.util.function.BinaryOperator * @since 1.8 */ public static float max(float a, float b) { return Math.max(a, b); } /** * Returns the smaller of two {@code float} values * as if by calling {@link Math#min(float, float) Math.min}. * * @param a the first operand * @param b the second operand * @return the smaller of {@code a} and {@code b} * @see java.util.function.BinaryOperator * @since 1.8 */ public static float min(float a, float b) { return Math.min(a, b); } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -2671257302660747028L; }
apache/phoenix
37,837
phoenix-core-client/src/main/java/org/apache/phoenix/expression/util/bson/UpdateExpressionUtils.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.expression.util.bson; import java.math.BigDecimal; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bson.BsonArray; import org.bson.BsonDecimal128; import org.bson.BsonDocument; import org.bson.BsonDouble; import org.bson.BsonInt32; import org.bson.BsonInt64; import org.bson.BsonNumber; import org.bson.BsonString; import org.bson.BsonValue; import org.bson.types.Decimal128; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * BSON Update Expression Utility to perform the Document updates. All update expressions provided * by this utility supports operations on nested document fields. The field key can represent any * top level or nested fields within the document. The caller should use "." notation for accessing * nested document elements and "[n]" notation for accessing nested array elements. Top level fields * do not require any additional character. */ public class UpdateExpressionUtils { private static final Logger LOGGER = LoggerFactory.getLogger(UpdateExpressionUtils.class); private static final String INVALID_UPDATE_PATH_MESSAGE = "The document path provided in the update expression is invalid for update"; /** * Update operator enum values. Any new update operator that requires update to deeply nested * structures (nested documents or nested arrays), need to have its own type added here. */ private enum UpdateOp { SET, UNSET, ADD, DELETE_FROM_SET } /** * Updates the given document based on the update expression. * <p/> * { "$SET": { &lt;field1&gt;: &lt;value1>, &lt;field2&gt;: &lt;value2&gt;, .... }, "$UNSET": { * &lt;field1&gt;: null, &lt;field2&gt;: null, ... }, "$ADD": { &lt;field1&gt;: &lt;value1&gt;, * &lt;field2&gt;: &lt;value2&gt;, .... }, "$DELETE_FROM_SET": { &lt;field1&gt;: &lt;value1&gt;, * &lt;field2&gt;: &lt;value2&gt;, .... } } * <p/> * "$SET": Use the SET action in an update expression to add one or more fields to a BSON * Document. If any of these fields already exists, they are overwritten by the new values. To * perform multiple SET actions, provide multiple fields key-value entries within the nested * document under $SET field key. "$UNSET": Use the UNSET action in an update expression to unset * or remove one or more fields from a BSON Document. To perform multiple UNSET actions, provide * multiple field key-value entries within the nested document under $UNSET field key. "$ADD": Use * the ADD action in an update expression to add a new field and its values to a BSON document. If * the field already exists, the behavior of ADD depends on the field's data type: * <p/> * 1. If the field is a number, and the value you are adding is also a number, the value is * mathematically added to the existing field. * <p/> * 2. If the field is a set, and the value you are adding is also a set, the value is appended to * the existing set. * <p/> * "$DELETE_FROM_SET": Use the DELETE action in an update expression to remove one or more * elements from a set. To perform multiple DELETE actions, provide multiple field key-value * entries within the nested document under $DELETE_FROM_SET field key. Definition of path and * subset in the context of the expression: * <p/> * 1. The path element is the document path to a field. The field must be a set data type. 2. The * subset is one or more elements that you want to delete from the given path. Subset must be of * set type. * <p/> * @param updateExpression Update Expression as a document. * @param bsonDocument Document contents to be updated. */ public static void updateExpression(final BsonDocument updateExpression, final BsonDocument bsonDocument) { LOGGER.info("Update Expression: {} , current bsonDocument: {}", updateExpression, bsonDocument); if (updateExpression.containsKey("$SET")) { executeSetExpression((BsonDocument) updateExpression.get("$SET"), bsonDocument); } if (updateExpression.containsKey("$UNSET")) { executeRemoveExpression((BsonDocument) updateExpression.get("$UNSET"), bsonDocument); } if (updateExpression.containsKey("$ADD")) { executeAddExpression((BsonDocument) updateExpression.get("$ADD"), bsonDocument); } if (updateExpression.containsKey("$DELETE_FROM_SET")) { executeDeleteExpression((BsonDocument) updateExpression.get("$DELETE_FROM_SET"), bsonDocument); } } /** * Update the given document by performing DELETE operation. This operation is applicable only on * Set data structure. The document is updated by removing the given set of elements from the * given set of elements. Let's say if the document field is of string set data type, and the * elements are: {"yellow", "green", "red", "blue"}. The elements to be removed from the set are * provided as {"blue", "yellow"} with the delete expression. The operation is expected to update * the existing field by removing "blue" and "yellow" from the given set and the resultant set is * expected to contain: {"green", "red"}. * @param deleteExpr Delete Expression Document with key-value pairs. Key represents field in * the given document, on which operation is to be performed. Value represents * set of elements to be removed from the existing set. * @param bsonDocument Document contents to be updated. */ private static void executeDeleteExpression(final BsonDocument deleteExpr, final BsonDocument bsonDocument) { for (Map.Entry<String, BsonValue> deleteEntry : deleteExpr.entrySet()) { String fieldKey = deleteEntry.getKey(); BsonValue newVal = deleteEntry.getValue(); BsonValue topLevelValue = bsonDocument.get(fieldKey); if (!CommonComparisonExpressionUtils.isBsonSet(newVal)) { throw new RuntimeException("Type of new value to be removed should be sets only"); } // If the top level field exists, perform the operation here and return. if (topLevelValue != null) { BsonValue value = modifyFieldValueByDeleteFromSet(topLevelValue, newVal); if (value == null) { bsonDocument.remove(fieldKey); } else { bsonDocument.put(fieldKey, value); } } else if (!fieldKey.contains(".") && !fieldKey.contains("[")) { LOGGER.info("Nothing to be removed as field with key {} does not exist", fieldKey); } else { // If the top level field does not exist and the field key contains "." or "[]" notations // for nested document or nested array, use the self-recursive function to go through // the document tree, one level at a time. updateNestedField(bsonDocument, 0, fieldKey, newVal, UpdateOp.DELETE_FROM_SET); } } } /** * Update the existing set by removing the set values that are present in * {@code setValuesToDelete}. For this operation to be successful, both {@code currentValue} and * {@code setValuesToDelete} must be of same set data type. For instance, both must be either set * of string, set of numbers or set of binary values. * @param currentValue The value that needs to be updated by performing deletion operation. * @param setValuesToDelete The set values that need to be deleted from the currentValue set. * @return Updated set after performing the set difference operation. */ private static BsonValue modifyFieldValueByDeleteFromSet(final BsonValue currentValue, final BsonValue setValuesToDelete) { if (areBsonSetOfSameType(currentValue, setValuesToDelete)) { Set<BsonValue> set1 = new HashSet<>(((BsonArray) ((BsonDocument) currentValue).get("$set")).getValues()); Set<BsonValue> set2 = new HashSet<>(((BsonArray) ((BsonDocument) setValuesToDelete).get("$set")).getValues()); set1.removeAll(set2); if (set1.isEmpty()) { return null; } BsonDocument bsonDocument = new BsonDocument(); bsonDocument.put("$set", new BsonArray(new ArrayList<>(set1))); return bsonDocument; } // Current value exists but is not a set, or is set of different type throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } /** * Update the given document by performing ADD operation. This operation is applicable only on * either Set data structure or Numerical value represented by Int32, Int64, Double or Decimal. If * the field is of type set, the document is updated by adding the given set of elements to the * given set of elements. If the field is of type number, the document is updated by adding the * numerical value to the given number field value. * </p> * Let's say if the document field is of numeric data type with value "234.5" and the value to be * added is "10", the resultant value is expected to be "244.5". Adding negative value would * result in subtract operation. For example, adding "-10" would result in "224.5". * </p> * On the other hand, if the document field is of string set data type, and the elements are: * {"yellow", "green", "red"}. The elements to be added to the set are provided as {"blue", * "yellow"} with the add expression. The operation is expected to update the existing field by * removing adding unique value "blue" and the resultant set is expected to contain: {"yellow", * "green", "red", "blue"}. * @param addExpr Add Expression Document * @param bsonDocument Document contents to be updated. */ private static void executeAddExpression(final BsonDocument addExpr, final BsonDocument bsonDocument) { for (Map.Entry<String, BsonValue> addEntry : addExpr.entrySet()) { String fieldKey = addEntry.getKey(); BsonValue newVal = addEntry.getValue(); BsonValue topLevelValue = bsonDocument.get(fieldKey); if ( !newVal.isNumber() && !newVal.isDecimal128() && !CommonComparisonExpressionUtils.isBsonSet(newVal) ) { throw new RuntimeException( "Type of new value to be updated should be either number or sets only"); } // If the top level field exists, perform the operation here and return. if (topLevelValue != null) { if ( !topLevelValue.isNumber() && !topLevelValue.isDecimal128() && !CommonComparisonExpressionUtils.isBsonSet(topLevelValue) ) { // Current value exists but is not a number or set throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } bsonDocument.put(fieldKey, modifyFieldValueByAdd(topLevelValue, newVal)); } else if (!fieldKey.contains(".") && !fieldKey.contains("[")) { bsonDocument.put(fieldKey, newVal); } else { // If the top level field does not exist and the field key contains "." or "[]" notations // for nested document or nested array, use the self-recursive function to go through // the document tree, one level at a time. updateNestedField(bsonDocument, 0, fieldKey, newVal, UpdateOp.ADD); } } } /** * Update the existing value {@code currentValue} depending on its data type. If the data type of * {@code currentValue} is numeric, add numeric value represented by {@code newVal} to it. If the * data type of {@code currentValue} is set, add set values represented by {@code newVal} to it. * For this operation to be successful, both {@code currentValue} and {@code newVal} must be of * same set data type. For instance, both must be either set of string, set of numbers or set of * binary values, or both must be of number data type. * @param currentValue The value that needs to be updated by performing add operation. * @param newVal The numeric or set values that need to be added to the currentValue. * @return Updated value after performing the add operation. */ private static BsonValue modifyFieldValueByAdd(final BsonValue currentValue, final BsonValue newVal) { if ( (currentValue.isNumber() || currentValue.isDecimal128()) && (newVal.isNumber() || newVal.isDecimal128()) ) { Number num1 = getNumberFromBsonNumber((BsonNumber) currentValue); Number num2 = getNumberFromBsonNumber((BsonNumber) newVal); Number newNum = addNum(num1, num2); return getBsonNumberFromNumber(newNum); } else if (areBsonSetOfSameType(currentValue, newVal)) { Set<BsonValue> set1 = new HashSet<>(((BsonArray) ((BsonDocument) currentValue).get("$set")).getValues()); Set<BsonValue> set2 = new HashSet<>(((BsonArray) ((BsonDocument) newVal).get("$set")).getValues()); set1.addAll(set2); BsonDocument bsonDocument = new BsonDocument(); bsonDocument.put("$set", new BsonArray(new ArrayList<>(set1))); return bsonDocument; } // Current value exists but is not a number or set, or is set of different type throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } /** * Update the given document by performing UNSET operation on one or more fields. This operation * is applicable to any field of the document at any level of the hierarchy. If the field exists, * it will be deleted. * @param unsetExpr Unset Expression Document. * @param bsonDocument Document contents to be updated. */ private static void executeRemoveExpression(final BsonDocument unsetExpr, final BsonDocument bsonDocument) { for (Map.Entry<String, BsonValue> removeField : unsetExpr.entrySet()) { String fieldKey = removeField.getKey(); BsonValue topLevelValue = bsonDocument.get(fieldKey); // If the top level field exists, perform the operation here and return. if (topLevelValue != null || (!fieldKey.contains(".") && !fieldKey.contains("["))) { bsonDocument.remove(fieldKey); } else { // If the top level field does not exist and the field key contains "." or "[]" notations // for nested document or nested array, use the self-recursive function to go through // the document tree, one level at a time. updateNestedField(bsonDocument, 0, fieldKey, null, UpdateOp.UNSET); } } } /** * Update the given document by performing SET operation on a given field. This operation is * applicable to any field of the document. The SET operation represents either adding a new field * with the given value of updating the existing field with new value provided by the SET * Expression Document. * @param setExpression SET Expression Document. * @param bsonDocument Document contents to be updated. */ private static void executeSetExpression(final BsonDocument setExpression, final BsonDocument bsonDocument) { for (Map.Entry<String, BsonValue> setEntry : setExpression.entrySet()) { String fieldKey = setEntry.getKey(); BsonValue fieldVal = setEntry.getValue(); BsonValue topLevelValue = bsonDocument.get(fieldKey); BsonValue newVal = getNewFieldValue(fieldVal, bsonDocument); // If the top level field exists, perform the operation here and return. if (topLevelValue != null || (!fieldKey.contains(".") && !fieldKey.contains("["))) { bsonDocument.put(fieldKey, newVal); } else { // If the top level field does not exist and the field key contains "." or "[]" notations // for nested document or nested array, use the self-recursive function to go through // the document tree, one level at a time. updateNestedField(bsonDocument, 0, fieldKey, newVal, UpdateOp.SET); } } } /** * Update the nested field with the given update operation. The update operation is determined by * the enum value {@code updateOp}. The field key is expected to contain "." and/or "[]" notations * for nested documents and/or nested array elements. This function keeps recursively calling * itself until it reaches the leaf node in the given tree. For instance, for field key * "category.subcategories.brands[5]", first the function evaluates and retrieves the value for * top-level field "category". The value of "category" is expected to be nested document. First * function call has value as full document, it retries nested document under "category" field and * calls the function recursively with index value same as index value of first "." (dot) in the * field key. For field key "category.subcategories.brands[5]", the index value would be 8. The * second function call retrieves value of field key "subcategories", which is expected to be * nested document. The third function call gets this nested document as BsonValue and index value * as 22 as the field key has second "." (dot) notation at index 22. The third function call * searches for field key "brands" and expects its value as nested array. The forth function call * gets this nested array as BsonValue and index 29 as the field key has "[]" array notation * starting at index 29. The forth function call retrieves value of nested array element at index * 5. As the function is at leaf node in the tree, now it performs the update operation as per the * given update operator ($SET / $UNSET / $ADD / $DELETE_FROM_SET) semantics. * @param value Bson value at the given level of the document hierarchy. * @param idx The index value for the given field key. The function is expected to retrieve * the value of the nested document or array at the given level of the tree. * @param fieldKey The full field key. * @param newVal The new Bson value to be added to the given nested document or a particular * index of the given nested array. * @param updateOp The enum value representing the update operation to perform. */ private static void updateNestedField(final BsonValue value, final int idx, final String fieldKey, final BsonValue newVal, final UpdateOp updateOp) { int curIdx = idx; if (fieldKey.charAt(curIdx) == '.') { if (value == null || !value.isDocument()) { LOGGER.error("Value is null or not document. Value: {}, Idx: {}, fieldKey: {}, New val: {}," + " Update op: {}", value, idx, fieldKey, newVal, updateOp); throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } BsonDocument nestedDocument = (BsonDocument) value; curIdx++; StringBuilder sb = new StringBuilder(); for (; curIdx < fieldKey.length(); curIdx++) { if (fieldKey.charAt(curIdx) == '.' || fieldKey.charAt(curIdx) == '[') { BsonValue nestedValue = nestedDocument.get(sb.toString()); if (nestedValue == null) { LOGGER.error("Should have found nested map for {}", sb); throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } updateNestedField(nestedValue, curIdx, fieldKey, newVal, updateOp); return; } else { sb.append(fieldKey.charAt(curIdx)); } } // reached leaf node of the document tree, update the value as per the update operator // semantics updateDocumentAtLeafNode(newVal, updateOp, nestedDocument, sb); } else if (fieldKey.charAt(curIdx) == '[') { curIdx++; StringBuilder arrayIdxStr = new StringBuilder(); while (fieldKey.charAt(curIdx) != ']') { arrayIdxStr.append(fieldKey.charAt(curIdx)); curIdx++; } curIdx++; int arrayIdx = Integer.parseInt(arrayIdxStr.toString()); if (value == null || !value.isArray()) { LOGGER.error("Value is null or not document. Value: {}, Idx: {}, fieldKey: {}, New val: {}", value, idx, fieldKey, newVal); throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } BsonArray nestedArray = (BsonArray) value; if (curIdx == fieldKey.length()) { // reached leaf node of the document tree, update the value as per the update operator // semantics updateArrayAtLeafNode(fieldKey, newVal, updateOp, arrayIdx, nestedArray); return; } BsonValue nestedValue = nestedArray.get(arrayIdx); if (nestedValue == null) { LOGGER.error("Should have found nested list for index {}", arrayIdx); return; } updateNestedField(nestedValue, curIdx, fieldKey, newVal, updateOp); } else { StringBuilder sb = new StringBuilder(); for (int i = idx; i < fieldKey.length(); i++) { if (fieldKey.charAt(i) == '.') { BsonValue topFieldValue = ((BsonDocument) value).get(sb.toString()); if (topFieldValue == null) { // Missing parent document - throw exception for all operations throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } updateNestedField(topFieldValue, i, fieldKey, newVal, updateOp); return; } else if (fieldKey.charAt(i) == '[') { BsonValue topFieldValue = ((BsonDocument) value).get(sb.toString()); if (topFieldValue == null) { // Parent array is missing throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } updateNestedField(topFieldValue, i, fieldKey, newVal, updateOp); return; } else { sb.append(fieldKey.charAt(i)); } } } } /** * Perform update operation at the leaf node. This method is called only when the leaf node or the * target node for the given field key is encountered while iterating through the tree structure. * This is specifically called when the closest ancestor of the given node is a nested array. The * leaf node is for the field key. For example, for "category.subcategories", the leaf node is * "subcategories" whereas for "category.subcategories.brands[2]", the leaf node is "brands". * @param fieldKey The full field key. * @param newVal New value to be used while performing update operation on the existing node. * @param updateOp Type of the update operation to be performed. * @param arrayIdx The index of the array at which the target node value is to be updated. * @param nestedArray The parent or ancestor node, expected to be nested array only. For example, * for "category.subcategories.brands[5]" field key, the nestedArray is * expected to be "brands" array and arrayIdx is expected to be 5. */ private static void updateArrayAtLeafNode(final String fieldKey, final BsonValue newVal, final UpdateOp updateOp, final int arrayIdx, final BsonArray nestedArray) { switch (updateOp) { case SET: { if (arrayIdx >= nestedArray.size()) { // Appending to the end of the array nestedArray.add(newVal); } else { // Setting existing element nestedArray.set(arrayIdx, newVal); } break; } case UNSET: { if (arrayIdx < nestedArray.size()) { nestedArray.remove(arrayIdx); } break; } case ADD: { if (arrayIdx < nestedArray.size()) { BsonValue currentValue = nestedArray.get(arrayIdx); if (currentValue != null) { // Validate ADD operation against existing array element if ( !currentValue.isNumber() && !currentValue.isDecimal128() && !CommonComparisonExpressionUtils.isBsonSet(currentValue) ) { // Current value exists but is not a number or set throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } nestedArray.set(arrayIdx, modifyFieldValueByAdd(currentValue, newVal)); } else { // For null array element, just set the value directly nestedArray.set(arrayIdx, newVal); } } else { // For ADD beyond array size, just set the value directly (no initialization logic) nestedArray.add(newVal); } break; } case DELETE_FROM_SET: { if (arrayIdx < nestedArray.size()) { BsonValue currentValue = nestedArray.get(arrayIdx); if (currentValue != null) { BsonValue modifiedVal = modifyFieldValueByDeleteFromSet(currentValue, newVal); if (modifiedVal == null) { nestedArray.remove(arrayIdx); } else { nestedArray.set(arrayIdx, modifiedVal); } } else { LOGGER.info("Nothing to be removed as nested list does not have value for field {}. " + "Update operator: {}", fieldKey, updateOp); } } break; } } } /** * Perform update operation at the leaf node. This method is called only when the leaf node or the * target node for the given field key is encountered while iterating through the tree structure. * This is specifically called when the closest ancestor of the given node is a nested document. * The leaf node is for the field key. For example, for "category.subcategories", the leaf node is * "subcategories" whereas for "category.subcategories.brands[2]", the leaf node is "brands". * @param newVal New value to be used while performing update operation on the * existing node. * @param updateOp Type of the update operation to be performed. * @param nestedDocument The parent or ancestor node, expected to be nested document only. * @param targetNodeFieldKey The target fieldKey value. For example, for "category.subcategories" * field key, the target node field key is expected to be * "subcategories" and the nestedDocument is expected to be "category" * document. */ private static void updateDocumentAtLeafNode(BsonValue newVal, UpdateOp updateOp, BsonDocument nestedDocument, StringBuilder targetNodeFieldKey) { switch (updateOp) { case SET: { nestedDocument.put(targetNodeFieldKey.toString(), newVal); break; } case UNSET: { nestedDocument.remove(targetNodeFieldKey.toString()); break; } case ADD: { BsonValue currentValue = nestedDocument.get(targetNodeFieldKey.toString()); if (currentValue != null) { // Validate ADD operation against existing value if ( !currentValue.isNumber() && !currentValue.isDecimal128() && !CommonComparisonExpressionUtils.isBsonSet(currentValue) ) { // Current value exists but is not a number or set throw new BsonUpdateInvalidArgumentException(INVALID_UPDATE_PATH_MESSAGE); } nestedDocument.put(targetNodeFieldKey.toString(), modifyFieldValueByAdd(currentValue, newVal)); } else { // For missing field, just set the value directly nestedDocument.put(targetNodeFieldKey.toString(), newVal); } break; } case DELETE_FROM_SET: { BsonValue currentValue = nestedDocument.get(targetNodeFieldKey.toString()); if (currentValue != null) { BsonValue modifiedVal = modifyFieldValueByDeleteFromSet(currentValue, newVal); if (modifiedVal == null) { nestedDocument.remove(targetNodeFieldKey.toString()); } else { nestedDocument.put(targetNodeFieldKey.toString(), modifiedVal); } } else { LOGGER.info( "Nothing to be removed as field with key {} does not exist. Update operator: {}", targetNodeFieldKey, updateOp); } break; } } } /** * Retrieve the value to be updated for the given current value. If the current value does not * contain any arithmetic operators, the current value is returned without any modifications. If * the current value contains arithmetic expressions like "a + b" or "a - b", the values of * operands are retrieved from the given document and if the values are numeric, the given * arithmetic operation is performed. If the current value is a bson document with an entry from * $IF_NOT_EXISTS to a document with a key and a fallback value, we lookup if the key is already * present in the document. If it is, we return its value. Otherwise, we return the provided * fallback value. * @param curValue The current value. * @param bsonDocument The document with all field key-value pairs. * @return Updated values to be used by SET operation. */ private static BsonValue getNewFieldValue(final BsonValue curValue, final BsonDocument bsonDocument) { if ( curValue != null && curValue.isString() && (((BsonString) curValue).getValue().contains(" + ") || ((BsonString) curValue).getValue().contains(" - ")) ) { String[] tokens = ((BsonString) curValue).getValue().split("\\s+"); boolean addNum = true; // Pattern pattern = Pattern.compile(":?[a-zA-Z0-9]+"); Pattern pattern = Pattern.compile("[#:$]?[^\\s\\n]+"); Number newNum = null; for (String token : tokens) { if (token.equals("+")) { addNum = true; continue; } else if (token.equals("-")) { addNum = false; continue; } Matcher matcher = pattern.matcher(token); if (matcher.find()) { String operand = matcher.group(); Number literalNum; BsonValue topLevelValue = bsonDocument.get(operand); BsonValue bsonValue = topLevelValue != null ? topLevelValue : CommonComparisonExpressionUtils.getFieldFromDocument(operand, bsonDocument); if (bsonValue == null && (literalNum = stringToNumber(operand)) != null) { Number val = literalNum; newNum = newNum == null ? val : (addNum ? addNum(newNum, val) : subtractNum(newNum, val)); } else { if (bsonValue == null) { throw new IllegalArgumentException("Operand " + operand + " does not exist"); } if (!bsonValue.isNumber() && !bsonValue.isDecimal128()) { throw new IllegalArgumentException( "Operand " + operand + " is not provided as number type"); } Number val = getNumberFromBsonNumber((BsonNumber) bsonValue); newNum = newNum == null ? val : (addNum ? addNum(newNum, val) : subtractNum(newNum, val)); } } } return getBsonNumberFromNumber(newNum); } else if ( curValue instanceof BsonDocument && ((BsonDocument) curValue).get("$IF_NOT_EXISTS") != null ) { BsonValue ifNotExistsDoc = ((BsonDocument) curValue).get("$IF_NOT_EXISTS"); Map.Entry<String, BsonValue> ifNotExistsEntry = ((BsonDocument) ifNotExistsDoc).entrySet().iterator().next(); String ifNotExistsKey = ifNotExistsEntry.getKey(); BsonValue ifNotExistsVal = ifNotExistsEntry.getValue(); BsonValue val = CommonComparisonExpressionUtils.getFieldFromDocument(ifNotExistsKey, bsonDocument); return (val != null) ? val : ifNotExistsVal; } return curValue; } /** * Performs arithmetic addition operation on the given numeric operands. * @param num1 First number. * @param num2 Second number. * @return The value as addition of both numbers. */ private static Number addNum(final Number num1, final Number num2) { if (num1 instanceof Double || num2 instanceof Double) { return num1.doubleValue() + num2.doubleValue(); } else if (num1 instanceof Float || num2 instanceof Float) { return num1.floatValue() + num2.floatValue(); } else if (num1 instanceof Long || num2 instanceof Long) { return num1.longValue() + num2.longValue(); } else { return num1.intValue() + num2.intValue(); } } /** * Performs arithmetic subtraction operation on the given numeric operands. * @param num1 First number. * @param num2 Second number. * @return The subtracted value as first number minus second number. */ private static Number subtractNum(final Number num1, final Number num2) { if (num1 instanceof Double || num2 instanceof Double) { return num1.doubleValue() - num2.doubleValue(); } else if (num1 instanceof Float || num2 instanceof Float) { return num1.floatValue() - num2.floatValue(); } else if (num1 instanceof Long || num2 instanceof Long) { return num1.longValue() - num2.longValue(); } else { return num1.intValue() - num2.intValue(); } } /** * Convert the given Number to String. * @param number The Number object. * @return String represented number value. */ private static String numberToString(Number number) { if (number instanceof Integer || number instanceof Short || number instanceof Byte) { return Integer.toString(number.intValue()); } else if (number instanceof Long) { return Long.toString(number.longValue()); } else if (number instanceof Double) { return Double.toString(number.doubleValue()); } else if (number instanceof Float) { return Float.toString(number.floatValue()); } throw new RuntimeException("Number type is not known for number: " + number); } /** * Convert the given String to Number. * @param number The String represented numeric value. * @return The Number object. */ private static Number stringToNumber(String number) { try { return Integer.parseInt(number); } catch (NumberFormatException e) { // no-op } try { return Long.parseLong(number); } catch (NumberFormatException e) { // no-op } try { return Double.parseDouble(number); } catch (NumberFormatException e) { // no-op } try { return NumberFormat.getInstance().parse(number); } catch (ParseException e) { return null; } } /** * Convert Number to BsonNumber. * @param number The Number object. * @return The BsonNumber object. */ private static BsonNumber getBsonNumberFromNumber(Number number) { BsonNumber bsonNumber; if (number instanceof Integer || number instanceof Short || number instanceof Byte) { bsonNumber = new BsonInt32(number.intValue()); } else if (number instanceof Long) { bsonNumber = new BsonInt64(number.longValue()); } else if (number instanceof Double || number instanceof Float) { bsonNumber = new BsonDouble(number.doubleValue()); } else if (number instanceof BigDecimal) { bsonNumber = new BsonDecimal128(new Decimal128((BigDecimal) number)); } else { throw new IllegalArgumentException("Unsupported Number type: " + number.getClass()); } return bsonNumber; } /** * Convert BsonNumber to Number. * @param bsonNumber The BsonNumber object. * @return The Number object. */ public static Number getNumberFromBsonNumber(BsonNumber bsonNumber) { if (bsonNumber instanceof BsonInt32) { return ((BsonInt32) bsonNumber).getValue(); } else if (bsonNumber instanceof BsonInt64) { return ((BsonInt64) bsonNumber).getValue(); } else if (bsonNumber instanceof BsonDouble) { return ((BsonDouble) bsonNumber).getValue(); } else if (bsonNumber instanceof BsonDecimal128) { return ((BsonDecimal128) bsonNumber).getValue().bigDecimalValue(); } else { throw new IllegalArgumentException("Unsupported BsonNumber type: " + bsonNumber.getClass()); } } /** * Returns true if both values represent Set data structure and the contents of the Set are of * same type. * @param bsonValue1 First value. * @param bsonValue2 Second value. * @return True if both values represent Set data structure and the contents of the Set are of * same type. */ private static boolean areBsonSetOfSameType(final BsonValue bsonValue1, final BsonValue bsonValue2) { if ( !CommonComparisonExpressionUtils.isBsonSet(bsonValue1) || !CommonComparisonExpressionUtils.isBsonSet(bsonValue2) ) { return false; } BsonArray bsonArray1 = (BsonArray) ((BsonDocument) bsonValue1).get("$set"); BsonArray bsonArray2 = (BsonArray) ((BsonDocument) bsonValue2).get("$set"); // Handle empty sets - they are compatible with any set if (bsonArray1.isEmpty() || bsonArray2.isEmpty()) { return true; } return bsonArray1.get(0).getBsonType().equals(bsonArray2.get(0).getBsonType()); } }
googleapis/google-api-java-client-services
37,693
clients/google-api-services-appengine/v1beta/1.31.0/com/google/api/services/appengine/model/Version.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.appengine.model; /** * A Version resource is a specific set of source code and configuration files that are deployed * into a service. * * <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 App Engine Admin 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 Version extends com.google.api.client.json.GenericJson { /** * Serving configuration for Google Cloud Endpoints * (https://cloud.google.com/appengine/docs/python/endpoints/).Only returned in GET requests if * view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private ApiConfigHandler apiConfig; /** * Allows App Engine second generation runtimes to access the legacy bundled services. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean appEngineApis; /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Instances are dynamically created and destroyed as needed in order to handle traffic. * The value may be {@code null}. */ @com.google.api.client.util.Key private AutomaticScaling automaticScaling; /** * A service with basic scaling will create an instance when the application receives a request. * The instance will be turned down when the app becomes idle. Basic scaling is ideal for work * that is intermittent or driven by user activity. * The value may be {@code null}. */ @com.google.api.client.util.Key private BasicScaling basicScaling; /** * Metadata settings that are supplied to this version to enable beta runtime features. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> betaSettings; /** * Environment variables available to the build environment.Only returned in GET requests if * view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> buildEnvVariables; /** * Time that this version was created.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private String createTime; /** * Email address of the user who created this version.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String createdBy; /** * Duration that static files should be cached by web proxies and browsers. Only applicable if the * corresponding StaticFilesHandler (https://cloud.google.com/appengine/docs/admin- * api/reference/rest/v1beta/apps.services.versions#StaticFilesHandler) does not specify its own * expiration time.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private String defaultExpiration; /** * Code and application artifacts that make up this version.Only returned in GET requests if * view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private Deployment deployment; /** * Total size in bytes of all the files that are included in this version and currently hosted on * the App Engine disk.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long diskUsageBytes; /** * Cloud Endpoints configuration.If endpoints_api_service is set, the Cloud Endpoints Extensible * Service Proxy will be provided to serve the API implemented by the app. * The value may be {@code null}. */ @com.google.api.client.util.Key private EndpointsApiService endpointsApiService; /** * The entrypoint for the application. * The value may be {@code null}. */ @com.google.api.client.util.Key private Entrypoint entrypoint; /** * App Engine execution environment for this version.Defaults to standard. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String env; /** * Environment variables available to the application.Only returned in GET requests if view=FULL * is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.Map<String, java.lang.String> envVariables; /** * Custom static error pages. Limited to 10KB per page.Only returned in GET requests if view=FULL * is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<ErrorHandler> errorHandlers; static { // hack to force ProGuard to consider ErrorHandler used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(ErrorHandler.class); } /** * An ordered list of URL-matching patterns that should be applied to incoming requests. The first * matching URL handles the request and other request handlers are not attempted.Only returned in * GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<UrlMap> handlers; static { // hack to force ProGuard to consider UrlMap used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(UrlMap.class); } /** * Configures health checking for instances. Unhealthy instances are stopped and replaced with new * instances. Only applicable in the App Engine flexible environment.Only returned in GET requests * if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private HealthCheck healthCheck; /** * Relative name of the version within the service. Example: v1. Version names can contain only * lowercase letters, numbers, or hyphens. Reserved names: "default", "latest", and any name with * the prefix "ah-". * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * Before an application can receive email or XMPP messages, the application must be configured to * enable the service. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> inboundServices; /** * Instance class that is used to run this version. Valid values are: AutomaticScaling: F1, F2, * F4, F4_1G ManualScaling or BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for * AutomaticScaling and B1 for ManualScaling or BasicScaling. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String instanceClass; /** * Configuration for third-party Python runtime libraries that are required by the * application.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Library> libraries; static { // hack to force ProGuard to consider Library used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Library.class); } /** * Configures liveness health checking for instances. Unhealthy instances are stopped and replaced * with new instancesOnly returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private LivenessCheck livenessCheck; /** * A service with manual scaling runs continuously, allowing you to perform complex initialization * and rely on the state of its memory over time. Manually scaled versions are sometimes referred * to as "backends". * The value may be {@code null}. */ @com.google.api.client.util.Key private ManualScaling manualScaling; /** * Full path to the Version resource in the API. Example: * apps/myapp/services/default/versions/v1.@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * Extra network settings. Only applicable in the App Engine flexible environment. * The value may be {@code null}. */ @com.google.api.client.util.Key private Network network; /** * Files that match this pattern will not be built into this version. Only applicable for Go * runtimes.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String nobuildFilesRegex; /** * Configures readiness health checking for instances. Unhealthy instances are not put into the * backend traffic rotation.Only returned in GET requests if view=FULL is set. * The value may be {@code null}. */ @com.google.api.client.util.Key private ReadinessCheck readinessCheck; /** * Machine resources for this version. Only applicable in the App Engine flexible environment. * The value may be {@code null}. */ @com.google.api.client.util.Key private Resources resources; /** * Desired runtime. Example: python27. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtime; /** * The version of the API in the given runtime environment. Please see the app.yaml reference for * valid values at https://cloud.google.com/appengine/docs/standard//config/appref * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtimeApiVersion; /** * The channel of the runtime to use. Only available for some runtimes. Defaults to the default * channel. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtimeChannel; /** * The path or name of the app's main executable. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String runtimeMainExecutablePath; /** * The identity that the deployed version will run as. Admin API will use the App Engine Appspot * service account as default if this field is neither provided in app.yaml file nor through CLI * flag. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String serviceAccount; /** * Current serving status of this version. Only the versions with a SERVING status create * instances and can be billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to * SERVING. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String servingStatus; /** * Whether multiple requests can be dispatched to this version at once. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean threadsafe; /** * Serving URL for this version. Example: "https://myversion-dot-myservice-dot- * myapp.appspot.com"@OutputOnly * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String versionUrl; /** * Whether to deploy this version in a container on a virtual machine. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean vm; /** * Enables VPC connectivity for standard apps. * The value may be {@code null}. */ @com.google.api.client.util.Key private VpcAccessConnector vpcAccessConnector; /** * The Google Compute Engine zones that are supported by this version in the App Engine flexible * environment. Deprecated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<java.lang.String> zones; /** * Serving configuration for Google Cloud Endpoints * (https://cloud.google.com/appengine/docs/python/endpoints/).Only returned in GET requests if * view=FULL is set. * @return value or {@code null} for none */ public ApiConfigHandler getApiConfig() { return apiConfig; } /** * Serving configuration for Google Cloud Endpoints * (https://cloud.google.com/appengine/docs/python/endpoints/).Only returned in GET requests if * view=FULL is set. * @param apiConfig apiConfig or {@code null} for none */ public Version setApiConfig(ApiConfigHandler apiConfig) { this.apiConfig = apiConfig; return this; } /** * Allows App Engine second generation runtimes to access the legacy bundled services. * @return value or {@code null} for none */ public java.lang.Boolean getAppEngineApis() { return appEngineApis; } /** * Allows App Engine second generation runtimes to access the legacy bundled services. * @param appEngineApis appEngineApis or {@code null} for none */ public Version setAppEngineApis(java.lang.Boolean appEngineApis) { this.appEngineApis = appEngineApis; return this; } /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Instances are dynamically created and destroyed as needed in order to handle traffic. * @return value or {@code null} for none */ public AutomaticScaling getAutomaticScaling() { return automaticScaling; } /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Instances are dynamically created and destroyed as needed in order to handle traffic. * @param automaticScaling automaticScaling or {@code null} for none */ public Version setAutomaticScaling(AutomaticScaling automaticScaling) { this.automaticScaling = automaticScaling; return this; } /** * A service with basic scaling will create an instance when the application receives a request. * The instance will be turned down when the app becomes idle. Basic scaling is ideal for work * that is intermittent or driven by user activity. * @return value or {@code null} for none */ public BasicScaling getBasicScaling() { return basicScaling; } /** * A service with basic scaling will create an instance when the application receives a request. * The instance will be turned down when the app becomes idle. Basic scaling is ideal for work * that is intermittent or driven by user activity. * @param basicScaling basicScaling or {@code null} for none */ public Version setBasicScaling(BasicScaling basicScaling) { this.basicScaling = basicScaling; return this; } /** * Metadata settings that are supplied to this version to enable beta runtime features. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getBetaSettings() { return betaSettings; } /** * Metadata settings that are supplied to this version to enable beta runtime features. * @param betaSettings betaSettings or {@code null} for none */ public Version setBetaSettings(java.util.Map<String, java.lang.String> betaSettings) { this.betaSettings = betaSettings; return this; } /** * Environment variables available to the build environment.Only returned in GET requests if * view=FULL is set. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getBuildEnvVariables() { return buildEnvVariables; } /** * Environment variables available to the build environment.Only returned in GET requests if * view=FULL is set. * @param buildEnvVariables buildEnvVariables or {@code null} for none */ public Version setBuildEnvVariables(java.util.Map<String, java.lang.String> buildEnvVariables) { this.buildEnvVariables = buildEnvVariables; return this; } /** * Time that this version was created.@OutputOnly * @return value or {@code null} for none */ public String getCreateTime() { return createTime; } /** * Time that this version was created.@OutputOnly * @param createTime createTime or {@code null} for none */ public Version setCreateTime(String createTime) { this.createTime = createTime; return this; } /** * Email address of the user who created this version.@OutputOnly * @return value or {@code null} for none */ public java.lang.String getCreatedBy() { return createdBy; } /** * Email address of the user who created this version.@OutputOnly * @param createdBy createdBy or {@code null} for none */ public Version setCreatedBy(java.lang.String createdBy) { this.createdBy = createdBy; return this; } /** * Duration that static files should be cached by web proxies and browsers. Only applicable if the * corresponding StaticFilesHandler (https://cloud.google.com/appengine/docs/admin- * api/reference/rest/v1beta/apps.services.versions#StaticFilesHandler) does not specify its own * expiration time.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public String getDefaultExpiration() { return defaultExpiration; } /** * Duration that static files should be cached by web proxies and browsers. Only applicable if the * corresponding StaticFilesHandler (https://cloud.google.com/appengine/docs/admin- * api/reference/rest/v1beta/apps.services.versions#StaticFilesHandler) does not specify its own * expiration time.Only returned in GET requests if view=FULL is set. * @param defaultExpiration defaultExpiration or {@code null} for none */ public Version setDefaultExpiration(String defaultExpiration) { this.defaultExpiration = defaultExpiration; return this; } /** * Code and application artifacts that make up this version.Only returned in GET requests if * view=FULL is set. * @return value or {@code null} for none */ public Deployment getDeployment() { return deployment; } /** * Code and application artifacts that make up this version.Only returned in GET requests if * view=FULL is set. * @param deployment deployment or {@code null} for none */ public Version setDeployment(Deployment deployment) { this.deployment = deployment; return this; } /** * Total size in bytes of all the files that are included in this version and currently hosted on * the App Engine disk.@OutputOnly * @return value or {@code null} for none */ public java.lang.Long getDiskUsageBytes() { return diskUsageBytes; } /** * Total size in bytes of all the files that are included in this version and currently hosted on * the App Engine disk.@OutputOnly * @param diskUsageBytes diskUsageBytes or {@code null} for none */ public Version setDiskUsageBytes(java.lang.Long diskUsageBytes) { this.diskUsageBytes = diskUsageBytes; return this; } /** * Cloud Endpoints configuration.If endpoints_api_service is set, the Cloud Endpoints Extensible * Service Proxy will be provided to serve the API implemented by the app. * @return value or {@code null} for none */ public EndpointsApiService getEndpointsApiService() { return endpointsApiService; } /** * Cloud Endpoints configuration.If endpoints_api_service is set, the Cloud Endpoints Extensible * Service Proxy will be provided to serve the API implemented by the app. * @param endpointsApiService endpointsApiService or {@code null} for none */ public Version setEndpointsApiService(EndpointsApiService endpointsApiService) { this.endpointsApiService = endpointsApiService; return this; } /** * The entrypoint for the application. * @return value or {@code null} for none */ public Entrypoint getEntrypoint() { return entrypoint; } /** * The entrypoint for the application. * @param entrypoint entrypoint or {@code null} for none */ public Version setEntrypoint(Entrypoint entrypoint) { this.entrypoint = entrypoint; return this; } /** * App Engine execution environment for this version.Defaults to standard. * @return value or {@code null} for none */ public java.lang.String getEnv() { return env; } /** * App Engine execution environment for this version.Defaults to standard. * @param env env or {@code null} for none */ public Version setEnv(java.lang.String env) { this.env = env; return this; } /** * Environment variables available to the application.Only returned in GET requests if view=FULL * is set. * @return value or {@code null} for none */ public java.util.Map<String, java.lang.String> getEnvVariables() { return envVariables; } /** * Environment variables available to the application.Only returned in GET requests if view=FULL * is set. * @param envVariables envVariables or {@code null} for none */ public Version setEnvVariables(java.util.Map<String, java.lang.String> envVariables) { this.envVariables = envVariables; return this; } /** * Custom static error pages. Limited to 10KB per page.Only returned in GET requests if view=FULL * is set. * @return value or {@code null} for none */ public java.util.List<ErrorHandler> getErrorHandlers() { return errorHandlers; } /** * Custom static error pages. Limited to 10KB per page.Only returned in GET requests if view=FULL * is set. * @param errorHandlers errorHandlers or {@code null} for none */ public Version setErrorHandlers(java.util.List<ErrorHandler> errorHandlers) { this.errorHandlers = errorHandlers; return this; } /** * An ordered list of URL-matching patterns that should be applied to incoming requests. The first * matching URL handles the request and other request handlers are not attempted.Only returned in * GET requests if view=FULL is set. * @return value or {@code null} for none */ public java.util.List<UrlMap> getHandlers() { return handlers; } /** * An ordered list of URL-matching patterns that should be applied to incoming requests. The first * matching URL handles the request and other request handlers are not attempted.Only returned in * GET requests if view=FULL is set. * @param handlers handlers or {@code null} for none */ public Version setHandlers(java.util.List<UrlMap> handlers) { this.handlers = handlers; return this; } /** * Configures health checking for instances. Unhealthy instances are stopped and replaced with new * instances. Only applicable in the App Engine flexible environment.Only returned in GET requests * if view=FULL is set. * @return value or {@code null} for none */ public HealthCheck getHealthCheck() { return healthCheck; } /** * Configures health checking for instances. Unhealthy instances are stopped and replaced with new * instances. Only applicable in the App Engine flexible environment.Only returned in GET requests * if view=FULL is set. * @param healthCheck healthCheck or {@code null} for none */ public Version setHealthCheck(HealthCheck healthCheck) { this.healthCheck = healthCheck; return this; } /** * Relative name of the version within the service. Example: v1. Version names can contain only * lowercase letters, numbers, or hyphens. Reserved names: "default", "latest", and any name with * the prefix "ah-". * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * Relative name of the version within the service. Example: v1. Version names can contain only * lowercase letters, numbers, or hyphens. Reserved names: "default", "latest", and any name with * the prefix "ah-". * @param id id or {@code null} for none */ public Version setId(java.lang.String id) { this.id = id; return this; } /** * Before an application can receive email or XMPP messages, the application must be configured to * enable the service. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getInboundServices() { return inboundServices; } /** * Before an application can receive email or XMPP messages, the application must be configured to * enable the service. * @param inboundServices inboundServices or {@code null} for none */ public Version setInboundServices(java.util.List<java.lang.String> inboundServices) { this.inboundServices = inboundServices; return this; } /** * Instance class that is used to run this version. Valid values are: AutomaticScaling: F1, F2, * F4, F4_1G ManualScaling or BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for * AutomaticScaling and B1 for ManualScaling or BasicScaling. * @return value or {@code null} for none */ public java.lang.String getInstanceClass() { return instanceClass; } /** * Instance class that is used to run this version. Valid values are: AutomaticScaling: F1, F2, * F4, F4_1G ManualScaling or BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for * AutomaticScaling and B1 for ManualScaling or BasicScaling. * @param instanceClass instanceClass or {@code null} for none */ public Version setInstanceClass(java.lang.String instanceClass) { this.instanceClass = instanceClass; return this; } /** * Configuration for third-party Python runtime libraries that are required by the * application.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public java.util.List<Library> getLibraries() { return libraries; } /** * Configuration for third-party Python runtime libraries that are required by the * application.Only returned in GET requests if view=FULL is set. * @param libraries libraries or {@code null} for none */ public Version setLibraries(java.util.List<Library> libraries) { this.libraries = libraries; return this; } /** * Configures liveness health checking for instances. Unhealthy instances are stopped and replaced * with new instancesOnly returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public LivenessCheck getLivenessCheck() { return livenessCheck; } /** * Configures liveness health checking for instances. Unhealthy instances are stopped and replaced * with new instancesOnly returned in GET requests if view=FULL is set. * @param livenessCheck livenessCheck or {@code null} for none */ public Version setLivenessCheck(LivenessCheck livenessCheck) { this.livenessCheck = livenessCheck; return this; } /** * A service with manual scaling runs continuously, allowing you to perform complex initialization * and rely on the state of its memory over time. Manually scaled versions are sometimes referred * to as "backends". * @return value or {@code null} for none */ public ManualScaling getManualScaling() { return manualScaling; } /** * A service with manual scaling runs continuously, allowing you to perform complex initialization * and rely on the state of its memory over time. Manually scaled versions are sometimes referred * to as "backends". * @param manualScaling manualScaling or {@code null} for none */ public Version setManualScaling(ManualScaling manualScaling) { this.manualScaling = manualScaling; return this; } /** * Full path to the Version resource in the API. Example: * apps/myapp/services/default/versions/v1.@OutputOnly * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Full path to the Version resource in the API. Example: * apps/myapp/services/default/versions/v1.@OutputOnly * @param name name or {@code null} for none */ public Version setName(java.lang.String name) { this.name = name; return this; } /** * Extra network settings. Only applicable in the App Engine flexible environment. * @return value or {@code null} for none */ public Network getNetwork() { return network; } /** * Extra network settings. Only applicable in the App Engine flexible environment. * @param network network or {@code null} for none */ public Version setNetwork(Network network) { this.network = network; return this; } /** * Files that match this pattern will not be built into this version. Only applicable for Go * runtimes.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public java.lang.String getNobuildFilesRegex() { return nobuildFilesRegex; } /** * Files that match this pattern will not be built into this version. Only applicable for Go * runtimes.Only returned in GET requests if view=FULL is set. * @param nobuildFilesRegex nobuildFilesRegex or {@code null} for none */ public Version setNobuildFilesRegex(java.lang.String nobuildFilesRegex) { this.nobuildFilesRegex = nobuildFilesRegex; return this; } /** * Configures readiness health checking for instances. Unhealthy instances are not put into the * backend traffic rotation.Only returned in GET requests if view=FULL is set. * @return value or {@code null} for none */ public ReadinessCheck getReadinessCheck() { return readinessCheck; } /** * Configures readiness health checking for instances. Unhealthy instances are not put into the * backend traffic rotation.Only returned in GET requests if view=FULL is set. * @param readinessCheck readinessCheck or {@code null} for none */ public Version setReadinessCheck(ReadinessCheck readinessCheck) { this.readinessCheck = readinessCheck; return this; } /** * Machine resources for this version. Only applicable in the App Engine flexible environment. * @return value or {@code null} for none */ public Resources getResources() { return resources; } /** * Machine resources for this version. Only applicable in the App Engine flexible environment. * @param resources resources or {@code null} for none */ public Version setResources(Resources resources) { this.resources = resources; return this; } /** * Desired runtime. Example: python27. * @return value or {@code null} for none */ public java.lang.String getRuntime() { return runtime; } /** * Desired runtime. Example: python27. * @param runtime runtime or {@code null} for none */ public Version setRuntime(java.lang.String runtime) { this.runtime = runtime; return this; } /** * The version of the API in the given runtime environment. Please see the app.yaml reference for * valid values at https://cloud.google.com/appengine/docs/standard//config/appref * @return value or {@code null} for none */ public java.lang.String getRuntimeApiVersion() { return runtimeApiVersion; } /** * The version of the API in the given runtime environment. Please see the app.yaml reference for * valid values at https://cloud.google.com/appengine/docs/standard//config/appref * @param runtimeApiVersion runtimeApiVersion or {@code null} for none */ public Version setRuntimeApiVersion(java.lang.String runtimeApiVersion) { this.runtimeApiVersion = runtimeApiVersion; return this; } /** * The channel of the runtime to use. Only available for some runtimes. Defaults to the default * channel. * @return value or {@code null} for none */ public java.lang.String getRuntimeChannel() { return runtimeChannel; } /** * The channel of the runtime to use. Only available for some runtimes. Defaults to the default * channel. * @param runtimeChannel runtimeChannel or {@code null} for none */ public Version setRuntimeChannel(java.lang.String runtimeChannel) { this.runtimeChannel = runtimeChannel; return this; } /** * The path or name of the app's main executable. * @return value or {@code null} for none */ public java.lang.String getRuntimeMainExecutablePath() { return runtimeMainExecutablePath; } /** * The path or name of the app's main executable. * @param runtimeMainExecutablePath runtimeMainExecutablePath or {@code null} for none */ public Version setRuntimeMainExecutablePath(java.lang.String runtimeMainExecutablePath) { this.runtimeMainExecutablePath = runtimeMainExecutablePath; return this; } /** * The identity that the deployed version will run as. Admin API will use the App Engine Appspot * service account as default if this field is neither provided in app.yaml file nor through CLI * flag. * @return value or {@code null} for none */ public java.lang.String getServiceAccount() { return serviceAccount; } /** * The identity that the deployed version will run as. Admin API will use the App Engine Appspot * service account as default if this field is neither provided in app.yaml file nor through CLI * flag. * @param serviceAccount serviceAccount or {@code null} for none */ public Version setServiceAccount(java.lang.String serviceAccount) { this.serviceAccount = serviceAccount; return this; } /** * Current serving status of this version. Only the versions with a SERVING status create * instances and can be billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to * SERVING. * @return value or {@code null} for none */ public java.lang.String getServingStatus() { return servingStatus; } /** * Current serving status of this version. Only the versions with a SERVING status create * instances and can be billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to * SERVING. * @param servingStatus servingStatus or {@code null} for none */ public Version setServingStatus(java.lang.String servingStatus) { this.servingStatus = servingStatus; return this; } /** * Whether multiple requests can be dispatched to this version at once. * @return value or {@code null} for none */ public java.lang.Boolean getThreadsafe() { return threadsafe; } /** * Whether multiple requests can be dispatched to this version at once. * @param threadsafe threadsafe or {@code null} for none */ public Version setThreadsafe(java.lang.Boolean threadsafe) { this.threadsafe = threadsafe; return this; } /** * Serving URL for this version. Example: "https://myversion-dot-myservice-dot- * myapp.appspot.com"@OutputOnly * @return value or {@code null} for none */ public java.lang.String getVersionUrl() { return versionUrl; } /** * Serving URL for this version. Example: "https://myversion-dot-myservice-dot- * myapp.appspot.com"@OutputOnly * @param versionUrl versionUrl or {@code null} for none */ public Version setVersionUrl(java.lang.String versionUrl) { this.versionUrl = versionUrl; return this; } /** * Whether to deploy this version in a container on a virtual machine. * @return value or {@code null} for none */ public java.lang.Boolean getVm() { return vm; } /** * Whether to deploy this version in a container on a virtual machine. * @param vm vm or {@code null} for none */ public Version setVm(java.lang.Boolean vm) { this.vm = vm; return this; } /** * Enables VPC connectivity for standard apps. * @return value or {@code null} for none */ public VpcAccessConnector getVpcAccessConnector() { return vpcAccessConnector; } /** * Enables VPC connectivity for standard apps. * @param vpcAccessConnector vpcAccessConnector or {@code null} for none */ public Version setVpcAccessConnector(VpcAccessConnector vpcAccessConnector) { this.vpcAccessConnector = vpcAccessConnector; return this; } /** * The Google Compute Engine zones that are supported by this version in the App Engine flexible * environment. Deprecated. * @return value or {@code null} for none */ public java.util.List<java.lang.String> getZones() { return zones; } /** * The Google Compute Engine zones that are supported by this version in the App Engine flexible * environment. Deprecated. * @param zones zones or {@code null} for none */ public Version setZones(java.util.List<java.lang.String> zones) { this.zones = zones; return this; } @Override public Version set(String fieldName, Object value) { return (Version) super.set(fieldName, value); } @Override public Version clone() { return (Version) super.clone(); } }
googleapis/google-cloud-java
37,673
java-language/proto-google-cloud-language-v1/src/main/java/com/google/cloud/language/v1/AnalyzeEntitySentimentResponse.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/v1/language_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.language.v1; /** * * * <pre> * The entity-level sentiment analysis response message. * </pre> * * Protobuf type {@code google.cloud.language.v1.AnalyzeEntitySentimentResponse} */ public final class AnalyzeEntitySentimentResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.language.v1.AnalyzeEntitySentimentResponse) AnalyzeEntitySentimentResponseOrBuilder { private static final long serialVersionUID = 0L; // Use AnalyzeEntitySentimentResponse.newBuilder() to construct. private AnalyzeEntitySentimentResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AnalyzeEntitySentimentResponse() { entities_ = java.util.Collections.emptyList(); language_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new AnalyzeEntitySentimentResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitySentimentResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitySentimentResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.class, com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.Builder.class); } public static final int ENTITIES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.language.v1.Entity> entities_; /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.language.v1.Entity> getEntitiesList() { return entities_; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.language.v1.EntityOrBuilder> getEntitiesOrBuilderList() { return entities_; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ @java.lang.Override public int getEntitiesCount() { return entities_.size(); } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ @java.lang.Override public com.google.cloud.language.v1.Entity getEntities(int index) { return entities_.get(index); } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ @java.lang.Override public com.google.cloud.language.v1.EntityOrBuilder getEntitiesOrBuilder(int index) { return entities_.get(index); } public static final int LANGUAGE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object language_ = ""; /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @return The language. */ @java.lang.Override public java.lang.String getLanguage() { java.lang.Object ref = language_; 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(); language_ = s; return s; } } /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @return The bytes for language. */ @java.lang.Override public com.google.protobuf.ByteString getLanguageBytes() { java.lang.Object ref = language_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); language_ = 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 < entities_.size(); i++) { output.writeMessage(1, entities_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(language_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, language_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < entities_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entities_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(language_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, language_); } 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.v1.AnalyzeEntitySentimentResponse)) { return super.equals(obj); } com.google.cloud.language.v1.AnalyzeEntitySentimentResponse other = (com.google.cloud.language.v1.AnalyzeEntitySentimentResponse) obj; if (!getEntitiesList().equals(other.getEntitiesList())) return false; if (!getLanguage().equals(other.getLanguage())) 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 (getEntitiesCount() > 0) { hash = (37 * hash) + ENTITIES_FIELD_NUMBER; hash = (53 * hash) + getEntitiesList().hashCode(); } hash = (37 * hash) + LANGUAGE_FIELD_NUMBER; hash = (53 * hash) + getLanguage().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse 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.v1.AnalyzeEntitySentimentResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse 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.v1.AnalyzeEntitySentimentResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse 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.v1.AnalyzeEntitySentimentResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse 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.v1.AnalyzeEntitySentimentResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse 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.v1.AnalyzeEntitySentimentResponse 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 entity-level sentiment analysis response message. * </pre> * * Protobuf type {@code google.cloud.language.v1.AnalyzeEntitySentimentResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.language.v1.AnalyzeEntitySentimentResponse) com.google.cloud.language.v1.AnalyzeEntitySentimentResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitySentimentResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitySentimentResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.class, com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.Builder.class); } // Construct using com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (entitiesBuilder_ == null) { entities_ = java.util.Collections.emptyList(); } else { entities_ = null; entitiesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); language_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitySentimentResponse_descriptor; } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitySentimentResponse getDefaultInstanceForType() { return com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitySentimentResponse build() { com.google.cloud.language.v1.AnalyzeEntitySentimentResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitySentimentResponse buildPartial() { com.google.cloud.language.v1.AnalyzeEntitySentimentResponse result = new com.google.cloud.language.v1.AnalyzeEntitySentimentResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.language.v1.AnalyzeEntitySentimentResponse result) { if (entitiesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { entities_ = java.util.Collections.unmodifiableList(entities_); bitField0_ = (bitField0_ & ~0x00000001); } result.entities_ = entities_; } else { result.entities_ = entitiesBuilder_.build(); } } private void buildPartial0(com.google.cloud.language.v1.AnalyzeEntitySentimentResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.language_ = language_; } } @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.v1.AnalyzeEntitySentimentResponse) { return mergeFrom((com.google.cloud.language.v1.AnalyzeEntitySentimentResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.language.v1.AnalyzeEntitySentimentResponse other) { if (other == com.google.cloud.language.v1.AnalyzeEntitySentimentResponse.getDefaultInstance()) return this; if (entitiesBuilder_ == null) { if (!other.entities_.isEmpty()) { if (entities_.isEmpty()) { entities_ = other.entities_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEntitiesIsMutable(); entities_.addAll(other.entities_); } onChanged(); } } else { if (!other.entities_.isEmpty()) { if (entitiesBuilder_.isEmpty()) { entitiesBuilder_.dispose(); entitiesBuilder_ = null; entities_ = other.entities_; bitField0_ = (bitField0_ & ~0x00000001); entitiesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEntitiesFieldBuilder() : null; } else { entitiesBuilder_.addAllMessages(other.entities_); } } } if (!other.getLanguage().isEmpty()) { language_ = other.language_; 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.language.v1.Entity m = input.readMessage( com.google.cloud.language.v1.Entity.parser(), extensionRegistry); if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.add(m); } else { entitiesBuilder_.addMessage(m); } break; } // case 10 case 18: { language_ = 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.language.v1.Entity> entities_ = java.util.Collections.emptyList(); private void ensureEntitiesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { entities_ = new java.util.ArrayList<com.google.cloud.language.v1.Entity>(entities_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.language.v1.Entity, com.google.cloud.language.v1.Entity.Builder, com.google.cloud.language.v1.EntityOrBuilder> entitiesBuilder_; /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public java.util.List<com.google.cloud.language.v1.Entity> getEntitiesList() { if (entitiesBuilder_ == null) { return java.util.Collections.unmodifiableList(entities_); } else { return entitiesBuilder_.getMessageList(); } } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public int getEntitiesCount() { if (entitiesBuilder_ == null) { return entities_.size(); } else { return entitiesBuilder_.getCount(); } } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public com.google.cloud.language.v1.Entity getEntities(int index) { if (entitiesBuilder_ == null) { return entities_.get(index); } else { return entitiesBuilder_.getMessage(index); } } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder setEntities(int index, com.google.cloud.language.v1.Entity value) { if (entitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntitiesIsMutable(); entities_.set(index, value); onChanged(); } else { entitiesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder setEntities( int index, com.google.cloud.language.v1.Entity.Builder builderForValue) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.set(index, builderForValue.build()); onChanged(); } else { entitiesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder addEntities(com.google.cloud.language.v1.Entity value) { if (entitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntitiesIsMutable(); entities_.add(value); onChanged(); } else { entitiesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder addEntities(int index, com.google.cloud.language.v1.Entity value) { if (entitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEntitiesIsMutable(); entities_.add(index, value); onChanged(); } else { entitiesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder addEntities(com.google.cloud.language.v1.Entity.Builder builderForValue) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.add(builderForValue.build()); onChanged(); } else { entitiesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder addEntities( int index, com.google.cloud.language.v1.Entity.Builder builderForValue) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.add(index, builderForValue.build()); onChanged(); } else { entitiesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder addAllEntities( java.lang.Iterable<? extends com.google.cloud.language.v1.Entity> values) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entities_); onChanged(); } else { entitiesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder clearEntities() { if (entitiesBuilder_ == null) { entities_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { entitiesBuilder_.clear(); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public Builder removeEntities(int index) { if (entitiesBuilder_ == null) { ensureEntitiesIsMutable(); entities_.remove(index); onChanged(); } else { entitiesBuilder_.remove(index); } return this; } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public com.google.cloud.language.v1.Entity.Builder getEntitiesBuilder(int index) { return getEntitiesFieldBuilder().getBuilder(index); } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public com.google.cloud.language.v1.EntityOrBuilder getEntitiesOrBuilder(int index) { if (entitiesBuilder_ == null) { return entities_.get(index); } else { return entitiesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public java.util.List<? extends com.google.cloud.language.v1.EntityOrBuilder> getEntitiesOrBuilderList() { if (entitiesBuilder_ != null) { return entitiesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(entities_); } } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public com.google.cloud.language.v1.Entity.Builder addEntitiesBuilder() { return getEntitiesFieldBuilder() .addBuilder(com.google.cloud.language.v1.Entity.getDefaultInstance()); } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public com.google.cloud.language.v1.Entity.Builder addEntitiesBuilder(int index) { return getEntitiesFieldBuilder() .addBuilder(index, com.google.cloud.language.v1.Entity.getDefaultInstance()); } /** * * * <pre> * The recognized entities in the input document with associated sentiments. * </pre> * * <code>repeated .google.cloud.language.v1.Entity entities = 1;</code> */ public java.util.List<com.google.cloud.language.v1.Entity.Builder> getEntitiesBuilderList() { return getEntitiesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.language.v1.Entity, com.google.cloud.language.v1.Entity.Builder, com.google.cloud.language.v1.EntityOrBuilder> getEntitiesFieldBuilder() { if (entitiesBuilder_ == null) { entitiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.language.v1.Entity, com.google.cloud.language.v1.Entity.Builder, com.google.cloud.language.v1.EntityOrBuilder>( entities_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); entities_ = null; } return entitiesBuilder_; } private java.lang.Object language_ = ""; /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @return The language. */ public java.lang.String getLanguage() { java.lang.Object ref = language_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); language_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @return The bytes for language. */ public com.google.protobuf.ByteString getLanguageBytes() { java.lang.Object ref = language_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); language_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @param value The language to set. * @return This builder for chaining. */ public Builder setLanguage(java.lang.String value) { if (value == null) { throw new NullPointerException(); } language_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @return This builder for chaining. */ public Builder clearLanguage() { language_ = getDefaultInstance().getLanguage(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * The language of the text, which will be the same as the language specified * in the request or, if not specified, the automatically-detected language. * See [Document.language][google.cloud.language.v1.Document.language] field * for more details. * </pre> * * <code>string language = 2;</code> * * @param value The bytes for language to set. * @return This builder for chaining. */ public Builder setLanguageBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); language_ = 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.language.v1.AnalyzeEntitySentimentResponse) } // @@protoc_insertion_point(class_scope:google.cloud.language.v1.AnalyzeEntitySentimentResponse) private static final com.google.cloud.language.v1.AnalyzeEntitySentimentResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.language.v1.AnalyzeEntitySentimentResponse(); } public static com.google.cloud.language.v1.AnalyzeEntitySentimentResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AnalyzeEntitySentimentResponse> PARSER = new com.google.protobuf.AbstractParser<AnalyzeEntitySentimentResponse>() { @java.lang.Override public AnalyzeEntitySentimentResponse 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<AnalyzeEntitySentimentResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AnalyzeEntitySentimentResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitySentimentResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googlearchive/science-journal
37,851
OpenScienceJournal/whistlepunk_library/src/main/java/com/google/android/apps/forscience/whistlepunk/RecorderControllerImpl.java
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.forscience.whistlepunk; import android.content.Context; import android.content.Intent; import android.os.RemoteException; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import android.text.TextUtils; import android.util.ArrayMap; import com.google.android.apps.forscience.javalib.Consumer; import com.google.android.apps.forscience.javalib.Delay; import com.google.android.apps.forscience.javalib.FallibleConsumer; import com.google.android.apps.forscience.javalib.MaybeConsumer; import com.google.android.apps.forscience.javalib.Scheduler; import com.google.android.apps.forscience.javalib.Success; import com.google.android.apps.forscience.whistlepunk.accounts.AppAccount; import com.google.android.apps.forscience.whistlepunk.actionarea.SensorFragment; import com.google.android.apps.forscience.whistlepunk.analytics.TrackerConstants; import com.google.android.apps.forscience.whistlepunk.data.GoosciSensorLayout.SensorLayout; import com.google.android.apps.forscience.whistlepunk.data.GoosciSensorLayout.SensorLayout.CardView; import com.google.android.apps.forscience.whistlepunk.data.GoosciSensorSpec; import com.google.android.apps.forscience.whistlepunk.filemetadata.Experiment; import com.google.android.apps.forscience.whistlepunk.filemetadata.Label; import com.google.android.apps.forscience.whistlepunk.filemetadata.SensorLayoutPojo; import com.google.android.apps.forscience.whistlepunk.filemetadata.SensorTrigger; import com.google.android.apps.forscience.whistlepunk.filemetadata.Trial; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciCaption; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciLabel; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciSensorTriggerInformation.TriggerInformation.TriggerActionType; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciSensorTriggerInformation.TriggerInformation.TriggerAlertType; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciSensorTriggerLabelValue; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciSnapshotValue; import com.google.android.apps.forscience.whistlepunk.metadata.GoosciSnapshotValue.SnapshotLabelValue.SensorSnapshot; import com.google.android.apps.forscience.whistlepunk.metadata.TriggerHelper; import com.google.android.apps.forscience.whistlepunk.sensorapi.ScalarSensor; import com.google.android.apps.forscience.whistlepunk.sensorapi.SensorChoice; import com.google.android.apps.forscience.whistlepunk.sensorapi.SensorEnvironment; import com.google.android.apps.forscience.whistlepunk.sensorapi.SensorObserver; import com.google.android.apps.forscience.whistlepunk.sensorapi.SensorRecorder; import com.google.android.apps.forscience.whistlepunk.sensorapi.SensorStatusListener; import com.google.android.apps.forscience.whistlepunk.sensordb.ScalarReading; import com.google.android.apps.forscience.whistlepunk.sensors.SystemScheduler; import com.google.android.apps.forscience.whistlepunk.wireapi.RecordingMetadata; import com.google.android.apps.forscience.whistlepunk.wireapi.TransportableSensorOptions; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import io.reactivex.Completable; import io.reactivex.Maybe; import io.reactivex.MaybeSource; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.subjects.BehaviorSubject; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Keeps track of: * * <ul> * <li>All the recorders that are currently observing or recording * <li>The recording state (when did the current run start, if any?) * <li>The currently-selected experiment * </ul> */ public class RecorderControllerImpl implements RecorderController { private static final String TAG = "RecorderController"; /** * Default delay to wait after the last observer stops before asking the sensor to stop * collecting. */ // private static final Delay DEFAULT_STOP_DELAY = Delay.seconds(5); // TODO: remove this comment when we're sure about the delay. // To disable delayed stop, comment out the above line, and uncomment this one. private static final Delay DEFAULT_STOP_DELAY = Delay.ZERO; private final AppAccount appAccount; private DataController dataController; private final Scheduler scheduler; private final Clock clock; private final Delay stopDelay; private SensorAppearanceProvider appearanceProvider; private Map<String, StatefulRecorder> recorders = new LinkedHashMap<>(); private final Context context; private final RecorderListenerRegistry registry; private Map<String, String> serviceObservers = new HashMap<>(); private RecorderServiceConnection serviceConnection = null; private int pauseCount = 0; private final SensorEnvironment sensorEnvironment; private BehaviorSubject<Experiment> selectedExperiment = BehaviorSubject.create(); private String currentTrialId = ""; private boolean recordingStateChangeInProgress; private TriggerHelper triggerHelper; private boolean activityInForeground = false; private final Supplier<RecorderServiceConnection> connectionSupplier; private int nextTriggerListenerId = 0; private Map<Integer, TriggerFiredListener> triggerListeners = new HashMap<>(); private Map<String, ObservedIdsListener> observedIdListeners = new ArrayMap<>(); private BehaviorSubject<RecordingStatus> recordingStatus = BehaviorSubject.createDefault(RecordingStatus.INACTIVE); private Supplier<List<SensorLayoutPojo>> layoutSupplier; /** The latest recorded value for each sensor */ private Map<String, BehaviorSubject<ScalarReading>> latestValues = new HashMap<>(); public RecorderControllerImpl(Context context, AppAccount appAccount) { this(context, appAccount, AppSingleton.getInstance(context).getDataController(appAccount)); } private RecorderControllerImpl( Context context, AppAccount appAccount, DataController dataController) { this( context, appAccount, AppSingleton.getInstance(context).getSensorEnvironment(), new RecorderListenerRegistry(), productionConnectionSupplier(context), dataController, new SystemScheduler(), DEFAULT_STOP_DELAY, AppSingleton.getInstance(context).getSensorAppearanceProvider(appAccount)); } // TODO: use builder? /** * @param scheduler for scheduling delayed stops if desired (to prevent sensor stop/start churn) * @param stopDelay how long to wait before stopping sensors. */ @VisibleForTesting public RecorderControllerImpl( final Context context, AppAccount appAccount, SensorEnvironment sensorEnvironment, RecorderListenerRegistry listenerRegistry, Supplier<RecorderServiceConnection> connectionSupplier, DataController dataController, Scheduler scheduler, Delay stopDelay, SensorAppearanceProvider appearanceProvider) { this.context = context; this.appAccount = appAccount; this.sensorEnvironment = sensorEnvironment; registry = listenerRegistry; this.connectionSupplier = connectionSupplier; this.dataController = dataController; this.scheduler = scheduler; this.stopDelay = stopDelay; this.appearanceProvider = appearanceProvider; clock = new CurrentTimeClock(); } @NonNull private static Supplier<RecorderServiceConnection> productionConnectionSupplier( final Context context) { return () -> new RecorderServiceConnectionImpl( context, LoggingConsumer.expectSuccess(TAG, "remote service operation")); } // TODO: Can RecorderControllerImpl eventually own / look up the triggers so they don't // need to be passed in here? @Override public String startObserving( final String sensorId, final List<SensorTrigger> activeTriggers, SensorObserver observer, SensorStatusListener listener, final TransportableSensorOptions initialOptions, SensorRegistry sensorRegistry) { // Put the observer and listener in the registry by sensorId. String observerId = registry.putListeners(sensorId, observer, listener); StatefulRecorder sr = recorders.get(sensorId); if (sr != null) { RecorderControllerImpl.this.startObserving(sr); addServiceObserverIfNeeded(sensorId, activeTriggers, sensorRegistry); } else { sensorRegistry.withSensorChoice( TAG, sensorId, new Consumer<SensorChoice>() { @Override public void take(SensorChoice sensor) { final SensorRecorder recorder = sensor.createRecorder( context, appAccount, registry.makeObserverForRecorder(sensorId), registry, sensorEnvironment); recorder.applyOptions(new ReadableTransportableSensorOptions(initialOptions)); StatefulRecorder newStatefulRecorder = new StatefulRecorder(recorder, scheduler, stopDelay); recorders.put(sensorId, newStatefulRecorder); // TODO: can we avoid passing sensorRegistry so deep? addServiceObserverIfNeeded(sensorId, activeTriggers, sensorRegistry); RecorderControllerImpl.this.startObserving(newStatefulRecorder); } }); } return observerId; } @Override public void reboot(String sensorId) { StatefulRecorder recorder = recorders.get(sensorId); if (recorder != null) { recorder.reboot(); } } private void addServiceObserverIfNeeded( final String sensorId, final List<SensorTrigger> activeTriggers, SensorRegistry sensorRegistry) { if (!latestValues.containsKey(sensorId)) { latestValues.put(sensorId, BehaviorSubject.<ScalarReading>create()); } if (!serviceObservers.containsKey(sensorId)) { String serviceObserverId = registry.putListeners( sensorId, (timestamp, data) -> { if (!ScalarSensor.hasValue(data)) { return; } double value = ScalarSensor.getValue(data); // Remember latest value latestValues.get(sensorId).onNext(new ScalarReading(timestamp, value, sensorId)); // Fire triggers. for (SensorTrigger trigger : activeTriggers) { if (!isRecording() && trigger.shouldTriggerOnlyWhenRecording()) { continue; } if (trigger.isTriggered(value)) { fireSensorTrigger(trigger, timestamp, sensorRegistry); } } }, null); serviceObservers.put(sensorId, serviceObserverId); } } private List<SensorLayoutPojo> buildSensorLayouts() { return layoutSupplier == null ? Collections.<SensorLayoutPojo>emptyList() : layoutSupplier.get(); } private void fireSensorTrigger( SensorTrigger trigger, long timestamp, SensorRegistry sensorRegistry) { // TODO: Think about behavior for triggers firing near the same time, especially // regarding start/stop recording and notes. Right now behavior may not seem repeatable // depending on timing of callbacks and order of triggers. b/ boolean triggerWasFired = false; if (trigger.getActionType() == TriggerActionType.TRIGGER_ACTION_START_RECORDING && !isRecording() && getSelectedExperiment() != null) { if (!recordingStateChangeInProgress) { triggerWasFired = true; for (TriggerFiredListener listener : triggerListeners.values()) { listener.onRequestStartRecording(); } // TODO: test this subscribe startRecording(new Intent(context, MainActivity.class), /* not user initiated */ false) .subscribe(LoggingConsumer.observe(TAG, "start recording with trigger")); WhistlePunkApplication.getUsageTracker(context) .trackEvent( TrackerConstants.CATEGORY_RUNS, TrackerConstants.ACTION_TRY_RECORDING_FROM_TRIGGER, null, 0); } } else if (trigger.getActionType() == TriggerActionType.TRIGGER_ACTION_STOP_RECORDING && isRecording()) { if (!recordingStateChangeInProgress) { triggerWasFired = true; for (TriggerFiredListener listener : triggerListeners.values()) { listener.onRequestStopRecording(this); } stopRecording(sensorRegistry) .subscribe(LoggingConsumer.observe(TAG, "stop recording with trigger")); WhistlePunkApplication.getUsageTracker(context) .trackEvent( TrackerConstants.CATEGORY_RUNS, TrackerConstants.ACTION_TRY_STOP_RECORDING_FROM_TRIGGER, null, 0); } } else if (trigger.getActionType() == TriggerActionType.TRIGGER_ACTION_NOTE) { triggerWasFired = true; addTriggerLabel(timestamp, trigger, sensorRegistry); } else if (trigger.getActionType() == TriggerActionType.TRIGGER_ACTION_ALERT) { Set<TriggerAlertType> alertTypes = trigger.getAlertTypes(); if (!alertTypes.isEmpty()) { triggerWasFired = true; } if (alertTypes.contains(TriggerAlertType.TRIGGER_ALERT_PHYSICAL)) { getTriggerHelper().doVibrateAlert(context); } if (alertTypes.contains(TriggerAlertType.TRIGGER_ALERT_AUDIO)) { getTriggerHelper().doAudioAlert(context); } // Visual alerts are not covered in RecorderControllerImpl. } // Not all triggers should actually be fired -- for example, we cannot stop recording if // we are not yet recording. Only call the trigger fired listeners when the event actually // takes place. if (triggerWasFired) { for (TriggerFiredListener listener : triggerListeners.values()) { listener.onTriggerFired(trigger); } } } private TriggerHelper getTriggerHelper() { if (triggerHelper == null) { triggerHelper = new TriggerHelper(); } return triggerHelper; } private void addTriggerLabel( long timestamp, SensorTrigger trigger, SensorRegistry sensorRegistry) { if (getSelectedExperiment() == null) { return; } GoosciSensorTriggerLabelValue.SensorTriggerLabelValue.Builder labelValue = GoosciSensorTriggerLabelValue.SensorTriggerLabelValue.newBuilder() .setTriggerInformation(trigger.getTriggerProto().getTriggerInformation()); GoosciCaption.Caption.Builder caption = null; if (!TextUtils.isEmpty((trigger.getNoteText()))) { caption = GoosciCaption.Caption.newBuilder(); caption.setLastEditedTimestamp(timestamp).setText(trigger.getNoteText()); } labelValue.setSensor(getSensorSpec(trigger.getSensorId(), sensorRegistry)); final Label triggerLabel = Label.newLabelWithValue( timestamp, GoosciLabel.Label.ValueType.SENSOR_TRIGGER, labelValue.build(), caption.build()); if (isRecording()) { // Adds the label to the trial and saves the updated experiment. getSelectedExperiment() .getTrial(currentTrialId) .addLabel(getSelectedExperiment(), triggerLabel); } else { // Adds the label to the experiment and saves the updated experiment. getSelectedExperiment().addLabel(getSelectedExperiment(), triggerLabel); } dataController.updateExperiment( getSelectedExperiment().getExperimentId(), new LoggingConsumer<Success>(TAG, "add trigger label") { @Override public void success(Success value) { onTriggerLabelAdded(triggerLabel); } }); } private GoosciSensorSpec.SensorSpec getSensorSpec( String sensorId, SensorRegistry sensorRegistry) { return sensorRegistry.getSpecForId(sensorId, appearanceProvider, context); } public Experiment getSelectedExperiment() { // TODO: consider using as subject more places return selectedExperiment.getValue(); } private void onTriggerLabelAdded(Label label) { String trackerLabel = isRecording() ? TrackerConstants.LABEL_RECORD : TrackerConstants.LABEL_OBSERVE; WhistlePunkApplication.getUsageTracker(context) .trackEvent( TrackerConstants.CATEGORY_NOTES, TrackerConstants.ACTION_CREATE, trackerLabel, TrackerConstants.getLabelValueType(label)); AppSingleton.getInstance(context).onLabelsAdded().onNext(label); } private void startObserving(StatefulRecorder sr) { sr.startObserving(); updateObservedIdListeners(); } @Override public void clearSensorTriggers(String sensorId, SensorRegistry sensorRegistry) { String observerId = serviceObservers.get(sensorId); if (!TextUtils.isEmpty(observerId)) { // Remove the old serviceObserver and add a new one with no triggers. serviceObservers.remove(sensorId); registry.remove(sensorId, observerId); addServiceObserverIfNeeded(sensorId, Collections.<SensorTrigger>emptyList(), sensorRegistry); } } @Override public void setLayoutSupplier(Supplier<List<SensorLayoutPojo>> supplier) { layoutSupplier = supplier; } @Override public long getNow() { return sensorEnvironment.getDefaultClock().getNow(); } @Override public void stopObserving(String sensorId, String observerId) { registry.remove(sensorId, observerId); // If there are no listeners left except for our serviceobserver, remove it. if (registry.countListeners(sensorId) == 1) { stopObservingServiceObserver(sensorId); } cleanUpUnusedRecorders(); updateObservedIdListeners(); if (recorders.isEmpty()) { SensorHistoryStorage storage = sensorEnvironment.getSensorHistoryStorage(); storage.setMostRecentSensorIds(Lists.newArrayList(sensorId)); } } private void stopObservingServiceObserver(String sensorId) { final StatefulRecorder r = recorders.get(sensorId); if (r != null) { r.stopObserving(); if (!r.isRecording()) { // If it was not recording, we can also remove our service-level observers. if (serviceObservers.containsKey(sensorId)) { String serviceObserverId = serviceObservers.get(sensorId); registry.remove(sensorId, serviceObserverId); serviceObservers.remove(sensorId); latestValues.remove(sensorId); } } } } private void updateObservedIdListeners() { List<String> currentObservedSensorIds = getCurrentObservedSensorIds(); for (ObservedIdsListener observedIdsListener : observedIdListeners.values()) { observedIdsListener.onObservedIdsChanged(currentObservedSensorIds); } } @Override public List<String> getMostRecentObservedSensorIds() { List<String> keys = getCurrentObservedSensorIds(); if (keys.isEmpty()) { return sensorEnvironment.getSensorHistoryStorage().getMostRecentSensorIds(); } else { return keys; } } @Override public Observable<RecordingStatus> watchRecordingStatus() { return recordingStatus; } private List<String> getCurrentObservedSensorIds() { return Lists.newArrayList(recorders.keySet()); } // TODO: test this logic @Override public String pauseObservingAll() { ++pauseCount; if (!isRecording()) { for (StatefulRecorder recorder : recorders.values()) { recorder.stopObserving(); } } return String.valueOf(pauseCount); } // TODO: test this logic @Override public boolean resumeObservingAll(String pauseId) { if (!Objects.equals(pauseId, String.valueOf(pauseCount))) { return false; } if (!isRecording()) { for (StatefulRecorder recorder : recorders.values()) { startObserving(recorder); } } return true; } @Override public void applyOptions(String sensorId, TransportableSensorOptions settings) { final StatefulRecorder r = recorders.get(sensorId); if (r != null) { r.applyOptions(new ReadableTransportableSensorOptions(settings)); } } private void cleanUpUnusedRecorders() { final Iterator<Map.Entry<String, StatefulRecorder>> iter = recorders.entrySet().iterator(); while (iter.hasNext()) { StatefulRecorder r = iter.next().getValue(); if (!r.isStillRunning()) { iter.remove(); } } } @Override public Completable startRecording(final Intent resumeIntent, boolean userInitiated) { if (isRecording() || recordingStateChangeInProgress) { return Completable.complete(); } if (recorders.size() == 0) { // If the recorders are empty, then we stopped observing a sensor before we tried // to start recording it. This may happen if we failed to connect to an external sensor // and it was disconnected before recording started. return Completable.error( new RecordingStartFailedException(RecorderController.ERROR_START_FAILED, null)); } // Check that all sensors are connected before starting a recording. for (String sensorId : recorders.keySet()) { if (!registry.isSourceConnectedWithoutError(sensorId)) { return Completable.error( new RecordingStartFailedException( RecorderController.ERROR_START_FAILED_DISCONNECTED, null)); } } recordingStatus.onNext( recordingStatus.getValue().withState(RecordingState.STARTING, userInitiated)); recordingStateChangeInProgress = true; return Completable.create( emitter -> withBoundRecorderService( new FallibleConsumer<IRecorderService>() { @Override public void take(final IRecorderService recorderService) throws RemoteException { final DataController dataController = RecorderControllerImpl.this.dataController; final long creationTimeMs = clock.getNow(); List<SensorLayoutPojo> layouts = buildSensorLayouts(); SensorLayout[] layoutProtos = new SensorLayout[layouts.size()]; int i = 0; for (SensorLayoutPojo pojo : layouts) { layoutProtos[i] = pojo.toProto(); i++; } Trial trial = Trial.newTrial(creationTimeMs, layoutProtos, appearanceProvider, context); currentTrialId = trial.getTrialId(); getSelectedExperiment().addTrial(trial); dataController.updateExperiment( getSelectedExperiment().getExperimentId(), new LoggingConsumer<Success>(TAG, "start trial") { @Override public void success(Success success) { RecordingMetadata recording = new RecordingMetadata( creationTimeMs, currentTrialId, getSelectedExperiment().getDisplayTitle(context)); ensureUnarchived(getSelectedExperiment(), dataController); recorderService.beginServiceRecording( recording.getExperimentName(), resumeIntent); for (StatefulRecorder recorder : recorders.values()) { recorder.startRecording(recording.getRunId()); } setRecording(recording); recordingStateChangeInProgress = false; emitter.onComplete(); } @Override public void fail(Exception e) { super.fail(e); recordingStateChangeInProgress = false; currentTrialId = ""; recordingStatus.onNext(RecordingStatus.INACTIVE); emitter.onError( new RecordingStartFailedException( RecorderController.ERROR_START_FAILED, e)); } }); } })); } private RecordingMetadata getRecording() { return recordingStatus.getValue().currentRecording; } private void setRecording(RecordingMetadata recording) { recordingStatus.onNext( recording == null ? RecordingStatus.INACTIVE : RecordingStatus.active(recording)); } private Completable stopRecordingError(int error) { // Still recording, because stopping has failed. Reset the recording status. recordingStatus.onNext(recordingStatus.getValue().withState(RecordingState.ACTIVE)); return Completable.error(new RecordingStopFailedException(error, null)); } @Override public Completable stopRecording(final SensorRegistry sensorRegistry) { if (!isRecording() || getSelectedExperiment() == null || recordingStateChangeInProgress) { return Completable.complete(); } // Disable the record button to stop double-clicks. recordingStatus.onNext(recordingStatus.getValue().withState(RecordingState.STOPPING)); // TODO: What happens when recording stop fails and the app is in the background? // First check that all sensors have at least one data point. A recording with no // data is invalid. for (String sensorId : recorders.keySet()) { // If we try to stop recording when a sensor is not connected, recording stop fails. if (!registry.isSourceConnectedWithoutError(sensorId)) { return stopRecordingError(RecorderController.ERROR_STOP_FAILED_DISCONNECTED); } // Check to see if it has no data recorded, as this also fails stop recording. if (!recorders.get(sensorId).hasRecordedData()) { return stopRecordingError(RecorderController.ERROR_STOP_FAILED_NO_DATA); } } recordingStateChangeInProgress = true; final boolean activityInForeground = this.activityInForeground; return Completable.create( emitter -> withBoundRecorderService( new FallibleConsumer<IRecorderService>() { @Override public void take(final IRecorderService recorderService) throws RemoteException { final Trial trial = getSelectedExperiment().getTrial(currentTrialId); final List<SensorLayoutPojo> sensorLayoutsAtStop = buildSensorLayouts(); if (sensorLayoutsAtStop.size() > 0) { trial.setSensorLayouts(sensorLayoutsAtStop); } trial.setRecordingEndTime(clock.getNow()); dataController.updateExperiment( getSelectedExperiment().getExperimentId(), new LoggingConsumer<Success>(TAG, "stopTrial") { @Override public void success(Success value) { for (StatefulRecorder recorder : recorders.values()) { recorder.stopRecording(trial); } trackStopRecording( context.getApplicationContext(), trial, sensorLayoutsAtStop, sensorRegistry); dataController.updateExperiment( getSelectedExperiment().getExperimentId(), endRecordingConsumer( recorderService, activityInForeground, currentTrialId)); // Now actually stop the recording. currentTrialId = ""; cleanUpUnusedRecorders(); setRecording(null); recordingStateChangeInProgress = false; emitter.onComplete(); } @Override public void fail(Exception e) { super.fail(e); recordingStateChangeInProgress = false; setRecording(null); emitter.onError( new RecordingStopFailedException( RecorderController.ERROR_FAILED_SAVE_RECORDING, e)); } }); } })); } /** This is a convenience function for testing. */ @VisibleForTesting public Maybe<String> generateSnapshotText(List<String> sensorIds, SensorRegistry sensorRegistry) { // TODO: we probably want to do something more structured eventually; // this is a placeholder, so we're not doing internationalization, etc. return generateSnapshotLabelValue(sensorIds, sensorRegistry) // turn the snapshots into strings .flatMapObservable(this::textsForSnapshotLabelValue) // join them with commas .reduce((a, b) -> a + ", " + b) // or return a default if there are none .defaultIfEmpty("No sensors observed"); } @Override public Single<GoosciSnapshotValue.SnapshotLabelValue> generateSnapshotLabelValue( List<String> sensorIds, SensorRegistry sensorRegistry) { // for each sensorId return Observable.fromIterable(sensorIds) // get a snapshot from the latest value* .flatMapMaybe(sensorId -> makeSnapshot(sensorId, sensorRegistry)) // gather those into a list .toList() // And build them into the appropriate proto value .map(this::buildSnapshotLabelValue); // * The "flat" in flatMapMaybe means that we're taking a stream of Maybes (one for each // sensorId), and "flattening" them into a stream of Strings (that is, we're waiting for // each Maybe to be resolved to its actual snapshotText). } private MaybeSource<SensorSnapshot> makeSnapshot(String sensorId, SensorRegistry sensorRegistry) throws Exception { BehaviorSubject<ScalarReading> subject = latestValues.get(sensorId); if (subject == null) { return Maybe.empty(); } final GoosciSensorSpec.SensorSpec spec = getSensorSpec(sensorId, sensorRegistry); return subject.firstElement().map(value -> generateSnapshot(spec, value)); } private GoosciSnapshotValue.SnapshotLabelValue buildSnapshotLabelValue( List<SensorSnapshot> snapshots) { return GoosciSnapshotValue.SnapshotLabelValue.newBuilder().addAllSnapshots(snapshots).build(); } private Observable<String> textsForSnapshotLabelValue( GoosciSnapshotValue.SnapshotLabelValue value) { return Observable.fromIterable(value.getSnapshotsList()) .map(this::textForSnapshot); } @NonNull private String textForSnapshot(SensorSnapshot snapshot) { return snapshot.getSensor().getRememberedAppearance().getName() + " has value " + snapshot.getValue(); } @NonNull private SensorSnapshot generateSnapshot(GoosciSensorSpec.SensorSpec spec, ScalarReading reading) { return SensorSnapshot.newBuilder() .setSensor(spec) .setValue(reading.getValue()) .setTimestampMs(reading.getCollectedTimeMillis()) .build(); } @Override public void stopRecordingWithoutSaving() { // TODO: Delete partially recorded data and trial? if (!isRecording() || recordingStateChangeInProgress) { return; } currentTrialId = ""; for (StatefulRecorder recorder : recorders.values()) { // No trial to update, since we are not saving this. recorder.stopRecording(null); } recordingStateChangeInProgress = true; withBoundRecorderService( recorderService -> { recorderService.endServiceRecording( appAccount, false, "", getSelectedExperiment().getExperimentId(), ""); recordingStateChangeInProgress = false; }); cleanUpUnusedRecorders(); setRecording(null); } @VisibleForTesting void trackStopRecording( Context context, Trial completeTrial, List<SensorLayoutPojo> sensorLayouts, SensorRegistry sensorRegistry) { // Record how long this session was. WhistlePunkApplication.getUsageTracker(context) .trackEvent( TrackerConstants.CATEGORY_RUNS, TrackerConstants.ACTION_CREATE, null, completeTrial.getOriginalLastTimestamp() - getRecording().getStartTime()); // Record which sensors were recorded and information about their layouts. List<String> sensorLogs = new ArrayList<>(); for (SensorLayoutPojo layout : sensorLayouts) { String loggingId = sensorRegistry.getLoggingId(layout.getSensorId()); sensorLogs.add(getLayoutLoggingString(loggingId, layout)); } WhistlePunkApplication.getUsageTracker(context) .trackEvent( TrackerConstants.CATEGORY_RUNS, TrackerConstants.ACTION_RECORDED, Joiner.on(",").join(sensorLogs), 0); } String getLayoutLoggingString(String loggingId, SensorLayoutPojo layout) { StringBuilder builder = new StringBuilder(); builder.append(loggingId); builder.append("|"); builder.append(layout.getCardView() == CardView.METER ? "meter" : "graph"); builder.append("|"); builder.append(layout.isAudioEnabled() ? "audioOn" : "audioOff"); return builder.toString(); } /** * Convenience function for asynchronously binding to the service and doing something with it. * * @param c what to do */ protected void withBoundRecorderService(final FallibleConsumer<IRecorderService> c) { // TODO: push logic to RecorderService if (serviceConnection == null) { serviceConnection = connectionSupplier.get(); } serviceConnection.runWithService(c); } public int addTriggerFiredListener(TriggerFiredListener listener) { Preconditions.checkNotNull(listener); int listenerId = nextTriggerListenerId++; triggerListeners.put(listenerId, listener); return listenerId; } @Override public void removeTriggerFiredListener(int listenerId) { triggerListeners.remove(listenerId); } @Override public void addObservedIdsListener(String listenerId, ObservedIdsListener listener) { observedIdListeners.put(listenerId, listener); listener.onObservedIdsChanged(getMostRecentObservedSensorIds()); } @Override public void removeObservedIdsListener(String listenerId) { observedIdListeners.remove(listenerId); } @Override public void setSelectedExperiment(Experiment experiment) { // TODO: pass in observable instead? selectedExperiment.onNext(experiment); } private boolean isRecording() { return getRecording() != null; } @VisibleForTesting public Map<String, StatefulRecorder> getRecorders() { return recorders; } @VisibleForTesting void ensureUnarchived(Experiment experiment, DataController dc) { SensorFragment.ensureUnarchived(context, experiment, dc); } @Override public void setRecordActivityInForeground(boolean isInForeground) { activityInForeground = isInForeground; } private MaybeConsumer<Success> endRecordingConsumer( IRecorderService recorderService, boolean activityInForeground, String trialId) { return new LoggingConsumer<Success>(TAG, "update completed trial") { @Override public void success(Success value) { // TODO: Can we use SimpleMetadataManager#close instead? dataController.saveImmediately( new LoggingConsumer<Success>(TAG, "save immediately") { @Override public void success(Success value) { // Close the service. When the service is // closed, if the app is in the background, // all processes will stop -- so this needs // to be the last thing to happen! Experiment exp = getSelectedExperiment(); recorderService.endServiceRecording( appAccount, !activityInForeground, trialId, exp.getExperimentId(), exp.getDisplayTitle(context)); } }); } }; } @Override public AppAccount getAppAccount() { return appAccount; } }
googleapis/google-cloud-java
37,697
java-gkehub/proto-google-cloud-gkehub-v1beta/src/main/java/com/google/cloud/gkehub/configmanagement/v1beta/PolicyControllerMonitoring.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/v1beta/configmanagement/configmanagement.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.gkehub.configmanagement.v1beta; /** * * * <pre> * PolicyControllerMonitoring specifies the backends Policy Controller should * export metrics to. For example, to specify metrics should be exported to * Cloud Monitoring and Prometheus, specify * backends: ["cloudmonitoring", "prometheus"] * </pre> * * Protobuf type {@code google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring} */ public final class PolicyControllerMonitoring extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) PolicyControllerMonitoringOrBuilder { private static final long serialVersionUID = 0L; // Use PolicyControllerMonitoring.newBuilder() to construct. private PolicyControllerMonitoring(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private PolicyControllerMonitoring() { backends_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new PolicyControllerMonitoring(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.configmanagement.v1beta.ConfigManagementProto .internal_static_google_cloud_gkehub_configmanagement_v1beta_PolicyControllerMonitoring_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.configmanagement.v1beta.ConfigManagementProto .internal_static_google_cloud_gkehub_configmanagement_v1beta_PolicyControllerMonitoring_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.class, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.Builder .class); } /** * * * <pre> * Supported backend options for monitoring * </pre> * * Protobuf enum {@code * google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend} */ public enum MonitoringBackend implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Backend cannot be determined * </pre> * * <code>MONITORING_BACKEND_UNSPECIFIED = 0;</code> */ MONITORING_BACKEND_UNSPECIFIED(0), /** * * * <pre> * Prometheus backend for monitoring * </pre> * * <code>PROMETHEUS = 1;</code> */ PROMETHEUS(1), /** * * * <pre> * Stackdriver/Cloud Monitoring backend for monitoring * </pre> * * <code>CLOUD_MONITORING = 2;</code> */ CLOUD_MONITORING(2), UNRECOGNIZED(-1), ; /** * * * <pre> * Backend cannot be determined * </pre> * * <code>MONITORING_BACKEND_UNSPECIFIED = 0;</code> */ public static final int MONITORING_BACKEND_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Prometheus backend for monitoring * </pre> * * <code>PROMETHEUS = 1;</code> */ public static final int PROMETHEUS_VALUE = 1; /** * * * <pre> * Stackdriver/Cloud Monitoring backend for monitoring * </pre> * * <code>CLOUD_MONITORING = 2;</code> */ public static final int CLOUD_MONITORING_VALUE = 2; 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 MonitoringBackend 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 MonitoringBackend forNumber(int value) { switch (value) { case 0: return MONITORING_BACKEND_UNSPECIFIED; case 1: return PROMETHEUS; case 2: return CLOUD_MONITORING; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<MonitoringBackend> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<MonitoringBackend> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<MonitoringBackend>() { public MonitoringBackend findValueByNumber(int number) { return MonitoringBackend.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.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .getDescriptor() .getEnumTypes() .get(0); } private static final MonitoringBackend[] VALUES = values(); public static MonitoringBackend 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 MonitoringBackend(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend) } public static final int BACKENDS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<java.lang.Integer> backends_; private static final com.google.protobuf.Internal.ListAdapter.Converter< java.lang.Integer, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend> backends_converter_ = new com.google.protobuf.Internal.ListAdapter.Converter< java.lang.Integer, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend>() { public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend convert(java.lang.Integer from) { com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend result = com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend.forNumber(from); return result == null ? com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend.UNRECOGNIZED : result; } }; /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return A list containing the backends. */ @java.lang.Override public java.util.List< com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend> getBackendsList() { return new com.google.protobuf.Internal.ListAdapter< java.lang.Integer, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend>(backends_, backends_converter_); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return The count of backends. */ @java.lang.Override public int getBackendsCount() { return backends_.size(); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param index The index of the element to return. * @return The backends at the given index. */ @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend getBackends(int index) { return backends_converter_.convert(backends_.get(index)); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return A list containing the enum numeric values on the wire for backends. */ @java.lang.Override public java.util.List<java.lang.Integer> getBackendsValueList() { return backends_; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param index The index of the value to return. * @return The enum numeric value on the wire of backends at the given index. */ @java.lang.Override public int getBackendsValue(int index) { return backends_.get(index); } private int backendsMemoizedSerializedSize; 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 (getBackendsList().size() > 0) { output.writeUInt32NoTag(10); output.writeUInt32NoTag(backendsMemoizedSerializedSize); } for (int i = 0; i < backends_.size(); i++) { output.writeEnumNoTag(backends_.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 < backends_.size(); i++) { dataSize += com.google.protobuf.CodedOutputStream.computeEnumSizeNoTag(backends_.get(i)); } size += dataSize; if (!getBackendsList().isEmpty()) { size += 1; size += com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(dataSize); } backendsMemoizedSerializedSize = 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.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring)) { return super.equals(obj); } com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring other = (com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) obj; if (!backends_.equals(other.backends_)) 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 (getBackendsCount() > 0) { hash = (37 * hash) + BACKENDS_FIELD_NUMBER; hash = (53 * hash) + backends_.hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring 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.configmanagement.v1beta.PolicyControllerMonitoring parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring 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.configmanagement.v1beta.PolicyControllerMonitoring parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring 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.configmanagement.v1beta.PolicyControllerMonitoring parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring 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.configmanagement.v1beta.PolicyControllerMonitoring parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring 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.configmanagement.v1beta.PolicyControllerMonitoring 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> * PolicyControllerMonitoring specifies the backends Policy Controller should * export metrics to. For example, to specify metrics should be exported to * Cloud Monitoring and Prometheus, specify * backends: ["cloudmonitoring", "prometheus"] * </pre> * * Protobuf type {@code google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoringOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.gkehub.configmanagement.v1beta.ConfigManagementProto .internal_static_google_cloud_gkehub_configmanagement_v1beta_PolicyControllerMonitoring_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.gkehub.configmanagement.v1beta.ConfigManagementProto .internal_static_google_cloud_gkehub_configmanagement_v1beta_PolicyControllerMonitoring_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.class, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.Builder .class); } // Construct using // com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; backends_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.gkehub.configmanagement.v1beta.ConfigManagementProto .internal_static_google_cloud_gkehub_configmanagement_v1beta_PolicyControllerMonitoring_descriptor; } @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring getDefaultInstanceForType() { return com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .getDefaultInstance(); } @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring build() { com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring buildPartial() { com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring result = new com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring result) { if (((bitField0_ & 0x00000001) != 0)) { backends_ = java.util.Collections.unmodifiableList(backends_); bitField0_ = (bitField0_ & ~0x00000001); } result.backends_ = backends_; } private void buildPartial0( com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring 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.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) { return mergeFrom( (com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring other) { if (other == com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .getDefaultInstance()) return this; if (!other.backends_.isEmpty()) { if (backends_.isEmpty()) { backends_ = other.backends_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureBackendsIsMutable(); backends_.addAll(other.backends_); } 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(); ensureBackendsIsMutable(); backends_.add(tmpRaw); break; } // case 8 case 10: { int length = input.readRawVarint32(); int oldLimit = input.pushLimit(length); while (input.getBytesUntilLimit() > 0) { int tmpRaw = input.readEnum(); ensureBackendsIsMutable(); backends_.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> backends_ = java.util.Collections.emptyList(); private void ensureBackendsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { backends_ = new java.util.ArrayList<java.lang.Integer>(backends_); bitField0_ |= 0x00000001; } } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return A list containing the backends. */ public java.util.List< com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend> getBackendsList() { return new com.google.protobuf.Internal.ListAdapter< java.lang.Integer, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend>(backends_, backends_converter_); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return The count of backends. */ public int getBackendsCount() { return backends_.size(); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param index The index of the element to return. * @return The backends at the given index. */ public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend getBackends(int index) { return backends_converter_.convert(backends_.get(index)); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param index The index to set the value at. * @param value The backends to set. * @return This builder for chaining. */ public Builder setBackends( int index, com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend value) { if (value == null) { throw new NullPointerException(); } ensureBackendsIsMutable(); backends_.set(index, value.getNumber()); onChanged(); return this; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param value The backends to add. * @return This builder for chaining. */ public Builder addBackends( com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend value) { if (value == null) { throw new NullPointerException(); } ensureBackendsIsMutable(); backends_.add(value.getNumber()); onChanged(); return this; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param values The backends to add. * @return This builder for chaining. */ public Builder addAllBackends( java.lang.Iterable< ? extends com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend> values) { ensureBackendsIsMutable(); for (com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring .MonitoringBackend value : values) { backends_.add(value.getNumber()); } onChanged(); return this; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return This builder for chaining. */ public Builder clearBackends() { backends_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @return A list containing the enum numeric values on the wire for backends. */ public java.util.List<java.lang.Integer> getBackendsValueList() { return java.util.Collections.unmodifiableList(backends_); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param index The index of the value to return. * @return The enum numeric value on the wire of backends at the given index. */ public int getBackendsValue(int index) { return backends_.get(index); } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param index The index to set the value at. * @param value The enum numeric value on the wire for backends to set. * @return This builder for chaining. */ public Builder setBackendsValue(int index, int value) { ensureBackendsIsMutable(); backends_.set(index, value); onChanged(); return this; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param value The enum numeric value on the wire for backends to add. * @return This builder for chaining. */ public Builder addBackendsValue(int value) { ensureBackendsIsMutable(); backends_.add(value); onChanged(); return this; } /** * * * <pre> * Specifies the list of backends Policy Controller will export to. * An empty list would effectively disable metrics export. * </pre> * * <code> * repeated .google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring.MonitoringBackend backends = 1; * </code> * * @param values The enum numeric values on the wire for backends to add. * @return This builder for chaining. */ public Builder addAllBackendsValue(java.lang.Iterable<java.lang.Integer> values) { ensureBackendsIsMutable(); for (int value : values) { backends_.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.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) } // @@protoc_insertion_point(class_scope:google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring) private static final com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring(); } public static com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<PolicyControllerMonitoring> PARSER = new com.google.protobuf.AbstractParser<PolicyControllerMonitoring>() { @java.lang.Override public PolicyControllerMonitoring 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<PolicyControllerMonitoring> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<PolicyControllerMonitoring> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.gkehub.configmanagement.v1beta.PolicyControllerMonitoring getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/directory-studio
37,696
tests/test.integration.ui/src/main/java/org/apache/directory/studio/test/integration/ui/BrowserTest.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.test.integration.ui; import static org.apache.directory.studio.test.integration.junit5.TestFixture.ALIAS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.CONTEXT_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_IP_HOST_NUMBER; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_TRAILING_EQUALS_CHARACTER; import static org.apache.directory.studio.test.integration.junit5.TestFixture.DN_WITH_TRAILING_EQUALS_CHARACTER_HEX_PAIR_ESCAPED; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MISC_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.MULTI_VALUED_RDN_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.REFERRAL_TO_USERS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER1_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER2_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USER3_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.USERS_DN; import static org.apache.directory.studio.test.integration.junit5.TestFixture.dn; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.studio.connection.core.Connection; import org.apache.directory.studio.connection.core.Connection.AliasDereferencingMethod; import org.apache.directory.studio.connection.core.Connection.ReferralHandlingMethod; import org.apache.directory.studio.ldapbrowser.core.BrowserCoreMessages; import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin; import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry; import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection; import org.apache.directory.studio.ldapbrowser.core.model.impl.Bookmark; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIConstants; import org.apache.directory.studio.ldapbrowser.ui.BrowserUIPlugin; import org.apache.directory.studio.ldapbrowser.ui.editors.entry.EntryEditor; import org.apache.directory.studio.test.integration.junit5.LdapServerType; import org.apache.directory.studio.test.integration.junit5.LdapServersSource; import org.apache.directory.studio.test.integration.junit5.LdapServersSource.Mode; import org.apache.directory.studio.test.integration.junit5.TestLdapServer; import org.apache.directory.studio.test.integration.ui.bots.DeleteDialogBot; import org.apache.directory.studio.test.integration.ui.bots.EntryEditorBot; import org.apache.directory.studio.test.integration.ui.bots.ReferralDialogBot; import org.apache.directory.studio.test.integration.ui.utils.JobWatcher; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable; import org.eclipse.swtbot.swt.finder.results.VoidResult; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPropertyListener; import org.eclipse.ui.PlatformUI; import org.junit.jupiter.params.ParameterizedTest; /** * Tests the LDAP browser. * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$, $Date$ */ public class BrowserTest extends AbstractTestBase { /** * Test for DIRSTUDIO-463. * * When expanding an entry in the browser only one search request * should be send to the server */ @ParameterizedTest @LdapServersSource public void testOnlyOneSearchRequestWhenExpandingEntry( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( CONTEXT_DN ) ); // get number of search requests before expanding the entry String text = searchLogsViewBot.getSearchLogsText(); int countMatchesBefore = StringUtils.countMatches( text, "#!SEARCH REQUEST" ); // expand browserViewBot.expandEntry( path( CONTEXT_DN ) ); browserViewBot.waitForEntry( path( USERS_DN ) ); // get number of search requests after expanding the entry text = searchLogsViewBot.getSearchLogsText(); int countMatchesAfter = StringUtils.countMatches( text, "#!SEARCH REQUEST" ); assertEquals( 1, countMatchesAfter - countMatchesBefore, "Expected exactly 1 search request" ); assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-512. * * Verify minimum UI updates when deleting multiple entries. */ @ParameterizedTest @LdapServersSource public void testDeleteDoesNotUpdateUI( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); browserViewBot.expandEntry( path( USERS_DN ) ); long fireCount0 = EventRegistry.getFireCount(); // delete String[] children = new String[] { "uid=user.1", "uid=user.2", "uid=user.3", "uid=user.4", "uid=user.5", "uid=user.6", "uid=user.7", "uid=user.8" }; browserViewBot.selectChildrenOfEntry( children, path( USERS_DN ) ); DeleteDialogBot deleteDialog = browserViewBot.openDeleteDialog(); deleteDialog.clickOkButton(); browserViewBot.selectEntry( path( USERS_DN ) ); long fireCount1 = EventRegistry.getFireCount(); // verify that only two events were fired during deletion long fireCount = fireCount1 - fireCount0; assertEquals( 2, fireCount, "Only 2 event firings expected when deleting multiple entries." ); } /** * Test for DIRSTUDIO-575. * * When opening a bookmark the entry editor should be opened and the * bookmark entry's attributes should be displayed. */ @ParameterizedTest @LdapServersSource public void testBookmark( TestLdapServer server ) throws Exception { // create a bookmark Connection connection = connectionsViewBot.createTestConnection( server ); IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); browserConnection.getBookmarkManager().addBookmark( new Bookmark( browserConnection, USER1_DN, "Existing Bookmark" ) ); // select the bookmark browserViewBot.selectEntry( "Bookmarks", "Existing Bookmark" ); // check that entry editor was opened and attributes are visible EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); String dn = entryEditorBot.getDnText(); assertEquals( "DN: " + USER1_DN.getName(), dn ); List<String> attributeValues = entryEditorBot.getAttributeValues(); assertEquals( 23, attributeValues.size() ); assertTrue( attributeValues.contains( "uid: user.1" ) ); assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. */ @ParameterizedTest @LdapServersSource public void testRefreshParent( TestLdapServer server ) throws Exception { // check the entry doesn't exist yet connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( MISC_DN ) ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // add the entry directly in the server server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); conn.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh parent browserViewBot.selectEntry( path( MISC_DN ) ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( path( MISC_DN ) ); assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); browserViewBot.selectEntry( path( refreshDn ) ); // delete the entry directly in the server server.withAdminConnection( conn -> { conn.delete( refreshDn ); } ); // check the entry still is visible in the tree assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh parent browserViewBot.selectEntry( path( MISC_DN ) ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( path( MISC_DN ) ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. * * @throws Exception */ @ParameterizedTest @LdapServersSource public void testRefreshContextEntry( TestLdapServer server ) throws Exception { // check the entry doesn't exist yet connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( MISC_DN ) ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // add the entry directly in the server server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); conn.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh context entry browserViewBot.selectEntry( path( CONTEXT_DN ) ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( path( MISC_DN ) ); assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); browserViewBot.selectEntry( path( refreshDn ) ); // delete the entry directly in the server server.withAdminConnection( connection -> { connection.delete( refreshDn ); } ); // check the entry still is visible in the tree assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh context entry browserViewBot.selectEntry( path( CONTEXT_DN ) ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( path( MISC_DN ) ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. */ @ParameterizedTest @LdapServersSource public void testRefreshRootDSE( TestLdapServer server ) throws Exception { // check the entry doesn't exist yet connectionsViewBot.createTestConnection( server ); browserViewBot.expandEntry( path( MISC_DN ) ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // add the entry directly in the server server.withAdminConnection( connection -> { Entry entry = new DefaultEntry( connection.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); connection.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh Root DSE browserViewBot.selectEntry( ROOT_DSE_PATH ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( path( MISC_DN ) ); assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); browserViewBot.selectEntry( path( refreshDn ) ); // delete the entry directly in the server server.withAdminConnection( connection -> { connection.delete( refreshDn ); } ); // check the entry still is now visible in the tree assertTrue( browserViewBot.existsEntry( path( refreshDn ) ) ); // refresh Root DSE browserViewBot.selectEntry( ROOT_DSE_PATH ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( path( MISC_DN ) ); assertFalse( browserViewBot.existsEntry( path( refreshDn ) ) ); } /** * Test for DIRSTUDIO-481. * * Check proper operation of refresh action. */ @ParameterizedTest @LdapServersSource public void testRefreshSearchContinuation( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); Dn refreshDn = dn( "cn=refresh", MISC_DN ); String[] pathToReferral = pathWithRefLdapUrl( server, MISC_DN ); String[] pathToRefreshViaReferral = path( pathToReferral, "cn=refresh" ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_REFERRALS_HANDLING_METHOD, ReferralHandlingMethod.FOLLOW_MANUALLY.ordinal() ); browserViewBot.selectEntry( ROOT_DSE_PATH ); browserViewBot.refresh(); // check the entry doesn't exist yet ReferralDialogBot refDialog = browserViewBot.expandEntryExpectingReferralDialog( pathToReferral ); refDialog.clickOkButton(); assertFalse( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); // add the entry directly in the server server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( refreshDn ); entry.add( "objectClass", "top", "person" ); entry.add( "cn", "refresh" ); entry.add( "sn", "refresh" ); conn.add( entry ); } ); // check the entry still isn't visible in the tree assertFalse( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); // refresh search continuation browserViewBot.selectEntry( pathToReferral ); browserViewBot.refresh(); // check the entry exists now browserViewBot.expandEntry( pathToReferral ); assertTrue( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); browserViewBot.selectEntry( pathToRefreshViaReferral ); // delete the entry directly in the server server.withAdminConnection( conn -> { conn.delete( refreshDn ); } ); // check the entry still is visible in the tree assertTrue( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); // refresh search continuation browserViewBot.selectEntry( pathToReferral ); browserViewBot.refresh(); // check the entry doesn't exist now browserViewBot.expandEntry( pathToReferral ); assertFalse( browserViewBot.existsEntry( pathToRefreshViaReferral ) ); } /** * Test for DIRSTUDIO-591. * (Error reading objects with # in DN) */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testBrowseDnWithSharpAndHexSequence( TestLdapServer server ) throws Exception { Dn dn = DN_WITH_LEADING_SHARP_BACKSLASH_PREFIXED; if ( server.getType() == LdapServerType.OpenLdap || server.getType() == LdapServerType.Fedora389ds ) { dn = DN_WITH_LEADING_SHARP_HEX_PAIR_ESCAPED; } connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-1172: Studio doesn't display entries with trailing =. */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testBrowseDnWithTrailingEqualsCharacter( TestLdapServer server ) throws Exception { Dn dn = DN_WITH_TRAILING_EQUALS_CHARACTER; if ( server.getType() == LdapServerType.OpenLdap ) { dn = DN_WITH_TRAILING_EQUALS_CHARACTER_HEX_PAIR_ESCAPED; } connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); } /** * Test for DIRSTUDIO-1172: Studio doesn't display entries with trailing =. */ @ParameterizedTest @LdapServersSource(except = { LdapServerType.OpenLdap, LdapServerType.Fedora389ds }, reason = "Empty RDN value is not supported by OpenLDAP and 389ds") public void testBrowseDnWithEmptyRdnValue( TestLdapServer server ) throws Exception { Dn dn = dn( "cn=nghZwwtHgxgyvVbTQCYyeY+email=", MISC_DN ); server.withAdminConnection( connection -> { Entry entry = new DefaultEntry( connection.getSchemaManager() ); entry.setDn( dn ); entry.add( "objectClass", "top", "person", "extensibleObject" ); entry.add( "cn", "nghZwwtHgxgyvVbTQCYyeY" ); entry.add( "sn", "nghZwwtHgxgyvVbTQCYyeY" ); entry.add( "email", "" ); connection.add( entry ); } ); connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); } /** * Test for DIRSTUDIO-1151: DN with backslash not displayed */ @ParameterizedTest @LdapServersSource(mode = Mode.All) public void testBrowseDnWithBackslash( TestLdapServer server ) throws Exception { Dn dn = DN_WITH_ESCAPED_CHARACTERS_BACKSLASH_PREFIXED; if ( server.getType() == LdapServerType.OpenLdap || server.getType() == LdapServerType.Fedora389ds ) { dn = DN_WITH_ESCAPED_CHARACTERS_HEX_PAIR_ESCAPED; } connectionsViewBot.createTestConnection( server ); // expand parent and verify entry is visible browserViewBot.expandEntry( path( dn.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); browserViewBot.selectEntry( path( dn ) ); // refresh entry and verify child is still visible browserViewBot.selectEntry( path( dn.getParent() ) ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( path( dn ) ) ); } /** * Test for DIRSTUDIO-597. * (Modification sent to the server while browsing through the DIT and refreshing entries) * * @throws Exception */ @ParameterizedTest @LdapServersSource public void testNoModificationWhileBrowsingAndRefreshing( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); boolean errorDialogAutomatedMode = ErrorDialog.AUTOMATED_MODE; ErrorDialog.AUTOMATED_MODE = false; String text = modificationLogsViewBot.getModificationLogsText(); assertEquals( "", text ); try { assertTrue( browserViewBot.existsEntry( path( MULTI_VALUED_RDN_DN ) ) ); for ( int i = 0; i < 5; i++ ) { // select entry and refresh browserViewBot.selectEntry( path( MULTI_VALUED_RDN_DN ) ); browserViewBot.refresh(); // select parent and refresh browserViewBot.selectEntry( path( MULTI_VALUED_RDN_DN.getParent() ) ); browserViewBot.refresh(); } } finally { // reset flag ErrorDialog.AUTOMATED_MODE = errorDialogAutomatedMode; } // check that modification logs is still empty // to ensure that no modification was sent to the server assertEquals( "", modificationLogsViewBot.getModificationLogsText(), "No modification expected" ); } /** * Test for DIRSTUDIO-603, DIRSHARED-41. * (Error browsing/entering rfc2307 compliant host entry.) */ @ParameterizedTest @LdapServersSource public void testBrowseDnWithIpHostNumber( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); assertTrue( browserViewBot.existsEntry( path( DN_WITH_IP_HOST_NUMBER ) ) ); browserViewBot.selectEntry( path( DN_WITH_IP_HOST_NUMBER ) ); } /** * DIRSTUDIO-637: copy/paste of attributes no longer works. * Test copy/paste of a value to a bookmark. */ @ParameterizedTest @LdapServersSource public void testCopyPasteValueToBookmark( TestLdapServer server ) throws Exception { // create a bookmark Connection connection = connectionsViewBot.createTestConnection( server ); IBrowserConnection browserConnection = BrowserCorePlugin.getDefault().getConnectionManager() .getBrowserConnection( connection ); browserConnection.getBookmarkManager().addBookmark( new Bookmark( browserConnection, MULTI_VALUED_RDN_DN, "My Bookmark" ) ); // copy a value browserViewBot.selectEntry( path( USER1_DN ) ); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); entryEditorBot.activate(); entryEditorBot.copyValue( "uid", "user.1" ); // select the bookmark browserViewBot.selectEntry( "Bookmarks", "My Bookmark" ); entryEditorBot = studioBot.getEntryEditorBot( MULTI_VALUED_RDN_DN.getName() ); entryEditorBot.activate(); assertEquals( 8, entryEditorBot.getAttributeValues().size() ); // paste the value JobWatcher watcher = new JobWatcher( BrowserCoreMessages.jobs__execute_ldif_name ); browserViewBot.paste(); watcher.waitUntilDone(); // assert pasted value visible in editor assertEquals( 9, entryEditorBot.getAttributeValues().size() ); entryEditorBot.getAttributeValues().contains( "uid: user.1" ); // assert pasted value was written to directory server.withAdminConnection( conn -> { Entry entry = conn.lookup( MULTI_VALUED_RDN_DN ); assertTrue( entry.contains( "uid", "user.1" ) ); } ); } /** * Test for DIRSTUDIO-1121. * * Verify input is set only once when entry is selected. */ @ParameterizedTest @LdapServersSource public void testSetInputOnlyOnce( TestLdapServer server ) throws Exception { /* * This test fails on Jenkins Windows Server, to be investigated... */ // Assume.assumeFalse( StudioSystemUtils.IS_OS_WINDOWS_SERVER ); connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); browserViewBot.expandEntry( path( USERS_DN ) ); // verify link-with-editor is enabled assertTrue( BrowserUIPlugin.getDefault().getPreferenceStore() .getBoolean( BrowserUIConstants.PREFERENCE_BROWSER_LINK_WITH_EDITOR ) ); // setup counter and listener to record entry editor input changes final AtomicInteger counter = new AtomicInteger(); UIThreadRunnable.syncExec( new VoidResult() { public void run() { try { IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage() .getActiveEditor(); editor.addPropertyListener( new IPropertyListener() { @Override public void propertyChanged( Object source, int propId ) { if ( source instanceof EntryEditor && propId == BrowserUIConstants.INPUT_CHANGED ) { counter.incrementAndGet(); } } } ); } catch ( Exception e ) { throw new RuntimeException( e ); } } } ); // select 3 different entries, select one twice should not set the input again browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.selectEntry( path( USER1_DN ) ); browserViewBot.selectEntry( path( USER2_DN ) ); browserViewBot.selectEntry( path( USER2_DN ) ); browserViewBot.selectEntry( path( USER3_DN ) ); browserViewBot.selectEntry( path( USER3_DN ) ); // verify that input was only set 3 times. assertEquals( 3, counter.get(), "Only 3 input changes expected." ); // reset counter counter.set( 0 ); // use navigation history to go back and forth, each step should set input only once studioBot.navigationHistoryBack(); browserViewBot.waitUntilEntryIsSelected( USER2_DN.getRdn().getName() ); studioBot.navigationHistoryBack(); browserViewBot.waitUntilEntryIsSelected( USER1_DN.getRdn().getName() ); studioBot.navigationHistoryForward(); browserViewBot.waitUntilEntryIsSelected( USER2_DN.getRdn().getName() ); studioBot.navigationHistoryForward(); browserViewBot.waitUntilEntryIsSelected( USER3_DN.getRdn().getName() ); // verify that input was only set 4 times. assertEquals( 4, counter.get(), "Only 4 input changes expected." ); } /** * Test for DIRSTUDIO-987, DIRSTUDIO-271. * * Browse and refresh entry with multi-valued RDN with same attribute type. */ @ParameterizedTest @LdapServersSource(except = LdapServerType.OpenLdap, reason = "Multi-valued RDN with same attribute is not supported by OpenLDAP") public void testBrowseAndRefreshEntryWithMvRdn( TestLdapServer server ) throws Exception { Dn entryDn = dn( "l=Berlin+l=Brandenburger Tor+l=de+l=eu", MISC_DN ); Dn childDn = dn( "cn=A", entryDn ); server.withAdminConnection( connection -> { Entry entry1 = new DefaultEntry( connection.getSchemaManager() ); entry1.setDn( entryDn ); entry1.add( "objectClass", "top", "locality" ); entry1.add( "l", "eu", "de", "Berlin", "Brandenburger Tor" ); connection.add( entry1 ); Entry entry2 = new DefaultEntry( connection.getSchemaManager() ); entry2.setDn( childDn ); entry2.add( "objectClass", "top", "person" ); entry2.add( "cn", "A" ); entry2.add( "sn", "A" ); connection.add( entry2 ); } ); String[] pathToParent = path( entryDn.getParent() ); String[] pathToEntry = path( entryDn ); String[] pathToChild = path( childDn ); connectionsViewBot.createTestConnection( server ); // expand parent and verify entry is visible browserViewBot.expandEntry( pathToParent ); assertTrue( browserViewBot.existsEntry( pathToEntry ) ); browserViewBot.selectEntry( pathToEntry ); // expand entry and verify child is visible browserViewBot.expandEntry( pathToEntry ); assertTrue( browserViewBot.existsEntry( pathToChild ) ); browserViewBot.selectEntry( pathToChild ); // refresh entry and verify child is still visible browserViewBot.selectEntry( pathToEntry ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( pathToChild ) ); // refresh parent and verify entry is still visible browserViewBot.selectEntry( pathToParent ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( pathToEntry ) ); // expand entry and verify child is visible browserViewBot.expandEntry( pathToEntry ); assertTrue( browserViewBot.existsEntry( pathToChild ) ); } @ParameterizedTest @LdapServersSource public void testBrowseAliasEntry( TestLdapServer server ) throws Exception { // disable alias dereferencing Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_ALIASES_DEREFERENCING_METHOD, AliasDereferencingMethod.NEVER.ordinal() ); browserViewBot.expandEntry( path( ALIAS_DN.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( ALIAS_DN ) ) ); browserViewBot.selectEntry( path( ALIAS_DN ) ); } @ParameterizedTest @LdapServersSource public void testBrowseReferralEntry( TestLdapServer server ) throws Exception { // enable ManageDsaIT control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_MANAGE_DSA_IT, true ); browserViewBot.expandEntry( path( REFERRAL_TO_USERS_DN.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( REFERRAL_TO_USERS_DN ) ) ); browserViewBot.selectEntry( path( REFERRAL_TO_USERS_DN ) ); } @ParameterizedTest @LdapServersSource(only = LdapServerType.ApacheDS, reason = "ApacheDS specific test") public void testBrowseSubEntry( TestLdapServer server ) throws Exception { Dn subentryDn = dn( "cn=subentry", MISC_DN ); // enable Subentries control Connection connection = connectionsViewBot.createTestConnection( server ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_FETCH_SUBENTRIES, true ); browserViewBot.expandEntry( path( subentryDn.getParent() ) ); assertTrue( browserViewBot.existsEntry( path( subentryDn ) ) ); browserViewBot.selectEntry( path( subentryDn ) ); } @ParameterizedTest @LdapServersSource public void testBrowseWithPagingWithScrollMode( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); // enable Simple Paged Results control connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_PAGED_SEARCH, true ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_PAGED_SEARCH_SIZE, 3 ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_PAGED_SEARCH_SCROLL_MODE, true ); // 1st page browserViewBot.expandEntry( path( USERS_DN ) ); assertFalse( browserViewBot.existsEntry( path( USERS_DN, "--- Top Page ---" ) ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "--- Next Page ---" ) ) ); // next page browserViewBot.selectEntry( path( USERS_DN, "--- Next Page ---" ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "--- Top Page ---" ) ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "--- Next Page ---" ) ) ); // last page browserViewBot.selectEntry( path( USERS_DN, "--- Next Page ---" ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "--- Top Page ---" ) ) ); assertFalse( browserViewBot.existsEntry( path( USERS_DN, "--- Next Page ---" ) ) ); // back to top browserViewBot.selectEntry( path( USERS_DN, "--- Top Page ---" ) ); assertFalse( browserViewBot.existsEntry( path( USERS_DN, "--- Top Page ---" ) ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "--- Next Page ---" ) ) ); } @ParameterizedTest @LdapServersSource public void testBrowseWithPagingWithoutScrollMode( TestLdapServer server ) throws Exception { Connection connection = connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); // enable Simple Paged Results control connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_PAGED_SEARCH, true ); connection.getConnectionParameter().setExtendedIntProperty( IBrowserConnection.CONNECTION_PARAMETER_PAGED_SEARCH_SIZE, 3 ); connection.getConnectionParameter().setExtendedBoolProperty( IBrowserConnection.CONNECTION_PARAMETER_PAGED_SEARCH_SCROLL_MODE, false ); browserViewBot.expandEntry( path( USERS_DN ) ); assertFalse( browserViewBot.existsEntry( path( USERS_DN, "--- Top Page ---" ) ) ); assertFalse( browserViewBot.existsEntry( path( USERS_DN, "--- Next Page ---" ) ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN ) ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "uid=user.1" ) ) ); assertTrue( browserViewBot.existsEntry( path( USERS_DN, "uid=user.8" ) ) ); } @ParameterizedTest @LdapServersSource public void x( TestLdapServer server ) throws Exception { connectionsViewBot.createTestConnection( server ); browserViewBot.selectEntry( path( USERS_DN ) ); browserViewBot.expandEntry( path( USERS_DN ) ); browserViewBot.selectEntry( path( USER1_DN ) ); EntryEditorBot entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); List<String> attributeValues = entryEditorBot.getAttributeValues(); assertEquals( 23, attributeValues.size() ); assertTrue( attributeValues.contains( "uid: user.1" ) ); assertTrue( entryEditorBot.getAttributeValues().contains( "initials: AA" ) ); DeleteDialogBot deleteDialog = browserViewBot.openDeleteDialog(); deleteDialog.clickOkButton(); browserViewBot.selectEntry( path( USERS_DN ) ); assertFalse( browserViewBot.existsEntry( path( USER1_DN ) ) ); server.withAdminConnection( conn -> { Entry entry = new DefaultEntry( conn.getSchemaManager() ); entry.setDn( USER1_DN ); entry.add( "objectClass", "top", "person", "organizationalPerson", "inetOrgPerson" ); entry.add( "uid", "user.1" ); entry.add( "givenName", "Foo" ); entry.add( "sn", "Bar" ); entry.add( "cn", "Foo Bar" ); entry.add( "initials", "FB" ); conn.add( entry ); } ); browserViewBot.refresh(); assertTrue( browserViewBot.existsEntry( path( USER1_DN ) ) ); browserViewBot.selectEntry( path( USER1_DN ) ); entryEditorBot = studioBot.getEntryEditorBot( USER1_DN.getName() ); attributeValues = entryEditorBot.getAttributeValues(); assertEquals( 9, attributeValues.size() ); assertTrue( attributeValues.contains( "uid: user.1" ) ); assertTrue( entryEditorBot.getAttributeValues().contains( "initials: FB" ) ); } }
googleapis/google-api-java-client-services
37,795
clients/google-api-services-testing/v1/1.30.1/com/google/api/services/testing/Testing.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.testing; /** * Service definition for Testing (v1). * * <p> * Allows developers to run automated tests for their mobile applications on Google infrastructure. * </p> * * <p> * For more information about this service, see the * <a href="https://developers.google.com/cloud-test-lab/" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link TestingRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class Testing extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.30.10 of the Cloud Testing API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://testing.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = ""; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Testing(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ Testing(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the ApplicationDetailService collection. * * <p>The typical use is:</p> * <pre> * {@code Testing testing = new Testing(...);} * {@code Testing.ApplicationDetailService.List request = testing.applicationDetailService().list(parameters ...)} * </pre> * * @return the resource collection */ public ApplicationDetailService applicationDetailService() { return new ApplicationDetailService(); } /** * The "applicationDetailService" collection of methods. */ public class ApplicationDetailService { /** * Gets the details of an Android application APK. * * Create a request for the method "applicationDetailService.getApkDetails". * * This request holds the parameters needed by the testing server. After setting any optional * parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation. * * @param content the {@link com.google.api.services.testing.model.FileReference} * @return the request */ public GetApkDetails getApkDetails(com.google.api.services.testing.model.FileReference content) throws java.io.IOException { GetApkDetails result = new GetApkDetails(content); initialize(result); return result; } public class GetApkDetails extends TestingRequest<com.google.api.services.testing.model.GetApkDetailsResponse> { private static final String REST_PATH = "v1/applicationDetailService/getApkDetails"; /** * Gets the details of an Android application APK. * * Create a request for the method "applicationDetailService.getApkDetails". * * This request holds the parameters needed by the the testing server. After setting any optional * parameters, call the {@link GetApkDetails#execute()} method to invoke the remote operation. <p> * {@link GetApkDetails#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientR * equest)} must be called to initialize this instance immediately after invoking the constructor. * </p> * * @param content the {@link com.google.api.services.testing.model.FileReference} * @since 1.13 */ protected GetApkDetails(com.google.api.services.testing.model.FileReference content) { super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.GetApkDetailsResponse.class); } @Override public GetApkDetails set$Xgafv(java.lang.String $Xgafv) { return (GetApkDetails) super.set$Xgafv($Xgafv); } @Override public GetApkDetails setAccessToken(java.lang.String accessToken) { return (GetApkDetails) super.setAccessToken(accessToken); } @Override public GetApkDetails setAlt(java.lang.String alt) { return (GetApkDetails) super.setAlt(alt); } @Override public GetApkDetails setCallback(java.lang.String callback) { return (GetApkDetails) super.setCallback(callback); } @Override public GetApkDetails setFields(java.lang.String fields) { return (GetApkDetails) super.setFields(fields); } @Override public GetApkDetails setKey(java.lang.String key) { return (GetApkDetails) super.setKey(key); } @Override public GetApkDetails setOauthToken(java.lang.String oauthToken) { return (GetApkDetails) super.setOauthToken(oauthToken); } @Override public GetApkDetails setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetApkDetails) super.setPrettyPrint(prettyPrint); } @Override public GetApkDetails setQuotaUser(java.lang.String quotaUser) { return (GetApkDetails) super.setQuotaUser(quotaUser); } @Override public GetApkDetails setUploadType(java.lang.String uploadType) { return (GetApkDetails) super.setUploadType(uploadType); } @Override public GetApkDetails setUploadProtocol(java.lang.String uploadProtocol) { return (GetApkDetails) super.setUploadProtocol(uploadProtocol); } @Override public GetApkDetails set(String parameterName, Object value) { return (GetApkDetails) super.set(parameterName, value); } } } /** * An accessor for creating requests from the Projects collection. * * <p>The typical use is:</p> * <pre> * {@code Testing testing = new Testing(...);} * {@code Testing.Projects.List request = testing.projects().list(parameters ...)} * </pre> * * @return the resource collection */ public Projects projects() { return new Projects(); } /** * The "projects" collection of methods. */ public class Projects { /** * An accessor for creating requests from the TestMatrices collection. * * <p>The typical use is:</p> * <pre> * {@code Testing testing = new Testing(...);} * {@code Testing.TestMatrices.List request = testing.testMatrices().list(parameters ...)} * </pre> * * @return the resource collection */ public TestMatrices testMatrices() { return new TestMatrices(); } /** * The "testMatrices" collection of methods. */ public class TestMatrices { /** * Cancels unfinished test executions in a test matrix. This call returns immediately and * cancellation proceeds asynchronously. If the matrix is already final, this operation will have no * effect. May return any of the following canonical error codes: - PERMISSION_DENIED - if the user * is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - * if the Test Matrix does not exist * * Create a request for the method "testMatrices.cancel". * * This request holds the parameters needed by the testing server. After setting any optional * parameters, call the {@link Cancel#execute()} method to invoke the remote operation. * * @param projectId Cloud project that owns the test. * @param testMatrixId Test matrix that will be canceled. * @return the request */ public Cancel cancel(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException { Cancel result = new Cancel(projectId, testMatrixId); initialize(result); return result; } public class Cancel extends TestingRequest<com.google.api.services.testing.model.CancelTestMatrixResponse> { private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}:cancel"; /** * Cancels unfinished test executions in a test matrix. This call returns immediately and * cancellation proceeds asynchronously. If the matrix is already final, this operation will have * no effect. May return any of the following canonical error codes: - PERMISSION_DENIED - if the * user is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - * NOT_FOUND - if the Test Matrix does not exist * * Create a request for the method "testMatrices.cancel". * * This request holds the parameters needed by the the testing server. After setting any optional * parameters, call the {@link Cancel#execute()} method to invoke the remote operation. <p> {@link * Cancel#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param projectId Cloud project that owns the test. * @param testMatrixId Test matrix that will be canceled. * @since 1.13 */ protected Cancel(java.lang.String projectId, java.lang.String testMatrixId) { super(Testing.this, "POST", REST_PATH, null, com.google.api.services.testing.model.CancelTestMatrixResponse.class); this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified."); this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId must be specified."); } @Override public Cancel set$Xgafv(java.lang.String $Xgafv) { return (Cancel) super.set$Xgafv($Xgafv); } @Override public Cancel setAccessToken(java.lang.String accessToken) { return (Cancel) super.setAccessToken(accessToken); } @Override public Cancel setAlt(java.lang.String alt) { return (Cancel) super.setAlt(alt); } @Override public Cancel setCallback(java.lang.String callback) { return (Cancel) super.setCallback(callback); } @Override public Cancel setFields(java.lang.String fields) { return (Cancel) super.setFields(fields); } @Override public Cancel setKey(java.lang.String key) { return (Cancel) super.setKey(key); } @Override public Cancel setOauthToken(java.lang.String oauthToken) { return (Cancel) super.setOauthToken(oauthToken); } @Override public Cancel setPrettyPrint(java.lang.Boolean prettyPrint) { return (Cancel) super.setPrettyPrint(prettyPrint); } @Override public Cancel setQuotaUser(java.lang.String quotaUser) { return (Cancel) super.setQuotaUser(quotaUser); } @Override public Cancel setUploadType(java.lang.String uploadType) { return (Cancel) super.setUploadType(uploadType); } @Override public Cancel setUploadProtocol(java.lang.String uploadProtocol) { return (Cancel) super.setUploadProtocol(uploadProtocol); } /** Cloud project that owns the test. */ @com.google.api.client.util.Key private java.lang.String projectId; /** Cloud project that owns the test. */ public java.lang.String getProjectId() { return projectId; } /** Cloud project that owns the test. */ public Cancel setProjectId(java.lang.String projectId) { this.projectId = projectId; return this; } /** Test matrix that will be canceled. */ @com.google.api.client.util.Key private java.lang.String testMatrixId; /** Test matrix that will be canceled. */ public java.lang.String getTestMatrixId() { return testMatrixId; } /** Test matrix that will be canceled. */ public Cancel setTestMatrixId(java.lang.String testMatrixId) { this.testMatrixId = testMatrixId; return this; } @Override public Cancel set(String parameterName, Object value) { return (Cancel) super.set(parameterName, value); } } /** * Creates and runs a matrix of tests according to the given specifications. Unsupported * environments will be returned in the state UNSUPPORTED. A test matrix is limited to use at most * 2000 devices in parallel. May return any of the following canonical error codes: - * PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if the * request is malformed or if the matrix tries to use too many simultaneous devices. * * Create a request for the method "testMatrices.create". * * This request holds the parameters needed by the testing server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param projectId The GCE project under which this job will run. * @param content the {@link com.google.api.services.testing.model.TestMatrix} * @return the request */ public Create create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) throws java.io.IOException { Create result = new Create(projectId, content); initialize(result); return result; } public class Create extends TestingRequest<com.google.api.services.testing.model.TestMatrix> { private static final String REST_PATH = "v1/projects/{projectId}/testMatrices"; /** * Creates and runs a matrix of tests according to the given specifications. Unsupported * environments will be returned in the state UNSUPPORTED. A test matrix is limited to use at most * 2000 devices in parallel. May return any of the following canonical error codes: - * PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if * the request is malformed or if the matrix tries to use too many simultaneous devices. * * Create a request for the method "testMatrices.create". * * This request holds the parameters needed by the the testing server. After setting any optional * parameters, call the {@link Create#execute()} method to invoke the remote operation. <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param projectId The GCE project under which this job will run. * @param content the {@link com.google.api.services.testing.model.TestMatrix} * @since 1.13 */ protected Create(java.lang.String projectId, com.google.api.services.testing.model.TestMatrix content) { super(Testing.this, "POST", REST_PATH, content, com.google.api.services.testing.model.TestMatrix.class); this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified."); } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** The GCE project under which this job will run. */ @com.google.api.client.util.Key private java.lang.String projectId; /** The GCE project under which this job will run. */ public java.lang.String getProjectId() { return projectId; } /** The GCE project under which this job will run. */ public Create setProjectId(java.lang.String projectId) { this.projectId = projectId; return this; } /** * A string id used to detect duplicated requests. Ids are automatically scoped to a * project, so users should ensure the ID is unique per-project. A UUID is recommended. * Optional, but strongly recommended. */ @com.google.api.client.util.Key private java.lang.String requestId; /** A string id used to detect duplicated requests. Ids are automatically scoped to a project, so users should ensure the ID is unique per-project. A UUID is recommended. Optional, but strongly recommended. */ public java.lang.String getRequestId() { return requestId; } /** * A string id used to detect duplicated requests. Ids are automatically scoped to a * project, so users should ensure the ID is unique per-project. A UUID is recommended. * Optional, but strongly recommended. */ public Create setRequestId(java.lang.String requestId) { this.requestId = requestId; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Checks the status of a test matrix. May return any of the following canonical error codes: - * PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the * request is malformed - NOT_FOUND - if the Test Matrix does not exist * * Create a request for the method "testMatrices.get". * * This request holds the parameters needed by the testing server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param projectId Cloud project that owns the test matrix. * @param testMatrixId Unique test matrix id which was assigned by the service. * @return the request */ public Get get(java.lang.String projectId, java.lang.String testMatrixId) throws java.io.IOException { Get result = new Get(projectId, testMatrixId); initialize(result); return result; } public class Get extends TestingRequest<com.google.api.services.testing.model.TestMatrix> { private static final String REST_PATH = "v1/projects/{projectId}/testMatrices/{testMatrixId}"; /** * Checks the status of a test matrix. May return any of the following canonical error codes: - * PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the * request is malformed - NOT_FOUND - if the Test Matrix does not exist * * Create a request for the method "testMatrices.get". * * This request holds the parameters needed by the the testing server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param projectId Cloud project that owns the test matrix. * @param testMatrixId Unique test matrix id which was assigned by the service. * @since 1.13 */ protected Get(java.lang.String projectId, java.lang.String testMatrixId) { super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestMatrix.class); this.projectId = com.google.api.client.util.Preconditions.checkNotNull(projectId, "Required parameter projectId must be specified."); this.testMatrixId = com.google.api.client.util.Preconditions.checkNotNull(testMatrixId, "Required parameter testMatrixId must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Cloud project that owns the test matrix. */ @com.google.api.client.util.Key private java.lang.String projectId; /** Cloud project that owns the test matrix. */ public java.lang.String getProjectId() { return projectId; } /** Cloud project that owns the test matrix. */ public Get setProjectId(java.lang.String projectId) { this.projectId = projectId; return this; } /** Unique test matrix id which was assigned by the service. */ @com.google.api.client.util.Key private java.lang.String testMatrixId; /** Unique test matrix id which was assigned by the service. */ public java.lang.String getTestMatrixId() { return testMatrixId; } /** Unique test matrix id which was assigned by the service. */ public Get setTestMatrixId(java.lang.String testMatrixId) { this.testMatrixId = testMatrixId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } } } /** * An accessor for creating requests from the TestEnvironmentCatalog collection. * * <p>The typical use is:</p> * <pre> * {@code Testing testing = new Testing(...);} * {@code Testing.TestEnvironmentCatalog.List request = testing.testEnvironmentCatalog().list(parameters ...)} * </pre> * * @return the resource collection */ public TestEnvironmentCatalog testEnvironmentCatalog() { return new TestEnvironmentCatalog(); } /** * The "testEnvironmentCatalog" collection of methods. */ public class TestEnvironmentCatalog { /** * Gets the catalog of supported test environments. May return any of the following canonical error * codes: - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment type * does not exist - INTERNAL - if an internal error occurred * * Create a request for the method "testEnvironmentCatalog.get". * * This request holds the parameters needed by the testing server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param environmentType Required. The type of environment that should be listed. * @return the request */ public Get get(java.lang.String environmentType) throws java.io.IOException { Get result = new Get(environmentType); initialize(result); return result; } public class Get extends TestingRequest<com.google.api.services.testing.model.TestEnvironmentCatalog> { private static final String REST_PATH = "v1/testEnvironmentCatalog/{environmentType}"; /** * Gets the catalog of supported test environments. May return any of the following canonical * error codes: - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the environment * type does not exist - INTERNAL - if an internal error occurred * * Create a request for the method "testEnvironmentCatalog.get". * * This request holds the parameters needed by the the testing server. After setting any optional * parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> {@link * Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be * called to initialize this instance immediately after invoking the constructor. </p> * * @param environmentType Required. The type of environment that should be listed. * @since 1.13 */ protected Get(java.lang.String environmentType) { super(Testing.this, "GET", REST_PATH, null, com.google.api.services.testing.model.TestEnvironmentCatalog.class); this.environmentType = com.google.api.client.util.Preconditions.checkNotNull(environmentType, "Required parameter environmentType must be specified."); } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Required. The type of environment that should be listed. */ @com.google.api.client.util.Key private java.lang.String environmentType; /** Required. The type of environment that should be listed. */ public java.lang.String getEnvironmentType() { return environmentType; } /** Required. The type of environment that should be listed. */ public Get setEnvironmentType(java.lang.String environmentType) { this.environmentType = environmentType; return this; } /** For authorization, the cloud project requesting the TestEnvironmentCatalog. */ @com.google.api.client.util.Key private java.lang.String projectId; /** For authorization, the cloud project requesting the TestEnvironmentCatalog. */ public java.lang.String getProjectId() { return projectId; } /** For authorization, the cloud project requesting the TestEnvironmentCatalog. */ public Get setProjectId(java.lang.String projectId) { this.projectId = projectId; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } } /** * Builder for {@link Testing}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link Testing}. */ @Override public Testing build() { return new Testing(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link TestingRequestInitializer}. * * @since 1.12 */ public Builder setTestingRequestInitializer( TestingRequestInitializer testingRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(testingRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
google/j2objc
38,423
jre_emul/android/platform/libcore/luni/src/test/java/libcore/java/nio/charset/OldCharset_MultiByte_UTF_8.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 libcore.java.nio.charset; public class OldCharset_MultiByte_UTF_8 extends OldCharset_AbstractTest { @Override protected void setUp() throws Exception { charsetName = "UTF-8"; testChars = theseChars(new int[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 296, 336, 376, 416, 456, 496, 536, 576, 616, 656, 696, 736, 776, 816, 856, 896, 936, 976, 1016, 1056, 1096, 1136, 1176, 1216, 1256, 1296, 1336, 1376, 1416, 1456, 1496, 1536, 1576, 1616, 1656, 1696, 1736, 1776, 1816, 1856, 1896, 1936, 1976, 2016, 2056, 2096, 2136, 2176, 2216, 2256, 2296, 2336, 2376, 2416, 2456, 2496, 2536, 2576, 2616, 2656, 2696, 2736, 2776, 2816, 2856, 2896, 2936, 2976, 3016, 3056, 3096, 3136, 3176, 3216, 3256, 3296, 3336, 3376, 3416, 3456, 3496, 3536, 3576, 3616, 3656, 3696, 3736, 3776, 3816, 3856, 3896, 3936, 3976, 4016, 4056, 4096, 4136, 4176, 4216, 4256, 4296, 4336, 4376, 4416, 4456, 4496, 4536, 4576, 4616, 4656, 4696, 4736, 4776, 4816, 4856, 4896, 4936, 4976, 5016, 5056, 5096, 5136, 5176, 5216, 5256, 5296, 5336, 5376, 5416, 5456, 5496, 5536, 5576, 5616, 5656, 5696, 5736, 5776, 5816, 5856, 5896, 5936, 5976, 6016, 6056, 6096, 6136, 6176, 6216, 6256, 6296, 6336, 6376, 6416, 6456, 6496, 6536, 6576, 6616, 6656, 6696, 6736, 6776, 6816, 6856, 6896, 6936, 6976, 7016, 7056, 7096, 7136, 7176, 7216, 7256, 7296, 7336, 7376, 7416, 7456, 7496, 7536, 7576, 7616, 7656, 7696, 7736, 7776, 7816, 7856, 7896, 7936, 7976, 8016, 8056, 8096, 8136, 8176, 8216, 8256, 8296, 8336, 8376, 8416, 8456, 8496, 8536, 8576, 8616, 8656, 8696, 8736, 8776, 8816, 8856, 8896, 8936, 8976, 9016, 9056, 9096, 9136, 9176, 9216, 9256, 9296, 9336, 9376, 9416, 9456, 9496, 9536, 9576, 9616, 9656, 9696, 9736, 9776, 9816, 9856, 9896, 9936, 9976, 10016, 10056, 10096, 10136, 10176, 10216, 10256, 10296, 10336, 10376, 10416, 10456, 10496, 10536, 10576, 10616, 10656, 10696, 10736, 10776, 10816, 10856, 10896, 10936, 10976, 11016, 11056, 11096, 11136, 11176, 11216, 11256, 11296, 11336, 11376, 11416, 11456, 11496, 11536, 11576, 11616, 11656, 11696, 11736, 11776, 11816, 11856, 11896, 11936, 11976, 12016, 12056, 12096, 12136, 12176, 12216, 12256, 12296, 12336, 12376, 12416, 12456, 12496, 12536, 12576, 12616, 12656, 12696, 12736, 12776, 12816, 12856, 12896, 12936, 12976, 13016, 13056, 13096, 13136, 13176, 13216, 13256, 13296, 13336, 13376, 13416, 13456, 13496, 13536, 13576, 13616, 13656, 13696, 13736, 13776, 13816, 13856, 13896, 13936, 13976, 14016, 14056, 14096, 14136, 14176, 14216, 14256, 14296, 14336, 14376, 14416, 14456, 14496, 14536, 14576, 14616, 14656, 14696, 14736, 14776, 14816, 14856, 14896, 14936, 14976, 15016, 15056, 15096, 15136, 15176, 15216, 15256, 15296, 15336, 15376, 15416, 15456, 15496, 15536, 15576, 15616, 15656, 15696, 15736, 15776, 15816, 15856, 15896, 15936, 15976, 16016, 16056, 16096, 16136, 16176, 16216, 16256, 16296, 16336, 16376, 16416, 16456, 16496, 16536, 16576, 16616, 16656, 16696, 16736, 16776, 16816, 16856, 16896, 16936, 16976, 17016, 17056, 17096, 17136, 17176, 17216, 17256, 17296, 17336, 17376, 17416, 17456, 17496, 17536, 17576, 17616, 17656, 17696, 17736, 17776, 17816, 17856, 17896, 17936, 17976, 18016, 18056, 18096, 18136, 18176, 18216, 18256, 18296, 18336, 18376, 18416, 18456, 18496, 18536, 18576, 18616, 18656, 18696, 18736, 18776, 18816, 18856, 18896, 18936, 18976, 19016, 19056, 19096, 19136, 19176, 19216, 19256, 19296, 19336, 19376, 19416, 19456, 19496, 19536, 19576, 19616, 19656, 19696, 19736, 19776, 19816, 19856, 19896, 19936, 19976, 20016, 20056, 20096, 20136, 20176, 20216, 20256, 20296, 20336, 20376, 20416, 20456, 20496, 20536, 20576, 20616, 20656, 20696, 20736, 20776, 20816, 20856, 20896, 20936, 20976, 21016, 21056, 21096, 21136, 21176, 21216, 21256, 21296, 21336, 21376, 21416, 21456, 21496, 21536, 21576, 21616, 21656, 21696, 21736, 21776, 21816, 21856, 21896, 21936, 21976, 22016, 22056, 22096, 22136, 22176, 22216, 22256, 22296, 22336, 22376, 22416, 22456, 22496, 22536, 22576, 22616, 22656, 22696, 22736, 22776, 22816, 22856, 22896, 22936, 22976, 23016, 23056, 23096, 23136, 23176, 23216, 23256, 23296, 23336, 23376, 23416, 23456, 23496, 23536, 23576, 23616, 23656, 23696, 23736, 23776, 23816, 23856, 23896, 23936, 23976, 24016, 24056, 24096, 24136, 24176, 24216, 24256, 24296, 24336, 24376, 24416, 24456, 24496, 24536, 24576, 24616, 24656, 24696, 24736, 24776, 24816, 24856, 24896, 24936, 24976, 25016, 25056, 25096, 25136, 25176, 25216, 25256, 25296, 25336, 25376, 25416, 25456, 25496, 25536, 25576, 25616, 25656, 25696, 25736, 25776, 25816, 25856, 25896, 25936, 25976, 26016, 26056, 26096, 26136, 26176, 26216, 26256, 26296, 26336, 26376, 26416, 26456, 26496, 26536, 26576, 26616, 26656, 26696, 26736, 26776, 26816, 26856, 26896, 26936, 26976, 27016, 27056, 27096, 27136, 27176, 27216, 27256, 27296, 27336, 27376, 27416, 27456, 27496, 27536, 27576, 27616, 27656, 27696, 27736, 27776, 27816, 27856, 27896, 27936, 27976, 28016, 28056, 28096, 28136, 28176, 28216, 28256, 28296, 28336, 28376, 28416, 28456, 28496, 28536, 28576, 28616, 28656, 28696, 28736, 28776, 28816, 28856, 28896, 28936, 28976, 29016, 29056, 29096, 29136, 29176, 29216, 29256, 29296, 29336, 29376, 29416, 29456, 29496, 29536, 29576, 29616, 29656, 29696, 29736, 29776, 29816, 29856, 29896, 29936, 29976, 30016, 30056, 30096, 30136, 30176, 30216, 30256, 30296, 30336, 30376, 30416, 30456, 30496, 30536, 30576, 30616, 30656, 30696, 30736, 30776, 30816, 30856, 30896, 30936, 30976, 31016, 31056, 31096, 31136, 31176, 31216, 31256, 31296, 31336, 31376, 31416, 31456, 31496, 31536, 31576, 31616, 31656, 31696, 31736, 31776, 31816, 31856, 31896, 31936, 31976, 32016, 32056, 32096, 32136, 32176, 32216, 32256, 32296, 32336, 32376, 32416, 32456, 32496, 32536, 32576, 32616, 32656, 32696, 32736, 32776, 32816, 32856, 32896, 32936, 32976, 33016, 33056, 33096, 33136, 33176, 33216, 33256, 33296, 33336, 33376, 33416, 33456, 33496, 33536, 33576, 33616, 33656, 33696, 33736, 33776, 33816, 33856, 33896, 33936, 33976, 34016, 34056, 34096, 34136, 34176, 34216, 34256, 34296, 34336, 34376, 34416, 34456, 34496, 34536, 34576, 34616, 34656, 34696, 34736, 34776, 34816, 34856, 34896, 34936, 34976, 35016, 35056, 35096, 35136, 35176, 35216, 35256, 35296, 35336, 35376, 35416, 35456, 35496, 35536, 35576, 35616, 35656, 35696, 35736, 35776, 35816, 35856, 35896, 35936, 35976, 36016, 36056, 36096, 36136, 36176, 36216, 36256, 36296, 36336, 36376, 36416, 36456, 36496, 36536, 36576, 36616, 36656, 36696, 36736, 36776, 36816, 36856, 36896, 36936, 36976, 37016, 37056, 37096, 37136, 37176, 37216, 37256, 37296, 37336, 37376, 37416, 37456, 37496, 37536, 37576, 37616, 37656, 37696, 37736, 37776, 37816, 37856, 37896, 37936, 37976, 38016, 38056, 38096, 38136, 38176, 38216, 38256, 38296, 38336, 38376, 38416, 38456, 38496, 38536, 38576, 38616, 38656, 38696, 38736, 38776, 38816, 38856, 38896, 38936, 38976, 39016, 39056, 39096, 39136, 39176, 39216, 39256, 39296, 39336, 39376, 39416, 39456, 39496, 39536, 39576, 39616, 39656, 39696, 39736, 39776, 39816, 39856, 39896, 39936, 39976, 40016, 40056, 40096, 40136, 40176, 40216, 40256, 40296, 40336, 40376, 40416, 40456, 40496, 40536, 40576, 40616, 40656, 40696, 40736, 40776, 40816, 40856, 40896, 40936, 40976, 41016, 41056, 41096, 41136, 41176, 41216, 41256, 41296, 41336, 41376, 41416, 41456, 41496, 41536, 41576, 41616, 41656, 41696, 41736, 41776, 41816, 41856, 41896, 41936, 41976, 42016, 42056, 42096, 42136, 42176, 42216, 42256, 42296, 42336, 42376, 42416, 42456, 42496, 42536, 42576, 42616, 42656, 42696, 42736, 42776, 42816, 42856, 42896, 42936, 42976, 43016, 43056, 43096, 43136, 43176, 43216, 43256, 43296, 43336, 43376, 43416, 43456, 43496, 43536, 43576, 43616, 43656, 43696, 43736, 43776, 43816, 43856, 43896, 43936, 43976, 44016, 44056, 44096, 44136, 44176, 44216, 44256, 44296, 44336, 44376, 44416, 44456, 44496, 44536, 44576, 44616, 44656, 44696, 44736, 44776, 44816, 44856, 44896, 44936, 44976, 45016, 45056, 45096, 45136, 45176, 45216, 45256, 45296, 45336, 45376, 45416, 45456, 45496, 45536, 45576, 45616, 45656, 45696, 45736, 45776, 45816, 45856, 45896, 45936, 45976, 46016, 46056, 46096, 46136, 46176, 46216, 46256, 46296, 46336, 46376, 46416, 46456, 46496, 46536, 46576, 46616, 46656, 46696, 46736, 46776, 46816, 46856, 46896, 46936, 46976, 47016, 47056, 47096, 47136, 47176, 47216, 47256, 47296, 47336, 47376, 47416, 47456, 47496, 47536, 47576, 47616, 47656, 47696, 47736, 47776, 47816, 47856, 47896, 47936, 47976, 48016, 48056, 48096, 48136, 48176, 48216, 48256, 48296, 48336, 48376, 48416, 48456, 48496, 48536, 48576, 48616, 48656, 48696, 48736, 48776, 48816, 48856, 48896, 48936, 48976, 49016, 49056, 49096, 49136, 49176, 49216, 49256, 49296, 49336, 49376, 49416, 49456, 49496, 49536, 49576, 49616, 49656, 49696, 49736, 49776, 49816, 49856, 49896, 49936, 49976, 50016, 50056, 50096, 50136, 50176, 50216, 50256, 50296, 50336, 50376, 50416, 50456, 50496, 50536, 50576, 50616, 50656, 50696, 50736, 50776, 50816, 50856, 50896, 50936, 50976, 51016, 51056, 51096, 51136, 51176, 51216, 51256, 51296, 51336, 51376, 51416, 51456, 51496, 51536, 51576, 51616, 51656, 51696, 51736, 51776, 51816, 51856, 51896, 51936, 51976, 52016, 52056, 52096, 52136, 52176, 52216, 52256, 52296, 52336, 52376, 52416, 52456, 52496, 52536, 52576, 52616, 52656, 52696, 52736, 52776, 52816, 52856, 52896, 52936, 52976, 53016, 53056, 53096, 53136, 53176, 53216, 53256, 53296, 53336, 53376, 53416, 53456, 53496, 53536, 53576, 53616, 53656, 53696, 53736, 53776, 53816, 53856, 53896, 53936, 53976, 54016, 54056, 54096, 54136, 54176, 54216, 54256, 54296, 54336, 54376, 54416, 54456, 54496, 54536, 54576, 54616, 54656, 54696, 54736, 54776, 54816, 54856, 54896, 54936, 54976, 55016, 55056, 55096, 55136, 55176, 55216, 55256, 57344, 57384, 57424, 57464, 57504, 57544, 57584, 57624, 57664, 57704, 57744, 57784, 57824, 57864, 57904, 57944, 57984, 58024, 58064, 58104, 58144, 58184, 58224, 58264, 58304, 58344, 58384, 58424, 58464, 58504, 58544, 58584, 58624, 58664, 58704, 58744, 58784, 58824, 58864, 58904, 58944, 58984, 59024, 59064, 59104, 59144, 59184, 59224, 59264, 59304, 59344, 59384, 59424, 59464, 59504, 59544, 59584, 59624, 59664, 59704, 59744, 59784, 59824, 59864, 59904, 59944, 59984, 60024, 60064, 60104, 60144, 60184, 60224, 60264, 60304, 60344, 60384, 60424, 60464, 60504, 60544, 60584, 60624, 60664, 60704, 60744, 60784, 60824, 60864, 60904, 60944, 60984, 61024, 61064, 61104, 61144, 61184, 61224, 61264, 61304, 61344, 61384, 61424, 61464, 61504, 61544, 61584, 61624, 61664, 61704, 61744, 61784, 61824, 61864, 61904, 61944, 61984, 62024, 62064, 62104, 62144, 62184, 62224, 62264, 62304, 62344, 62384, 62424, 62464, 62504, 62544, 62584, 62624, 62664, 62704, 62744, 62784, 62824, 62864, 62904, 62944, 62984, 63024, 63064, 63104, 63144, 63184, 63224, 63264, 63304, 63344, 63384, 63424, 63464, 63504, 63544, 63584, 63624, 63664, 63704, 63744, 63784, 63824, 63864, 63904, 63944, 63984, 64024, 64064, 64104, 64144, 64184, 64224, 64264, 64304, 64344, 64384, 64424, 64464, 64504, 64544, 64584, 64624, 64664, 64704, 64744, 64784, 64824, 64864, 64904, 64944, 64984, 65024, 65064, 65104, 65144, 65184, 65224, 65264, 65304, 65344, 65384, 65424, 65464, 65504 }); testBytes = theseBytes(new int[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 194, 128, 194, 129, 194, 130, 194, 131, 194, 132, 194, 133, 194, 134, 194, 135, 194, 136, 194, 137, 194, 138, 194, 139, 194, 140, 194, 141, 194, 142, 194, 143, 194, 144, 194, 145, 194, 146, 194, 147, 194, 148, 194, 149, 194, 150, 194, 151, 194, 152, 194, 153, 194, 154, 194, 155, 194, 156, 194, 157, 194, 158, 194, 159, 194, 160, 194, 161, 194, 162, 194, 163, 194, 164, 194, 165, 194, 166, 194, 167, 194, 168, 194, 169, 194, 170, 194, 171, 194, 172, 194, 173, 194, 174, 194, 175, 194, 176, 194, 177, 194, 178, 194, 179, 194, 180, 194, 181, 194, 182, 194, 183, 194, 184, 194, 185, 194, 186, 194, 187, 194, 188, 194, 189, 194, 190, 194, 191, 195, 128, 195, 129, 195, 130, 195, 131, 195, 132, 195, 133, 195, 134, 195, 135, 195, 136, 195, 137, 195, 138, 195, 139, 195, 140, 195, 141, 195, 142, 195, 143, 195, 144, 195, 145, 195, 146, 195, 147, 195, 148, 195, 149, 195, 150, 195, 151, 195, 152, 195, 153, 195, 154, 195, 155, 195, 156, 195, 157, 195, 158, 195, 159, 195, 160, 195, 161, 195, 162, 195, 163, 195, 164, 195, 165, 195, 166, 195, 167, 195, 168, 195, 169, 195, 170, 195, 171, 195, 172, 195, 173, 195, 174, 195, 175, 195, 176, 195, 177, 195, 178, 195, 179, 195, 180, 195, 181, 195, 182, 195, 183, 195, 184, 195, 185, 195, 186, 195, 187, 195, 188, 195, 189, 195, 190, 195, 191, 196, 128, 196, 168, 197, 144, 197, 184, 198, 160, 199, 136, 199, 176, 200, 152, 201, 128, 201, 168, 202, 144, 202, 184, 203, 160, 204, 136, 204, 176, 205, 152, 206, 128, 206, 168, 207, 144, 207, 184, 208, 160, 209, 136, 209, 176, 210, 152, 211, 128, 211, 168, 212, 144, 212, 184, 213, 160, 214, 136, 214, 176, 215, 152, 216, 128, 216, 168, 217, 144, 217, 184, 218, 160, 219, 136, 219, 176, 220, 152, 221, 128, 221, 168, 222, 144, 222, 184, 223, 160, 224, 160, 136, 224, 160, 176, 224, 161, 152, 224, 162, 128, 224, 162, 168, 224, 163, 144, 224, 163, 184, 224, 164, 160, 224, 165, 136, 224, 165, 176, 224, 166, 152, 224, 167, 128, 224, 167, 168, 224, 168, 144, 224, 168, 184, 224, 169, 160, 224, 170, 136, 224, 170, 176, 224, 171, 152, 224, 172, 128, 224, 172, 168, 224, 173, 144, 224, 173, 184, 224, 174, 160, 224, 175, 136, 224, 175, 176, 224, 176, 152, 224, 177, 128, 224, 177, 168, 224, 178, 144, 224, 178, 184, 224, 179, 160, 224, 180, 136, 224, 180, 176, 224, 181, 152, 224, 182, 128, 224, 182, 168, 224, 183, 144, 224, 183, 184, 224, 184, 160, 224, 185, 136, 224, 185, 176, 224, 186, 152, 224, 187, 128, 224, 187, 168, 224, 188, 144, 224, 188, 184, 224, 189, 160, 224, 190, 136, 224, 190, 176, 224, 191, 152, 225, 128, 128, 225, 128, 168, 225, 129, 144, 225, 129, 184, 225, 130, 160, 225, 131, 136, 225, 131, 176, 225, 132, 152, 225, 133, 128, 225, 133, 168, 225, 134, 144, 225, 134, 184, 225, 135, 160, 225, 136, 136, 225, 136, 176, 225, 137, 152, 225, 138, 128, 225, 138, 168, 225, 139, 144, 225, 139, 184, 225, 140, 160, 225, 141, 136, 225, 141, 176, 225, 142, 152, 225, 143, 128, 225, 143, 168, 225, 144, 144, 225, 144, 184, 225, 145, 160, 225, 146, 136, 225, 146, 176, 225, 147, 152, 225, 148, 128, 225, 148, 168, 225, 149, 144, 225, 149, 184, 225, 150, 160, 225, 151, 136, 225, 151, 176, 225, 152, 152, 225, 153, 128, 225, 153, 168, 225, 154, 144, 225, 154, 184, 225, 155, 160, 225, 156, 136, 225, 156, 176, 225, 157, 152, 225, 158, 128, 225, 158, 168, 225, 159, 144, 225, 159, 184, 225, 160, 160, 225, 161, 136, 225, 161, 176, 225, 162, 152, 225, 163, 128, 225, 163, 168, 225, 164, 144, 225, 164, 184, 225, 165, 160, 225, 166, 136, 225, 166, 176, 225, 167, 152, 225, 168, 128, 225, 168, 168, 225, 169, 144, 225, 169, 184, 225, 170, 160, 225, 171, 136, 225, 171, 176, 225, 172, 152, 225, 173, 128, 225, 173, 168, 225, 174, 144, 225, 174, 184, 225, 175, 160, 225, 176, 136, 225, 176, 176, 225, 177, 152, 225, 178, 128, 225, 178, 168, 225, 179, 144, 225, 179, 184, 225, 180, 160, 225, 181, 136, 225, 181, 176, 225, 182, 152, 225, 183, 128, 225, 183, 168, 225, 184, 144, 225, 184, 184, 225, 185, 160, 225, 186, 136, 225, 186, 176, 225, 187, 152, 225, 188, 128, 225, 188, 168, 225, 189, 144, 225, 189, 184, 225, 190, 160, 225, 191, 136, 225, 191, 176, 226, 128, 152, 226, 129, 128, 226, 129, 168, 226, 130, 144, 226, 130, 184, 226, 131, 160, 226, 132, 136, 226, 132, 176, 226, 133, 152, 226, 134, 128, 226, 134, 168, 226, 135, 144, 226, 135, 184, 226, 136, 160, 226, 137, 136, 226, 137, 176, 226, 138, 152, 226, 139, 128, 226, 139, 168, 226, 140, 144, 226, 140, 184, 226, 141, 160, 226, 142, 136, 226, 142, 176, 226, 143, 152, 226, 144, 128, 226, 144, 168, 226, 145, 144, 226, 145, 184, 226, 146, 160, 226, 147, 136, 226, 147, 176, 226, 148, 152, 226, 149, 128, 226, 149, 168, 226, 150, 144, 226, 150, 184, 226, 151, 160, 226, 152, 136, 226, 152, 176, 226, 153, 152, 226, 154, 128, 226, 154, 168, 226, 155, 144, 226, 155, 184, 226, 156, 160, 226, 157, 136, 226, 157, 176, 226, 158, 152, 226, 159, 128, 226, 159, 168, 226, 160, 144, 226, 160, 184, 226, 161, 160, 226, 162, 136, 226, 162, 176, 226, 163, 152, 226, 164, 128, 226, 164, 168, 226, 165, 144, 226, 165, 184, 226, 166, 160, 226, 167, 136, 226, 167, 176, 226, 168, 152, 226, 169, 128, 226, 169, 168, 226, 170, 144, 226, 170, 184, 226, 171, 160, 226, 172, 136, 226, 172, 176, 226, 173, 152, 226, 174, 128, 226, 174, 168, 226, 175, 144, 226, 175, 184, 226, 176, 160, 226, 177, 136, 226, 177, 176, 226, 178, 152, 226, 179, 128, 226, 179, 168, 226, 180, 144, 226, 180, 184, 226, 181, 160, 226, 182, 136, 226, 182, 176, 226, 183, 152, 226, 184, 128, 226, 184, 168, 226, 185, 144, 226, 185, 184, 226, 186, 160, 226, 187, 136, 226, 187, 176, 226, 188, 152, 226, 189, 128, 226, 189, 168, 226, 190, 144, 226, 190, 184, 226, 191, 160, 227, 128, 136, 227, 128, 176, 227, 129, 152, 227, 130, 128, 227, 130, 168, 227, 131, 144, 227, 131, 184, 227, 132, 160, 227, 133, 136, 227, 133, 176, 227, 134, 152, 227, 135, 128, 227, 135, 168, 227, 136, 144, 227, 136, 184, 227, 137, 160, 227, 138, 136, 227, 138, 176, 227, 139, 152, 227, 140, 128, 227, 140, 168, 227, 141, 144, 227, 141, 184, 227, 142, 160, 227, 143, 136, 227, 143, 176, 227, 144, 152, 227, 145, 128, 227, 145, 168, 227, 146, 144, 227, 146, 184, 227, 147, 160, 227, 148, 136, 227, 148, 176, 227, 149, 152, 227, 150, 128, 227, 150, 168, 227, 151, 144, 227, 151, 184, 227, 152, 160, 227, 153, 136, 227, 153, 176, 227, 154, 152, 227, 155, 128, 227, 155, 168, 227, 156, 144, 227, 156, 184, 227, 157, 160, 227, 158, 136, 227, 158, 176, 227, 159, 152, 227, 160, 128, 227, 160, 168, 227, 161, 144, 227, 161, 184, 227, 162, 160, 227, 163, 136, 227, 163, 176, 227, 164, 152, 227, 165, 128, 227, 165, 168, 227, 166, 144, 227, 166, 184, 227, 167, 160, 227, 168, 136, 227, 168, 176, 227, 169, 152, 227, 170, 128, 227, 170, 168, 227, 171, 144, 227, 171, 184, 227, 172, 160, 227, 173, 136, 227, 173, 176, 227, 174, 152, 227, 175, 128, 227, 175, 168, 227, 176, 144, 227, 176, 184, 227, 177, 160, 227, 178, 136, 227, 178, 176, 227, 179, 152, 227, 180, 128, 227, 180, 168, 227, 181, 144, 227, 181, 184, 227, 182, 160, 227, 183, 136, 227, 183, 176, 227, 184, 152, 227, 185, 128, 227, 185, 168, 227, 186, 144, 227, 186, 184, 227, 187, 160, 227, 188, 136, 227, 188, 176, 227, 189, 152, 227, 190, 128, 227, 190, 168, 227, 191, 144, 227, 191, 184, 228, 128, 160, 228, 129, 136, 228, 129, 176, 228, 130, 152, 228, 131, 128, 228, 131, 168, 228, 132, 144, 228, 132, 184, 228, 133, 160, 228, 134, 136, 228, 134, 176, 228, 135, 152, 228, 136, 128, 228, 136, 168, 228, 137, 144, 228, 137, 184, 228, 138, 160, 228, 139, 136, 228, 139, 176, 228, 140, 152, 228, 141, 128, 228, 141, 168, 228, 142, 144, 228, 142, 184, 228, 143, 160, 228, 144, 136, 228, 144, 176, 228, 145, 152, 228, 146, 128, 228, 146, 168, 228, 147, 144, 228, 147, 184, 228, 148, 160, 228, 149, 136, 228, 149, 176, 228, 150, 152, 228, 151, 128, 228, 151, 168, 228, 152, 144, 228, 152, 184, 228, 153, 160, 228, 154, 136, 228, 154, 176, 228, 155, 152, 228, 156, 128, 228, 156, 168, 228, 157, 144, 228, 157, 184, 228, 158, 160, 228, 159, 136, 228, 159, 176, 228, 160, 152, 228, 161, 128, 228, 161, 168, 228, 162, 144, 228, 162, 184, 228, 163, 160, 228, 164, 136, 228, 164, 176, 228, 165, 152, 228, 166, 128, 228, 166, 168, 228, 167, 144, 228, 167, 184, 228, 168, 160, 228, 169, 136, 228, 169, 176, 228, 170, 152, 228, 171, 128, 228, 171, 168, 228, 172, 144, 228, 172, 184, 228, 173, 160, 228, 174, 136, 228, 174, 176, 228, 175, 152, 228, 176, 128, 228, 176, 168, 228, 177, 144, 228, 177, 184, 228, 178, 160, 228, 179, 136, 228, 179, 176, 228, 180, 152, 228, 181, 128, 228, 181, 168, 228, 182, 144, 228, 182, 184, 228, 183, 160, 228, 184, 136, 228, 184, 176, 228, 185, 152, 228, 186, 128, 228, 186, 168, 228, 187, 144, 228, 187, 184, 228, 188, 160, 228, 189, 136, 228, 189, 176, 228, 190, 152, 228, 191, 128, 228, 191, 168, 229, 128, 144, 229, 128, 184, 229, 129, 160, 229, 130, 136, 229, 130, 176, 229, 131, 152, 229, 132, 128, 229, 132, 168, 229, 133, 144, 229, 133, 184, 229, 134, 160, 229, 135, 136, 229, 135, 176, 229, 136, 152, 229, 137, 128, 229, 137, 168, 229, 138, 144, 229, 138, 184, 229, 139, 160, 229, 140, 136, 229, 140, 176, 229, 141, 152, 229, 142, 128, 229, 142, 168, 229, 143, 144, 229, 143, 184, 229, 144, 160, 229, 145, 136, 229, 145, 176, 229, 146, 152, 229, 147, 128, 229, 147, 168, 229, 148, 144, 229, 148, 184, 229, 149, 160, 229, 150, 136, 229, 150, 176, 229, 151, 152, 229, 152, 128, 229, 152, 168, 229, 153, 144, 229, 153, 184, 229, 154, 160, 229, 155, 136, 229, 155, 176, 229, 156, 152, 229, 157, 128, 229, 157, 168, 229, 158, 144, 229, 158, 184, 229, 159, 160, 229, 160, 136, 229, 160, 176, 229, 161, 152, 229, 162, 128, 229, 162, 168, 229, 163, 144, 229, 163, 184, 229, 164, 160, 229, 165, 136, 229, 165, 176, 229, 166, 152, 229, 167, 128, 229, 167, 168, 229, 168, 144, 229, 168, 184, 229, 169, 160, 229, 170, 136, 229, 170, 176, 229, 171, 152, 229, 172, 128, 229, 172, 168, 229, 173, 144, 229, 173, 184, 229, 174, 160, 229, 175, 136, 229, 175, 176, 229, 176, 152, 229, 177, 128, 229, 177, 168, 229, 178, 144, 229, 178, 184, 229, 179, 160, 229, 180, 136, 229, 180, 176, 229, 181, 152, 229, 182, 128, 229, 182, 168, 229, 183, 144, 229, 183, 184, 229, 184, 160, 229, 185, 136, 229, 185, 176, 229, 186, 152, 229, 187, 128, 229, 187, 168, 229, 188, 144, 229, 188, 184, 229, 189, 160, 229, 190, 136, 229, 190, 176, 229, 191, 152, 230, 128, 128, 230, 128, 168, 230, 129, 144, 230, 129, 184, 230, 130, 160, 230, 131, 136, 230, 131, 176, 230, 132, 152, 230, 133, 128, 230, 133, 168, 230, 134, 144, 230, 134, 184, 230, 135, 160, 230, 136, 136, 230, 136, 176, 230, 137, 152, 230, 138, 128, 230, 138, 168, 230, 139, 144, 230, 139, 184, 230, 140, 160, 230, 141, 136, 230, 141, 176, 230, 142, 152, 230, 143, 128, 230, 143, 168, 230, 144, 144, 230, 144, 184, 230, 145, 160, 230, 146, 136, 230, 146, 176, 230, 147, 152, 230, 148, 128, 230, 148, 168, 230, 149, 144, 230, 149, 184, 230, 150, 160, 230, 151, 136, 230, 151, 176, 230, 152, 152, 230, 153, 128, 230, 153, 168, 230, 154, 144, 230, 154, 184, 230, 155, 160, 230, 156, 136, 230, 156, 176, 230, 157, 152, 230, 158, 128, 230, 158, 168, 230, 159, 144, 230, 159, 184, 230, 160, 160, 230, 161, 136, 230, 161, 176, 230, 162, 152, 230, 163, 128, 230, 163, 168, 230, 164, 144, 230, 164, 184, 230, 165, 160, 230, 166, 136, 230, 166, 176, 230, 167, 152, 230, 168, 128, 230, 168, 168, 230, 169, 144, 230, 169, 184, 230, 170, 160, 230, 171, 136, 230, 171, 176, 230, 172, 152, 230, 173, 128, 230, 173, 168, 230, 174, 144, 230, 174, 184, 230, 175, 160, 230, 176, 136, 230, 176, 176, 230, 177, 152, 230, 178, 128, 230, 178, 168, 230, 179, 144, 230, 179, 184, 230, 180, 160, 230, 181, 136, 230, 181, 176, 230, 182, 152, 230, 183, 128, 230, 183, 168, 230, 184, 144, 230, 184, 184, 230, 185, 160, 230, 186, 136, 230, 186, 176, 230, 187, 152, 230, 188, 128, 230, 188, 168, 230, 189, 144, 230, 189, 184, 230, 190, 160, 230, 191, 136, 230, 191, 176, 231, 128, 152, 231, 129, 128, 231, 129, 168, 231, 130, 144, 231, 130, 184, 231, 131, 160, 231, 132, 136, 231, 132, 176, 231, 133, 152, 231, 134, 128, 231, 134, 168, 231, 135, 144, 231, 135, 184, 231, 136, 160, 231, 137, 136, 231, 137, 176, 231, 138, 152, 231, 139, 128, 231, 139, 168, 231, 140, 144, 231, 140, 184, 231, 141, 160, 231, 142, 136, 231, 142, 176, 231, 143, 152, 231, 144, 128, 231, 144, 168, 231, 145, 144, 231, 145, 184, 231, 146, 160, 231, 147, 136, 231, 147, 176, 231, 148, 152, 231, 149, 128, 231, 149, 168, 231, 150, 144, 231, 150, 184, 231, 151, 160, 231, 152, 136, 231, 152, 176, 231, 153, 152, 231, 154, 128, 231, 154, 168, 231, 155, 144, 231, 155, 184, 231, 156, 160, 231, 157, 136, 231, 157, 176, 231, 158, 152, 231, 159, 128, 231, 159, 168, 231, 160, 144, 231, 160, 184, 231, 161, 160, 231, 162, 136, 231, 162, 176, 231, 163, 152, 231, 164, 128, 231, 164, 168, 231, 165, 144, 231, 165, 184, 231, 166, 160, 231, 167, 136, 231, 167, 176, 231, 168, 152, 231, 169, 128, 231, 169, 168, 231, 170, 144, 231, 170, 184, 231, 171, 160, 231, 172, 136, 231, 172, 176, 231, 173, 152, 231, 174, 128, 231, 174, 168, 231, 175, 144, 231, 175, 184, 231, 176, 160, 231, 177, 136, 231, 177, 176, 231, 178, 152, 231, 179, 128, 231, 179, 168, 231, 180, 144, 231, 180, 184, 231, 181, 160, 231, 182, 136, 231, 182, 176, 231, 183, 152, 231, 184, 128, 231, 184, 168, 231, 185, 144, 231, 185, 184, 231, 186, 160, 231, 187, 136, 231, 187, 176, 231, 188, 152, 231, 189, 128, 231, 189, 168, 231, 190, 144, 231, 190, 184, 231, 191, 160, 232, 128, 136, 232, 128, 176, 232, 129, 152, 232, 130, 128, 232, 130, 168, 232, 131, 144, 232, 131, 184, 232, 132, 160, 232, 133, 136, 232, 133, 176, 232, 134, 152, 232, 135, 128, 232, 135, 168, 232, 136, 144, 232, 136, 184, 232, 137, 160, 232, 138, 136, 232, 138, 176, 232, 139, 152, 232, 140, 128, 232, 140, 168, 232, 141, 144, 232, 141, 184, 232, 142, 160, 232, 143, 136, 232, 143, 176, 232, 144, 152, 232, 145, 128, 232, 145, 168, 232, 146, 144, 232, 146, 184, 232, 147, 160, 232, 148, 136, 232, 148, 176, 232, 149, 152, 232, 150, 128, 232, 150, 168, 232, 151, 144, 232, 151, 184, 232, 152, 160, 232, 153, 136, 232, 153, 176, 232, 154, 152, 232, 155, 128, 232, 155, 168, 232, 156, 144, 232, 156, 184, 232, 157, 160, 232, 158, 136, 232, 158, 176, 232, 159, 152, 232, 160, 128, 232, 160, 168, 232, 161, 144, 232, 161, 184, 232, 162, 160, 232, 163, 136, 232, 163, 176, 232, 164, 152, 232, 165, 128, 232, 165, 168, 232, 166, 144, 232, 166, 184, 232, 167, 160, 232, 168, 136, 232, 168, 176, 232, 169, 152, 232, 170, 128, 232, 170, 168, 232, 171, 144, 232, 171, 184, 232, 172, 160, 232, 173, 136, 232, 173, 176, 232, 174, 152, 232, 175, 128, 232, 175, 168, 232, 176, 144, 232, 176, 184, 232, 177, 160, 232, 178, 136, 232, 178, 176, 232, 179, 152, 232, 180, 128, 232, 180, 168, 232, 181, 144, 232, 181, 184, 232, 182, 160, 232, 183, 136, 232, 183, 176, 232, 184, 152, 232, 185, 128, 232, 185, 168, 232, 186, 144, 232, 186, 184, 232, 187, 160, 232, 188, 136, 232, 188, 176, 232, 189, 152, 232, 190, 128, 232, 190, 168, 232, 191, 144, 232, 191, 184, 233, 128, 160, 233, 129, 136, 233, 129, 176, 233, 130, 152, 233, 131, 128, 233, 131, 168, 233, 132, 144, 233, 132, 184, 233, 133, 160, 233, 134, 136, 233, 134, 176, 233, 135, 152, 233, 136, 128, 233, 136, 168, 233, 137, 144, 233, 137, 184, 233, 138, 160, 233, 139, 136, 233, 139, 176, 233, 140, 152, 233, 141, 128, 233, 141, 168, 233, 142, 144, 233, 142, 184, 233, 143, 160, 233, 144, 136, 233, 144, 176, 233, 145, 152, 233, 146, 128, 233, 146, 168, 233, 147, 144, 233, 147, 184, 233, 148, 160, 233, 149, 136, 233, 149, 176, 233, 150, 152, 233, 151, 128, 233, 151, 168, 233, 152, 144, 233, 152, 184, 233, 153, 160, 233, 154, 136, 233, 154, 176, 233, 155, 152, 233, 156, 128, 233, 156, 168, 233, 157, 144, 233, 157, 184, 233, 158, 160, 233, 159, 136, 233, 159, 176, 233, 160, 152, 233, 161, 128, 233, 161, 168, 233, 162, 144, 233, 162, 184, 233, 163, 160, 233, 164, 136, 233, 164, 176, 233, 165, 152, 233, 166, 128, 233, 166, 168, 233, 167, 144, 233, 167, 184, 233, 168, 160, 233, 169, 136, 233, 169, 176, 233, 170, 152, 233, 171, 128, 233, 171, 168, 233, 172, 144, 233, 172, 184, 233, 173, 160, 233, 174, 136, 233, 174, 176, 233, 175, 152, 233, 176, 128, 233, 176, 168, 233, 177, 144, 233, 177, 184, 233, 178, 160, 233, 179, 136, 233, 179, 176, 233, 180, 152, 233, 181, 128, 233, 181, 168, 233, 182, 144, 233, 182, 184, 233, 183, 160, 233, 184, 136, 233, 184, 176, 233, 185, 152, 233, 186, 128, 233, 186, 168, 233, 187, 144, 233, 187, 184, 233, 188, 160, 233, 189, 136, 233, 189, 176, 233, 190, 152, 233, 191, 128, 233, 191, 168, 234, 128, 144, 234, 128, 184, 234, 129, 160, 234, 130, 136, 234, 130, 176, 234, 131, 152, 234, 132, 128, 234, 132, 168, 234, 133, 144, 234, 133, 184, 234, 134, 160, 234, 135, 136, 234, 135, 176, 234, 136, 152, 234, 137, 128, 234, 137, 168, 234, 138, 144, 234, 138, 184, 234, 139, 160, 234, 140, 136, 234, 140, 176, 234, 141, 152, 234, 142, 128, 234, 142, 168, 234, 143, 144, 234, 143, 184, 234, 144, 160, 234, 145, 136, 234, 145, 176, 234, 146, 152, 234, 147, 128, 234, 147, 168, 234, 148, 144, 234, 148, 184, 234, 149, 160, 234, 150, 136, 234, 150, 176, 234, 151, 152, 234, 152, 128, 234, 152, 168, 234, 153, 144, 234, 153, 184, 234, 154, 160, 234, 155, 136, 234, 155, 176, 234, 156, 152, 234, 157, 128, 234, 157, 168, 234, 158, 144, 234, 158, 184, 234, 159, 160, 234, 160, 136, 234, 160, 176, 234, 161, 152, 234, 162, 128, 234, 162, 168, 234, 163, 144, 234, 163, 184, 234, 164, 160, 234, 165, 136, 234, 165, 176, 234, 166, 152, 234, 167, 128, 234, 167, 168, 234, 168, 144, 234, 168, 184, 234, 169, 160, 234, 170, 136, 234, 170, 176, 234, 171, 152, 234, 172, 128, 234, 172, 168, 234, 173, 144, 234, 173, 184, 234, 174, 160, 234, 175, 136, 234, 175, 176, 234, 176, 152, 234, 177, 128, 234, 177, 168, 234, 178, 144, 234, 178, 184, 234, 179, 160, 234, 180, 136, 234, 180, 176, 234, 181, 152, 234, 182, 128, 234, 182, 168, 234, 183, 144, 234, 183, 184, 234, 184, 160, 234, 185, 136, 234, 185, 176, 234, 186, 152, 234, 187, 128, 234, 187, 168, 234, 188, 144, 234, 188, 184, 234, 189, 160, 234, 190, 136, 234, 190, 176, 234, 191, 152, 235, 128, 128, 235, 128, 168, 235, 129, 144, 235, 129, 184, 235, 130, 160, 235, 131, 136, 235, 131, 176, 235, 132, 152, 235, 133, 128, 235, 133, 168, 235, 134, 144, 235, 134, 184, 235, 135, 160, 235, 136, 136, 235, 136, 176, 235, 137, 152, 235, 138, 128, 235, 138, 168, 235, 139, 144, 235, 139, 184, 235, 140, 160, 235, 141, 136, 235, 141, 176, 235, 142, 152, 235, 143, 128, 235, 143, 168, 235, 144, 144, 235, 144, 184, 235, 145, 160, 235, 146, 136, 235, 146, 176, 235, 147, 152, 235, 148, 128, 235, 148, 168, 235, 149, 144, 235, 149, 184, 235, 150, 160, 235, 151, 136, 235, 151, 176, 235, 152, 152, 235, 153, 128, 235, 153, 168, 235, 154, 144, 235, 154, 184, 235, 155, 160, 235, 156, 136, 235, 156, 176, 235, 157, 152, 235, 158, 128, 235, 158, 168, 235, 159, 144, 235, 159, 184, 235, 160, 160, 235, 161, 136, 235, 161, 176, 235, 162, 152, 235, 163, 128, 235, 163, 168, 235, 164, 144, 235, 164, 184, 235, 165, 160, 235, 166, 136, 235, 166, 176, 235, 167, 152, 235, 168, 128, 235, 168, 168, 235, 169, 144, 235, 169, 184, 235, 170, 160, 235, 171, 136, 235, 171, 176, 235, 172, 152, 235, 173, 128, 235, 173, 168, 235, 174, 144, 235, 174, 184, 235, 175, 160, 235, 176, 136, 235, 176, 176, 235, 177, 152, 235, 178, 128, 235, 178, 168, 235, 179, 144, 235, 179, 184, 235, 180, 160, 235, 181, 136, 235, 181, 176, 235, 182, 152, 235, 183, 128, 235, 183, 168, 235, 184, 144, 235, 184, 184, 235, 185, 160, 235, 186, 136, 235, 186, 176, 235, 187, 152, 235, 188, 128, 235, 188, 168, 235, 189, 144, 235, 189, 184, 235, 190, 160, 235, 191, 136, 235, 191, 176, 236, 128, 152, 236, 129, 128, 236, 129, 168, 236, 130, 144, 236, 130, 184, 236, 131, 160, 236, 132, 136, 236, 132, 176, 236, 133, 152, 236, 134, 128, 236, 134, 168, 236, 135, 144, 236, 135, 184, 236, 136, 160, 236, 137, 136, 236, 137, 176, 236, 138, 152, 236, 139, 128, 236, 139, 168, 236, 140, 144, 236, 140, 184, 236, 141, 160, 236, 142, 136, 236, 142, 176, 236, 143, 152, 236, 144, 128, 236, 144, 168, 236, 145, 144, 236, 145, 184, 236, 146, 160, 236, 147, 136, 236, 147, 176, 236, 148, 152, 236, 149, 128, 236, 149, 168, 236, 150, 144, 236, 150, 184, 236, 151, 160, 236, 152, 136, 236, 152, 176, 236, 153, 152, 236, 154, 128, 236, 154, 168, 236, 155, 144, 236, 155, 184, 236, 156, 160, 236, 157, 136, 236, 157, 176, 236, 158, 152, 236, 159, 128, 236, 159, 168, 236, 160, 144, 236, 160, 184, 236, 161, 160, 236, 162, 136, 236, 162, 176, 236, 163, 152, 236, 164, 128, 236, 164, 168, 236, 165, 144, 236, 165, 184, 236, 166, 160, 236, 167, 136, 236, 167, 176, 236, 168, 152, 236, 169, 128, 236, 169, 168, 236, 170, 144, 236, 170, 184, 236, 171, 160, 236, 172, 136, 236, 172, 176, 236, 173, 152, 236, 174, 128, 236, 174, 168, 236, 175, 144, 236, 175, 184, 236, 176, 160, 236, 177, 136, 236, 177, 176, 236, 178, 152, 236, 179, 128, 236, 179, 168, 236, 180, 144, 236, 180, 184, 236, 181, 160, 236, 182, 136, 236, 182, 176, 236, 183, 152, 236, 184, 128, 236, 184, 168, 236, 185, 144, 236, 185, 184, 236, 186, 160, 236, 187, 136, 236, 187, 176, 236, 188, 152, 236, 189, 128, 236, 189, 168, 236, 190, 144, 236, 190, 184, 236, 191, 160, 237, 128, 136, 237, 128, 176, 237, 129, 152, 237, 130, 128, 237, 130, 168, 237, 131, 144, 237, 131, 184, 237, 132, 160, 237, 133, 136, 237, 133, 176, 237, 134, 152, 237, 135, 128, 237, 135, 168, 237, 136, 144, 237, 136, 184, 237, 137, 160, 237, 138, 136, 237, 138, 176, 237, 139, 152, 237, 140, 128, 237, 140, 168, 237, 141, 144, 237, 141, 184, 237, 142, 160, 237, 143, 136, 237, 143, 176, 237, 144, 152, 237, 145, 128, 237, 145, 168, 237, 146, 144, 237, 146, 184, 237, 147, 160, 237, 148, 136, 237, 148, 176, 237, 149, 152, 237, 150, 128, 237, 150, 168, 237, 151, 144, 237, 151, 184, 237, 152, 160, 237, 153, 136, 237, 153, 176, 237, 154, 152, 237, 155, 128, 237, 155, 168, 237, 156, 144, 237, 156, 184, 237, 157, 160, 237, 158, 136, 237, 158, 176, 237, 159, 152, 238, 128, 128, 238, 128, 168, 238, 129, 144, 238, 129, 184, 238, 130, 160, 238, 131, 136, 238, 131, 176, 238, 132, 152, 238, 133, 128, 238, 133, 168, 238, 134, 144, 238, 134, 184, 238, 135, 160, 238, 136, 136, 238, 136, 176, 238, 137, 152, 238, 138, 128, 238, 138, 168, 238, 139, 144, 238, 139, 184, 238, 140, 160, 238, 141, 136, 238, 141, 176, 238, 142, 152, 238, 143, 128, 238, 143, 168, 238, 144, 144, 238, 144, 184, 238, 145, 160, 238, 146, 136, 238, 146, 176, 238, 147, 152, 238, 148, 128, 238, 148, 168, 238, 149, 144, 238, 149, 184, 238, 150, 160, 238, 151, 136, 238, 151, 176, 238, 152, 152, 238, 153, 128, 238, 153, 168, 238, 154, 144, 238, 154, 184, 238, 155, 160, 238, 156, 136, 238, 156, 176, 238, 157, 152, 238, 158, 128, 238, 158, 168, 238, 159, 144, 238, 159, 184, 238, 160, 160, 238, 161, 136, 238, 161, 176, 238, 162, 152, 238, 163, 128, 238, 163, 168, 238, 164, 144, 238, 164, 184, 238, 165, 160, 238, 166, 136, 238, 166, 176, 238, 167, 152, 238, 168, 128, 238, 168, 168, 238, 169, 144, 238, 169, 184, 238, 170, 160, 238, 171, 136, 238, 171, 176, 238, 172, 152, 238, 173, 128, 238, 173, 168, 238, 174, 144, 238, 174, 184, 238, 175, 160, 238, 176, 136, 238, 176, 176, 238, 177, 152, 238, 178, 128, 238, 178, 168, 238, 179, 144, 238, 179, 184, 238, 180, 160, 238, 181, 136, 238, 181, 176, 238, 182, 152, 238, 183, 128, 238, 183, 168, 238, 184, 144, 238, 184, 184, 238, 185, 160, 238, 186, 136, 238, 186, 176, 238, 187, 152, 238, 188, 128, 238, 188, 168, 238, 189, 144, 238, 189, 184, 238, 190, 160, 238, 191, 136, 238, 191, 176, 239, 128, 152, 239, 129, 128, 239, 129, 168, 239, 130, 144, 239, 130, 184, 239, 131, 160, 239, 132, 136, 239, 132, 176, 239, 133, 152, 239, 134, 128, 239, 134, 168, 239, 135, 144, 239, 135, 184, 239, 136, 160, 239, 137, 136, 239, 137, 176, 239, 138, 152, 239, 139, 128, 239, 139, 168, 239, 140, 144, 239, 140, 184, 239, 141, 160, 239, 142, 136, 239, 142, 176, 239, 143, 152, 239, 144, 128, 239, 144, 168, 239, 145, 144, 239, 145, 184, 239, 146, 160, 239, 147, 136, 239, 147, 176, 239, 148, 152, 239, 149, 128, 239, 149, 168, 239, 150, 144, 239, 150, 184, 239, 151, 160, 239, 152, 136, 239, 152, 176, 239, 153, 152, 239, 154, 128, 239, 154, 168, 239, 155, 144, 239, 155, 184, 239, 156, 160, 239, 157, 136, 239, 157, 176, 239, 158, 152, 239, 159, 128, 239, 159, 168, 239, 160, 144, 239, 160, 184, 239, 161, 160, 239, 162, 136, 239, 162, 176, 239, 163, 152, 239, 164, 128, 239, 164, 168, 239, 165, 144, 239, 165, 184, 239, 166, 160, 239, 167, 136, 239, 167, 176, 239, 168, 152, 239, 169, 128, 239, 169, 168, 239, 170, 144, 239, 170, 184, 239, 171, 160, 239, 172, 136, 239, 172, 176, 239, 173, 152, 239, 174, 128, 239, 174, 168, 239, 175, 144, 239, 175, 184, 239, 176, 160, 239, 177, 136, 239, 177, 176, 239, 178, 152, 239, 179, 128, 239, 179, 168, 239, 180, 144, 239, 180, 184, 239, 181, 160, 239, 182, 136, 239, 182, 176, 239, 183, 152, 239, 184, 128, 239, 184, 168, 239, 185, 144, 239, 185, 184, 239, 186, 160, 239, 187, 136, 239, 187, 176, 239, 188, 152, 239, 189, 128, 239, 189, 168, 239, 190, 144, 239, 190, 184, 239, 191, 160 }); super.setUp(); } }
googleapis/google-cloud-java
37,634
java-cloudbuild/proto-google-cloud-build-v1/src/main/java/com/google/cloudbuild/v1/DeleteWorkerPoolOperationMetadata.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/cloudbuild/v1/cloudbuild.proto // Protobuf Java Version: 3.25.8 package com.google.cloudbuild.v1; /** * * * <pre> * Metadata for the `DeleteWorkerPool` operation. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.DeleteWorkerPoolOperationMetadata} */ public final class DeleteWorkerPoolOperationMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) DeleteWorkerPoolOperationMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteWorkerPoolOperationMetadata.newBuilder() to construct. private DeleteWorkerPoolOperationMetadata( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteWorkerPoolOperationMetadata() { workerPool_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteWorkerPoolOperationMetadata(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_DeleteWorkerPoolOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_DeleteWorkerPoolOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.class, com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.Builder.class); } private int bitField0_; public static final int WORKER_POOL_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object workerPool_ = ""; /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The workerPool. */ @java.lang.Override public java.lang.String getWorkerPool() { java.lang.Object ref = workerPool_; 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(); workerPool_ = s; return s; } } /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for workerPool. */ @java.lang.Override public com.google.protobuf.ByteString getWorkerPoolBytes() { java.lang.Object ref = workerPool_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workerPool_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATE_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } public static final int COMPLETE_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp completeTime_; /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return Whether the completeTime field is set. */ @java.lang.Override public boolean hasCompleteTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return The completeTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCompleteTime() { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCompleteTimeOrBuilder() { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } 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(workerPool_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, workerPool_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getCompleteTime()); } 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(workerPool_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, workerPool_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCompleteTime()); } 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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata)) { return super.equals(obj); } com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata other = (com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) obj; if (!getWorkerPool().equals(other.getWorkerPool())) return false; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasCompleteTime() != other.hasCompleteTime()) return false; if (hasCompleteTime()) { if (!getCompleteTime().equals(other.getCompleteTime())) 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) + WORKER_POOL_FIELD_NUMBER; hash = (53 * hash) + getWorkerPool().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasCompleteTime()) { hash = (37 * hash) + COMPLETE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCompleteTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata 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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata 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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata 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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata 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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Metadata for the `DeleteWorkerPool` operation. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.DeleteWorkerPoolOperationMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_DeleteWorkerPoolOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_DeleteWorkerPoolOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.class, com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.Builder.class); } // Construct using com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCreateTimeFieldBuilder(); getCompleteTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; workerPool_ = ""; createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } completeTime_ = null; if (completeTimeBuilder_ != null) { completeTimeBuilder_.dispose(); completeTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_DeleteWorkerPoolOperationMetadata_descriptor; } @java.lang.Override public com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata getDefaultInstanceForType() { return com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.getDefaultInstance(); } @java.lang.Override public com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata build() { com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata buildPartial() { com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata result = new com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.workerPool_ = workerPool_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.completeTime_ = completeTimeBuilder_ == null ? completeTime_ : completeTimeBuilder_.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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) { return mergeFrom((com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata other) { if (other == com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata.getDefaultInstance()) return this; if (!other.getWorkerPool().isEmpty()) { workerPool_ = other.workerPool_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasCompleteTime()) { mergeCompleteTime(other.getCompleteTime()); } 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: { workerPool_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getCompleteTimeFieldBuilder().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 workerPool_ = ""; /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The workerPool. */ public java.lang.String getWorkerPool() { java.lang.Object ref = workerPool_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workerPool_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for workerPool. */ public com.google.protobuf.ByteString getWorkerPoolBytes() { java.lang.Object ref = workerPool_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workerPool_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The workerPool to set. * @return This builder for chaining. */ public Builder setWorkerPool(java.lang.String value) { if (value == null) { throw new NullPointerException(); } workerPool_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearWorkerPool() { workerPool_ = getDefaultInstance().getWorkerPool(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The resource name of the `WorkerPool` being deleted. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for workerPool to set. * @return This builder for chaining. */ public Builder setWorkerPoolBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); workerPool_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; } else { createTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && createTime_ != null && createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCreateTimeBuilder().mergeFrom(value); } else { createTime_ = value; } } else { createTimeBuilder_.mergeFrom(value); } if (createTime_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder clearCreateTime() { bitField0_ = (bitField0_ & ~0x00000002); createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.protobuf.Timestamp completeTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> completeTimeBuilder_; /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return Whether the completeTime field is set. */ public boolean hasCompleteTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return The completeTime. */ public com.google.protobuf.Timestamp getCompleteTime() { if (completeTimeBuilder_ == null) { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } else { return completeTimeBuilder_.getMessage(); } } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder setCompleteTime(com.google.protobuf.Timestamp value) { if (completeTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } completeTime_ = value; } else { completeTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder setCompleteTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (completeTimeBuilder_ == null) { completeTime_ = builderForValue.build(); } else { completeTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder mergeCompleteTime(com.google.protobuf.Timestamp value) { if (completeTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && completeTime_ != null && completeTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCompleteTimeBuilder().mergeFrom(value); } else { completeTime_ = value; } } else { completeTimeBuilder_.mergeFrom(value); } if (completeTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder clearCompleteTime() { bitField0_ = (bitField0_ & ~0x00000004); completeTime_ = null; if (completeTimeBuilder_ != null) { completeTimeBuilder_.dispose(); completeTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public com.google.protobuf.Timestamp.Builder getCompleteTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getCompleteTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public com.google.protobuf.TimestampOrBuilder getCompleteTimeOrBuilder() { if (completeTimeBuilder_ != null) { return completeTimeBuilder_.getMessageOrBuilder(); } else { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCompleteTimeFieldBuilder() { if (completeTimeBuilder_ == null) { completeTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCompleteTime(), getParentForChildren(), isClean()); completeTime_ = null; } return completeTimeBuilder_; } @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.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) } // @@protoc_insertion_point(class_scope:google.devtools.cloudbuild.v1.DeleteWorkerPoolOperationMetadata) private static final com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata(); } public static com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteWorkerPoolOperationMetadata> PARSER = new com.google.protobuf.AbstractParser<DeleteWorkerPoolOperationMetadata>() { @java.lang.Override public DeleteWorkerPoolOperationMetadata 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<DeleteWorkerPoolOperationMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteWorkerPoolOperationMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloudbuild.v1.DeleteWorkerPoolOperationMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,634
java-cloudbuild/proto-google-cloud-build-v1/src/main/java/com/google/cloudbuild/v1/UpdateWorkerPoolOperationMetadata.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/cloudbuild/v1/cloudbuild.proto // Protobuf Java Version: 3.25.8 package com.google.cloudbuild.v1; /** * * * <pre> * Metadata for the `UpdateWorkerPool` operation. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.UpdateWorkerPoolOperationMetadata} */ public final class UpdateWorkerPoolOperationMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) UpdateWorkerPoolOperationMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateWorkerPoolOperationMetadata.newBuilder() to construct. private UpdateWorkerPoolOperationMetadata( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateWorkerPoolOperationMetadata() { workerPool_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateWorkerPoolOperationMetadata(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_UpdateWorkerPoolOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_UpdateWorkerPoolOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.class, com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.Builder.class); } private int bitField0_; public static final int WORKER_POOL_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object workerPool_ = ""; /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The workerPool. */ @java.lang.Override public java.lang.String getWorkerPool() { java.lang.Object ref = workerPool_; 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(); workerPool_ = s; return s; } } /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for workerPool. */ @java.lang.Override public com.google.protobuf.ByteString getWorkerPoolBytes() { java.lang.Object ref = workerPool_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workerPool_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATE_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } public static final int COMPLETE_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp completeTime_; /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return Whether the completeTime field is set. */ @java.lang.Override public boolean hasCompleteTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return The completeTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCompleteTime() { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCompleteTimeOrBuilder() { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } 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(workerPool_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, workerPool_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getCompleteTime()); } 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(workerPool_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, workerPool_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCompleteTime()); } 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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata)) { return super.equals(obj); } com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata other = (com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) obj; if (!getWorkerPool().equals(other.getWorkerPool())) return false; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasCompleteTime() != other.hasCompleteTime()) return false; if (hasCompleteTime()) { if (!getCompleteTime().equals(other.getCompleteTime())) 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) + WORKER_POOL_FIELD_NUMBER; hash = (53 * hash) + getWorkerPool().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasCompleteTime()) { hash = (37 * hash) + COMPLETE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCompleteTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata 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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata 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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata 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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata 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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Metadata for the `UpdateWorkerPool` operation. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.UpdateWorkerPoolOperationMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_UpdateWorkerPoolOperationMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_UpdateWorkerPoolOperationMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.class, com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.Builder.class); } // Construct using com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCreateTimeFieldBuilder(); getCompleteTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; workerPool_ = ""; createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } completeTime_ = null; if (completeTimeBuilder_ != null) { completeTimeBuilder_.dispose(); completeTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_UpdateWorkerPoolOperationMetadata_descriptor; } @java.lang.Override public com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata getDefaultInstanceForType() { return com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.getDefaultInstance(); } @java.lang.Override public com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata build() { com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata buildPartial() { com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata result = new com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.workerPool_ = workerPool_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.completeTime_ = completeTimeBuilder_ == null ? completeTime_ : completeTimeBuilder_.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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) { return mergeFrom((com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata other) { if (other == com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata.getDefaultInstance()) return this; if (!other.getWorkerPool().isEmpty()) { workerPool_ = other.workerPool_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasCompleteTime()) { mergeCompleteTime(other.getCompleteTime()); } 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: { workerPool_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getCompleteTimeFieldBuilder().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 workerPool_ = ""; /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The workerPool. */ public java.lang.String getWorkerPool() { java.lang.Object ref = workerPool_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); workerPool_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for workerPool. */ public com.google.protobuf.ByteString getWorkerPoolBytes() { java.lang.Object ref = workerPool_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); workerPool_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The workerPool to set. * @return This builder for chaining. */ public Builder setWorkerPool(java.lang.String value) { if (value == null) { throw new NullPointerException(); } workerPool_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearWorkerPool() { workerPool_ = getDefaultInstance().getWorkerPool(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The resource name of the `WorkerPool` being updated. * Format: * `projects/{project}/locations/{location}/workerPools/{worker_pool}`. * </pre> * * <code>string worker_pool = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for workerPool to set. * @return This builder for chaining. */ public Builder setWorkerPoolBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); workerPool_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; } else { createTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && createTime_ != null && createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCreateTimeBuilder().mergeFrom(value); } else { createTime_ = value; } } else { createTimeBuilder_.mergeFrom(value); } if (createTime_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public Builder clearCreateTime() { bitField0_ = (bitField0_ & ~0x00000002); createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Time the operation was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.protobuf.Timestamp completeTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> completeTimeBuilder_; /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return Whether the completeTime field is set. */ public boolean hasCompleteTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> * * @return The completeTime. */ public com.google.protobuf.Timestamp getCompleteTime() { if (completeTimeBuilder_ == null) { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } else { return completeTimeBuilder_.getMessage(); } } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder setCompleteTime(com.google.protobuf.Timestamp value) { if (completeTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } completeTime_ = value; } else { completeTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder setCompleteTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (completeTimeBuilder_ == null) { completeTime_ = builderForValue.build(); } else { completeTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder mergeCompleteTime(com.google.protobuf.Timestamp value) { if (completeTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && completeTime_ != null && completeTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCompleteTimeBuilder().mergeFrom(value); } else { completeTime_ = value; } } else { completeTimeBuilder_.mergeFrom(value); } if (completeTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public Builder clearCompleteTime() { bitField0_ = (bitField0_ & ~0x00000004); completeTime_ = null; if (completeTimeBuilder_ != null) { completeTimeBuilder_.dispose(); completeTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public com.google.protobuf.Timestamp.Builder getCompleteTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getCompleteTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ public com.google.protobuf.TimestampOrBuilder getCompleteTimeOrBuilder() { if (completeTimeBuilder_ != null) { return completeTimeBuilder_.getMessageOrBuilder(); } else { return completeTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : completeTime_; } } /** * * * <pre> * Time the operation was completed. * </pre> * * <code>.google.protobuf.Timestamp complete_time = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCompleteTimeFieldBuilder() { if (completeTimeBuilder_ == null) { completeTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCompleteTime(), getParentForChildren(), isClean()); completeTime_ = null; } return completeTimeBuilder_; } @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.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) } // @@protoc_insertion_point(class_scope:google.devtools.cloudbuild.v1.UpdateWorkerPoolOperationMetadata) private static final com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata(); } public static com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateWorkerPoolOperationMetadata> PARSER = new com.google.protobuf.AbstractParser<UpdateWorkerPoolOperationMetadata>() { @java.lang.Override public UpdateWorkerPoolOperationMetadata 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<UpdateWorkerPoolOperationMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateWorkerPoolOperationMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloudbuild.v1.UpdateWorkerPoolOperationMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,869
java-compute/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/RegionInstanceTemplatesClient.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.compute.v1; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.longrunning.OperationFuture; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.compute.v1.stub.RegionInstanceTemplatesStub; import com.google.cloud.compute.v1.stub.RegionInstanceTemplatesStubSettings; import com.google.common.util.concurrent.MoreExecutors; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: The RegionInstanceTemplates API. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * String project = "project-309310695"; * String region = "region-934795532"; * String instanceTemplate = "instanceTemplate1009541167"; * InstanceTemplate response = * regionInstanceTemplatesClient.get(project, region, instanceTemplate); * } * }</pre> * * <p>Note: close() needs to be called on the RegionInstanceTemplatesClient object to clean up * resources such as threads. In the example above, try-with-resources is used, which automatically * calls close(). * * <table> * <caption>Methods</caption> * <tr> * <th>Method</th> * <th>Description</th> * <th>Method Variants</th> * </tr> * <tr> * <td><p> Delete</td> * <td><p> Deletes the specified instance template. Deleting an instance template is permanent and cannot be undone.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> deleteAsync(DeleteRegionInstanceTemplateRequest request) * </ul> * <p>Methods that return long-running operations have "Async" method variants that return `OperationFuture`, which is used to track polling of the service.</p> * <ul> * <li><p> deleteAsync(String project, String region, String instanceTemplate) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> deleteOperationCallable() * <li><p> deleteCallable() * </ul> * </td> * </tr> * <tr> * <td><p> Get</td> * <td><p> Returns the specified instance template.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> get(GetRegionInstanceTemplateRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> get(String project, String region, String instanceTemplate) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getCallable() * </ul> * </td> * </tr> * <tr> * <td><p> Insert</td> * <td><p> Creates an instance template in the specified project and region using the global instance template whose URL is included in the request.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> insertAsync(InsertRegionInstanceTemplateRequest request) * </ul> * <p>Methods that return long-running operations have "Async" method variants that return `OperationFuture`, which is used to track polling of the service.</p> * <ul> * <li><p> insertAsync(String project, String region, InstanceTemplate instanceTemplateResource) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> insertOperationCallable() * <li><p> insertCallable() * </ul> * </td> * </tr> * <tr> * <td><p> List</td> * <td><p> Retrieves a list of instance templates that are contained within the specified project and region.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> list(ListRegionInstanceTemplatesRequest request) * </ul> * <p>"Flattened" method variants have converted the fields of the request object into function parameters to enable multiple ways to call the same method.</p> * <ul> * <li><p> list(String project, String region) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> listPagedCallable() * <li><p> listCallable() * </ul> * </td> * </tr> * </table> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of * RegionInstanceTemplatesSettings to create(). For example: * * <p>To customize credentials: * * <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 * RegionInstanceTemplatesSettings regionInstanceTemplatesSettings = * RegionInstanceTemplatesSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create(regionInstanceTemplatesSettings); * }</pre> * * <p>To customize the endpoint: * * <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 * RegionInstanceTemplatesSettings regionInstanceTemplatesSettings = * RegionInstanceTemplatesSettings.newBuilder().setEndpoint(myEndpoint).build(); * RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create(regionInstanceTemplatesSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class RegionInstanceTemplatesClient implements BackgroundResource { private final RegionInstanceTemplatesSettings settings; private final RegionInstanceTemplatesStub stub; /** Constructs an instance of RegionInstanceTemplatesClient with default settings. */ public static final RegionInstanceTemplatesClient create() throws IOException { return create(RegionInstanceTemplatesSettings.newBuilder().build()); } /** * Constructs an instance of RegionInstanceTemplatesClient, using the given settings. The channels * are created based on the settings passed in, or defaults for any settings that are not set. */ public static final RegionInstanceTemplatesClient create(RegionInstanceTemplatesSettings settings) throws IOException { return new RegionInstanceTemplatesClient(settings); } /** * Constructs an instance of RegionInstanceTemplatesClient, using the given stub for making calls. * This is for advanced usage - prefer using create(RegionInstanceTemplatesSettings). */ public static final RegionInstanceTemplatesClient create(RegionInstanceTemplatesStub stub) { return new RegionInstanceTemplatesClient(stub); } /** * Constructs an instance of RegionInstanceTemplatesClient, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected RegionInstanceTemplatesClient(RegionInstanceTemplatesSettings settings) throws IOException { this.settings = settings; this.stub = ((RegionInstanceTemplatesStubSettings) settings.getStubSettings()).createStub(); } protected RegionInstanceTemplatesClient(RegionInstanceTemplatesStub stub) { this.settings = null; this.stub = stub; } public final RegionInstanceTemplatesSettings getSettings() { return settings; } public RegionInstanceTemplatesStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified instance template. Deleting an instance template is permanent and cannot * be undone. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * String project = "project-309310695"; * String region = "region-934795532"; * String instanceTemplate = "instanceTemplate1009541167"; * Operation response = * regionInstanceTemplatesClient.deleteAsync(project, region, instanceTemplate).get(); * } * }</pre> * * @param project Project ID for this request. * @param region The name of the region for this request. * @param instanceTemplate The name of the instance template to delete. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Operation, Operation> deleteAsync( String project, String region, String instanceTemplate) { DeleteRegionInstanceTemplateRequest request = DeleteRegionInstanceTemplateRequest.newBuilder() .setProject(project) .setRegion(region) .setInstanceTemplate(instanceTemplate) .build(); return deleteAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified instance template. Deleting an instance template is permanent and cannot * be undone. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * DeleteRegionInstanceTemplateRequest request = * DeleteRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplate("instanceTemplate1009541167") * .setProject("project-309310695") * .setRegion("region-934795532") * .setRequestId("requestId693933066") * .build(); * Operation response = regionInstanceTemplatesClient.deleteAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Operation, Operation> deleteAsync( DeleteRegionInstanceTemplateRequest request) { return deleteOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified instance template. Deleting an instance template is permanent and cannot * be undone. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * DeleteRegionInstanceTemplateRequest request = * DeleteRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplate("instanceTemplate1009541167") * .setProject("project-309310695") * .setRegion("region-934795532") * .setRequestId("requestId693933066") * .build(); * OperationFuture<Operation, Operation> future = * regionInstanceTemplatesClient.deleteOperationCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final OperationCallable<DeleteRegionInstanceTemplateRequest, Operation, Operation> deleteOperationCallable() { return stub.deleteOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Deletes the specified instance template. Deleting an instance template is permanent and cannot * be undone. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * DeleteRegionInstanceTemplateRequest request = * DeleteRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplate("instanceTemplate1009541167") * .setProject("project-309310695") * .setRegion("region-934795532") * .setRequestId("requestId693933066") * .build(); * ApiFuture<Operation> future = * regionInstanceTemplatesClient.deleteCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<DeleteRegionInstanceTemplateRequest, Operation> deleteCallable() { return stub.deleteCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the specified instance template. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * String project = "project-309310695"; * String region = "region-934795532"; * String instanceTemplate = "instanceTemplate1009541167"; * InstanceTemplate response = * regionInstanceTemplatesClient.get(project, region, instanceTemplate); * } * }</pre> * * @param project Project ID for this request. * @param region The name of the region for this request. * @param instanceTemplate The name of the instance template. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final InstanceTemplate get(String project, String region, String instanceTemplate) { GetRegionInstanceTemplateRequest request = GetRegionInstanceTemplateRequest.newBuilder() .setProject(project) .setRegion(region) .setInstanceTemplate(instanceTemplate) .build(); return get(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the specified instance template. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * GetRegionInstanceTemplateRequest request = * GetRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplate("instanceTemplate1009541167") * .setProject("project-309310695") * .setRegion("region-934795532") * .build(); * InstanceTemplate response = regionInstanceTemplatesClient.get(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final InstanceTemplate get(GetRegionInstanceTemplateRequest request) { return getCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the specified instance template. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * GetRegionInstanceTemplateRequest request = * GetRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplate("instanceTemplate1009541167") * .setProject("project-309310695") * .setRegion("region-934795532") * .build(); * ApiFuture<InstanceTemplate> future = * regionInstanceTemplatesClient.getCallable().futureCall(request); * // Do something. * InstanceTemplate response = future.get(); * } * }</pre> */ public final UnaryCallable<GetRegionInstanceTemplateRequest, InstanceTemplate> getCallable() { return stub.getCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates an instance template in the specified project and region using the global instance * template whose URL is included in the request. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * String project = "project-309310695"; * String region = "region-934795532"; * InstanceTemplate instanceTemplateResource = InstanceTemplate.newBuilder().build(); * Operation response = * regionInstanceTemplatesClient * .insertAsync(project, region, instanceTemplateResource) * .get(); * } * }</pre> * * @param project Project ID for this request. * @param region The name of the region for this request. * @param instanceTemplateResource The body resource for this request * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Operation, Operation> insertAsync( String project, String region, InstanceTemplate instanceTemplateResource) { InsertRegionInstanceTemplateRequest request = InsertRegionInstanceTemplateRequest.newBuilder() .setProject(project) .setRegion(region) .setInstanceTemplateResource(instanceTemplateResource) .build(); return insertAsync(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates an instance template in the specified project and region using the global instance * template whose URL is included in the request. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * InsertRegionInstanceTemplateRequest request = * InsertRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplateResource(InstanceTemplate.newBuilder().build()) * .setProject("project-309310695") * .setRegion("region-934795532") * .setRequestId("requestId693933066") * .build(); * Operation response = regionInstanceTemplatesClient.insertAsync(request).get(); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final OperationFuture<Operation, Operation> insertAsync( InsertRegionInstanceTemplateRequest request) { return insertOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates an instance template in the specified project and region using the global instance * template whose URL is included in the request. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * InsertRegionInstanceTemplateRequest request = * InsertRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplateResource(InstanceTemplate.newBuilder().build()) * .setProject("project-309310695") * .setRegion("region-934795532") * .setRequestId("requestId693933066") * .build(); * OperationFuture<Operation, Operation> future = * regionInstanceTemplatesClient.insertOperationCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final OperationCallable<InsertRegionInstanceTemplateRequest, Operation, Operation> insertOperationCallable() { return stub.insertOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Creates an instance template in the specified project and region using the global instance * template whose URL is included in the request. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * InsertRegionInstanceTemplateRequest request = * InsertRegionInstanceTemplateRequest.newBuilder() * .setInstanceTemplateResource(InstanceTemplate.newBuilder().build()) * .setProject("project-309310695") * .setRegion("region-934795532") * .setRequestId("requestId693933066") * .build(); * ApiFuture<Operation> future = * regionInstanceTemplatesClient.insertCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<InsertRegionInstanceTemplateRequest, Operation> insertCallable() { return stub.insertCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves a list of instance templates that are contained within the specified project and * region. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * String project = "project-309310695"; * String region = "region-934795532"; * for (InstanceTemplate element : * regionInstanceTemplatesClient.list(project, region).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param project Project ID for this request. * @param region The name of the regions for this request. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListPagedResponse list(String project, String region) { ListRegionInstanceTemplatesRequest request = ListRegionInstanceTemplatesRequest.newBuilder() .setProject(project) .setRegion(region) .build(); return list(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves a list of instance templates that are contained within the specified project and * region. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * ListRegionInstanceTemplatesRequest request = * ListRegionInstanceTemplatesRequest.newBuilder() * .setFilter("filter-1274492040") * .setMaxResults(1128457243) * .setOrderBy("orderBy-1207110587") * .setPageToken("pageToken873572522") * .setProject("project-309310695") * .setRegion("region-934795532") * .setReturnPartialSuccess(true) * .build(); * for (InstanceTemplate element : regionInstanceTemplatesClient.list(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListPagedResponse list(ListRegionInstanceTemplatesRequest request) { return listPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves a list of instance templates that are contained within the specified project and * region. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * ListRegionInstanceTemplatesRequest request = * ListRegionInstanceTemplatesRequest.newBuilder() * .setFilter("filter-1274492040") * .setMaxResults(1128457243) * .setOrderBy("orderBy-1207110587") * .setPageToken("pageToken873572522") * .setProject("project-309310695") * .setRegion("region-934795532") * .setReturnPartialSuccess(true) * .build(); * ApiFuture<InstanceTemplate> future = * regionInstanceTemplatesClient.listPagedCallable().futureCall(request); * // Do something. * for (InstanceTemplate element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListRegionInstanceTemplatesRequest, ListPagedResponse> listPagedCallable() { return stub.listPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves a list of instance templates that are contained within the specified project and * region. * * <p>Sample code: * * <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 * try (RegionInstanceTemplatesClient regionInstanceTemplatesClient = * RegionInstanceTemplatesClient.create()) { * ListRegionInstanceTemplatesRequest request = * ListRegionInstanceTemplatesRequest.newBuilder() * .setFilter("filter-1274492040") * .setMaxResults(1128457243) * .setOrderBy("orderBy-1207110587") * .setPageToken("pageToken873572522") * .setProject("project-309310695") * .setRegion("region-934795532") * .setReturnPartialSuccess(true) * .build(); * while (true) { * InstanceTemplateList response = regionInstanceTemplatesClient.listCallable().call(request); * for (InstanceTemplate element : response.getItemsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListRegionInstanceTemplatesRequest, InstanceTemplateList> listCallable() { return stub.listCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListPagedResponse extends AbstractPagedListResponse< ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate, ListPage, ListFixedSizeCollection> { public static ApiFuture<ListPagedResponse> createAsync( PageContext<ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate> context, ApiFuture<InstanceTemplateList> futureResponse) { ApiFuture<ListPage> futurePage = ListPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListPagedResponse(input), MoreExecutors.directExecutor()); } private ListPagedResponse(ListPage page) { super(page, ListFixedSizeCollection.createEmptyCollection()); } } public static class ListPage extends AbstractPage< ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate, ListPage> { private ListPage( PageContext<ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate> context, InstanceTemplateList response) { super(context, response); } private static ListPage createEmptyPage() { return new ListPage(null, null); } @Override protected ListPage createPage( PageContext<ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate> context, InstanceTemplateList response) { return new ListPage(context, response); } @Override public ApiFuture<ListPage> createPageAsync( PageContext<ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate> context, ApiFuture<InstanceTemplateList> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListFixedSizeCollection extends AbstractFixedSizeCollection< ListRegionInstanceTemplatesRequest, InstanceTemplateList, InstanceTemplate, ListPage, ListFixedSizeCollection> { private ListFixedSizeCollection(List<ListPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListFixedSizeCollection createEmptyCollection() { return new ListFixedSizeCollection(null, 0); } @Override protected ListFixedSizeCollection createCollection(List<ListPage> pages, int collectionSize) { return new ListFixedSizeCollection(pages, collectionSize); } } }
apache/incubator-hugegraph
37,922
hugegraph-store/hg-store-core/src/main/java/org/apache/hugegraph/store/business/BusinessHandlerImpl.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.hugegraph.store.business; import static org.apache.hugegraph.store.util.HgStoreConst.EMPTY_BYTES; import static org.apache.hugegraph.store.util.HgStoreConst.SCAN_ALL_PARTITIONS_ID; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.annotation.concurrent.NotThreadSafe; import org.apache.commons.configuration2.MapConfiguration; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.hugegraph.config.HugeConfig; import org.apache.hugegraph.config.OptionSpace; import org.apache.hugegraph.pd.grpc.pulse.CleanType; import org.apache.hugegraph.rocksdb.access.DBStoreException; import org.apache.hugegraph.rocksdb.access.RocksDBFactory; import org.apache.hugegraph.rocksdb.access.RocksDBFactory.RocksdbChangedListener; import org.apache.hugegraph.rocksdb.access.RocksDBOptions; import org.apache.hugegraph.rocksdb.access.RocksDBSession; import org.apache.hugegraph.rocksdb.access.ScanIterator; import org.apache.hugegraph.rocksdb.access.SessionOperator; import org.apache.hugegraph.store.HgStoreEngine; import org.apache.hugegraph.store.cmd.CleanDataRequest; import org.apache.hugegraph.store.grpc.Graphpb.ScanPartitionRequest; import org.apache.hugegraph.store.grpc.Graphpb.ScanPartitionRequest.Request; import org.apache.hugegraph.store.grpc.Graphpb.ScanPartitionRequest.ScanType; import org.apache.hugegraph.store.meta.Partition; import org.apache.hugegraph.store.meta.PartitionManager; import org.apache.hugegraph.store.meta.asynctask.AsyncTaskState; import org.apache.hugegraph.store.meta.asynctask.CleanTask; import org.apache.hugegraph.store.metric.HgStoreMetric; import org.apache.hugegraph.store.pd.PdProvider; import org.apache.hugegraph.store.term.Bits; import org.apache.hugegraph.store.term.HgPair; import org.apache.hugegraph.store.util.HgStoreException; import org.rocksdb.Cache; import org.rocksdb.MemoryUsageType; import com.alipay.sofa.jraft.util.Utils; import lombok.extern.slf4j.Slf4j; @Slf4j public class BusinessHandlerImpl implements BusinessHandler { private static final int batchSize = 10000; private static final RocksDBFactory factory = RocksDBFactory.getInstance(); private static final HashMap<ScanType, String> tableMapping = new HashMap<>() {{ put(ScanType.SCAN_VERTEX, tableVertex); put(ScanType.SCAN_EDGE, tableOutEdge); }}; private static final Map<Integer, String> dbNames = new ConcurrentHashMap<>(); static { int code = tableUnknown.hashCode(); code = tableVertex.hashCode(); code = tableOutEdge.hashCode(); code = tableInEdge.hashCode(); code = tableIndex.hashCode(); code = tableTask.hashCode(); code = tableTask.hashCode(); log.debug("init table code:{}", code); } private final PartitionManager partitionManager; private final PdProvider provider; private final InnerKeyCreator keyCreator; public BusinessHandlerImpl(PartitionManager partitionManager) { this.partitionManager = partitionManager; this.provider = partitionManager.getPdProvider(); this.keyCreator = new InnerKeyCreator(this); factory.addRocksdbChangedListener(new RocksdbChangedListener() { @Override public void onDBDeleteBegin(String dbName, String filePath) { partitionManager.getDeletedFileManager().addDeletedFile(filePath); } @Override public void onDBDeleted(String dbName, String filePath) { partitionManager.getDeletedFileManager().removeDeletedFile(filePath); } @Override public void onDBSessionReleased(RocksDBSession dbSession) { } }); } public static HugeConfig initRocksdb(Map<String, Object> rocksdbConfig, RocksdbChangedListener listener) { // Register rocksdb configuration OptionSpace.register("rocksdb", "org.apache.hugegraph.rocksdb.access.RocksDBOptions"); RocksDBOptions.instance(); HugeConfig hConfig = new HugeConfig(new MapConfiguration(rocksdbConfig)); factory.setHugeConfig(hConfig); if (listener != null) { factory.addRocksdbChangedListener(listener); } return hConfig; } public static String getDbName(int partId) { String dbName = dbNames.get(partId); if (dbName == null) { dbName = String.format("%05d", partId); dbNames.put(partId, dbName); } // Each partition corresponds to a rocksdb instance, so the rocksdb instance name is partId. return dbName; } @Override public void doPut(String graph, int code, String table, byte[] key, byte[] value) throws HgStoreException { int partId = provider.getPartitionByCode(graph, code).getId(); try (RocksDBSession dbSession = getSession(graph, table, partId)) { SessionOperator op = dbSession.sessionOp(); try { op.prepare(); byte[] targetKey = keyCreator.getKey(partId, graph, code, key); op.put(table, targetKey, value); op.commit(); } catch (Exception e) { log.error("Graph " + graph + " doPut exception", e); op.rollback(); throw new HgStoreException(HgStoreException.EC_RKDB_DOPUT_FAIL, e.toString()); } } } @Override public byte[] doGet(String graph, int code, String table, byte[] key) throws HgStoreException { int partId = provider.getPartitionByCode(graph, code).getId(); try (RocksDBSession dbSession = getSession(graph, table, partId)) { byte[] targetKey = keyCreator.getKey(partId, graph, code, key); return dbSession.sessionOp().get(table, targetKey); } catch (Exception e) { log.error("Graph " + graph + " doGet exception", e); throw new HgStoreException(HgStoreException.EC_RKDB_DOGET_FAIL, e.toString()); } } @Override public ScanIterator scanAll(String graph, String table) throws HgStoreException { List<Integer> ids = this.getLeaderPartitionIds(graph); BiFunction<Integer, byte[], ScanIterator> function = (id, position) -> { try (RocksDBSession dbSession = getSession(graph, table, id)) { return new InnerKeyFilter(dbSession.sessionOp().scan(table, position == null ? keyCreator.getStartKey( id, graph) : keyCreator.getStartKey( id, graph, position), keyCreator.getEndKey(id, graph), ScanIterator.Trait.SCAN_LT_END)); } }; return MultiPartitionIterator.of(ids, function); } @Override public ScanIterator scanAll(String graph, String table, byte[] query) throws HgStoreException { return scanAll(graph, table); } @Override public ScanIterator scan(String graph, int code, String table, byte[] start, byte[] end, int scanType) throws HgStoreException { List<Integer> ids; if (code == SCAN_ALL_PARTITIONS_ID) { ids = this.getLeaderPartitionIds(graph); } else { ids = new ArrayList<>(); ids.add(partitionManager.getPartitionIdByCode(graph, code)); } BiFunction<Integer, byte[], ScanIterator> function = (id, position) -> { byte[] endKey; int type; if (ArrayUtils.isEmpty(end)) { endKey = keyCreator.getEndKey(id, graph); type = ScanIterator.Trait.SCAN_LT_END; } else { endKey = keyCreator.getEndKey(id, graph, end); type = scanType; } try (RocksDBSession dbSession = getSession(graph, table, id)) { return new InnerKeyFilter(dbSession.sessionOp().scan(table, keyCreator.getStartKey(id, graph, toPosition( start, position)), endKey, type)); } }; return MultiPartitionIterator.of(ids, function); } /** * According to keyCode range return data, left closed right open. * * @param graph * @param table * @param codeFrom Starting code, including this value * @param codeTo End code, does not include this value * @return * @throws HgStoreException */ @Override public ScanIterator scan(String graph, String table, int codeFrom, int codeTo) throws HgStoreException { List<Integer> ids = new ArrayList<>(); ids.add(partitionManager.getPartitionIdByCode(graph, codeFrom)); BiFunction<Integer, byte[], ScanIterator> function = (id, position) -> { try (RocksDBSession dbSession = getSession(graph, table, id)) { byte[] startKey; if (position != null) { startKey = keyCreator.getStartKey(id, graph, position); } else { startKey = keyCreator.getStartKey(id, graph); } byte[] endKey = keyCreator.getEndKey(id, graph); ScanIterator iterator = dbSession.sessionOp().scan(table, startKey, endKey, ScanIterator.Trait.SCAN_LT_END); return new InnerKeyFilter(iterator, codeFrom, codeTo); } }; return MultiPartitionIterator.of(ids, function); } @Override public ScanIterator scan(String graph, int code, String table, byte[] start, byte[] end, int scanType, byte[] conditionQuery) throws HgStoreException { ScanIterator it = null; if ((scanType & ScanIterator.Trait.SCAN_HASHCODE) == ScanIterator.Trait.SCAN_HASHCODE) { int codeFrom = Bits.toInt(start); int codeTo = Bits.toInt(end); it = scan(graph, table, codeFrom, codeTo); } else { it = scan(graph, code, table, start, end, scanType); } return it; } @Override public GraphStoreIterator scan(ScanPartitionRequest spr) throws HgStoreException { return new GraphStoreIterator(scanOriginal(spr), spr); } @Override public ScanIterator scanOriginal(ScanPartitionRequest spr) throws HgStoreException { Request request = spr.getScanRequest(); String graph = request.getGraphName(); List<Integer> ids; int partitionId = request.getPartitionId(); int startCode = request.getStartCode(); int endCode = request.getEndCode(); if (partitionId == SCAN_ALL_PARTITIONS_ID) { ids = this.getLeaderPartitionIds(graph); } else { ids = new ArrayList<>(); if (startCode != 0 || endCode != 0) { ids.add(partitionManager.getPartitionIdByCode(graph, startCode)); } else { ids.add(partitionId); } } String table = request.getTable(); if (StringUtils.isEmpty(table)) { table = tableMapping.get(request.getScanType()); } int scanType = request.getBoundary(); if (scanType == 0) { scanType = ScanIterator.Trait.SCAN_LT_END; } String tab = table; int st = scanType; BiFunction<Integer, byte[], ScanIterator> func = (id, position) -> { try (RocksDBSession dbSession = getSession(graph, tab, id)) { byte[] startPos = toPosition(EMPTY_BYTES, position); byte[] startKey = keyCreator.getStartKey(id, graph, startPos); byte[] endKey = keyCreator.getEndKey(id, graph); ScanIterator iter = dbSession.sessionOp().scan(tab, startKey, endKey, st); return new InnerKeyFilter(iter); } }; return MultiPartitionIterator.of(ids, func); } @Override public ScanIterator scanPrefix(String graph, int code, String table, byte[] prefix, int scanType) throws HgStoreException { List<Integer> ids; if (code == SCAN_ALL_PARTITIONS_ID) { ids = this.getLeaderPartitionIds(graph); } else { ids = new ArrayList<>(); ids.add(partitionManager.getPartitionIdByCode(graph, code)); } BiFunction<Integer, byte[], ScanIterator> function = (id, position) -> { try (RocksDBSession dbSession = getSession(graph, table, id)) { return new InnerKeyFilter(dbSession.sessionOp().scan(table, keyCreator.getPrefixKey(id, graph, toPosition( prefix, position)), scanType)); } }; return MultiPartitionIterator.of(ids, function); } @Override public ScanIterator scanPrefix(String graph, int code, String table, byte[] prefix) throws HgStoreException { return scanPrefix(graph, code, table, prefix, 0); } private byte[] toPosition(byte[] start, byte[] position) { if (position == null || position.length == 0) { return start; } return position; } @Override public HgStoreMetric.Partition getPartitionMetric(String graph, int partId, boolean accurateCount) throws HgStoreException { // get key count Map<String, Long> countMap = null; Map<String, String> sizeMap = null; try (RocksDBSession dbSession = getSession(graph, partId)) { countMap = dbSession.getKeyCountPerCF(keyCreator.getStartKey(partId, graph), keyCreator.getEndKey(partId, graph), accurateCount); sizeMap = dbSession.getApproximateCFDataSize(keyCreator.getStartKey(partId, graph), keyCreator.getEndKey(partId, graph)); HgStoreMetric.Partition partMetric = new HgStoreMetric.Partition(); partMetric.setPartitionId(partId); List<HgStoreMetric.Table> tables = new ArrayList<>(sizeMap.size()); for (String tableName : sizeMap.keySet()) { HgStoreMetric.Table table = new HgStoreMetric.Table(); table.setTableName(tableName); table.setKeyCount(countMap.get(tableName)); table.setDataSize(sizeMap.get(tableName)); tables.add(table); } partMetric.setTables(tables); return partMetric; } } @Override public HgStoreMetric.Graph getGraphMetric(String graph, int partId) { HgStoreMetric.Graph graphMetric = new HgStoreMetric.Graph(); try (RocksDBSession dbSession = getSession(graph, partId)) { graphMetric.setApproxDataSize( dbSession.getApproximateDataSize(keyCreator.getStartKey(partId, graph), keyCreator.getEndKey(partId, graph))); graphMetric.setApproxKeyCount(dbSession.getEstimateNumKeys()); return graphMetric; } } @Override public void batchGet(String graph, String table, Supplier<HgPair<Integer, byte[]>> s, Consumer<HgPair<byte[], byte[]>> c) throws HgStoreException { int count = 0; while (true) { // Prevent dead loops if (count++ == Integer.MAX_VALUE) { break; } HgPair<Integer, byte[]> duality = s.get(); if (duality == null) { break; } int code = duality.getKey(); byte[] key = duality.getValue(); int partId = provider.getPartitionByCode(graph, code).getId(); try (RocksDBSession dbSession = getSession(graph, table, partId)) { byte[] targetKey = keyCreator.getKey(partId, graph, code, key); byte[] value = dbSession.sessionOp().get(table, targetKey); c.accept(new HgPair<>(key, value)); } } } /** * Clear map data */ @Override public void truncate(String graphName, int partId) throws HgStoreException { // Each partition corresponds to a rocksdb instance, so the rocksdb instance name is rocksdb + partId try (RocksDBSession dbSession = getSession(graphName, partId)) { dbSession.sessionOp().deleteRange(keyCreator.getStartKey(partId, graphName), keyCreator.getEndKey(partId, graphName)); // Release map ID keyCreator.delGraphId(partId, graphName); } } @Override public void flushAll() { log.warn("Flush all!!! "); factory.getGraphNames().forEach(dbName -> { try (RocksDBSession dbSession = factory.queryGraphDB(dbName)) { if (dbSession != null) { dbSession.flush(false); } } }); } @Override public void closeAll() { log.warn("close all db!!! "); factory.getGraphNames().forEach(dbName -> { factory.releaseGraphDB(dbName); }); } @Override public Map<MemoryUsageType, Long> getApproximateMemoryUsageByType(List<Cache> caches) { try { return factory.getApproximateMemoryUsageByType(null, caches); } catch (Exception e) { return new HashMap<>(); } } @Override public List<Integer> getLeaderPartitionIds(String graph) { return partitionManager.getLeaderPartitionIds(graph); } @Override public void saveSnapshot(String snapshotPath, String graph, int partId) throws HgStoreException { try (RocksDBSession dbSession = getSession(graph, partId)) { dbSession.saveSnapshot(snapshotPath); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_EXPORT_SNAPSHOT_FAIL, e.toString()); } } @Override public void loadSnapshot(String snapshotPath, String graph, int partId, long v1) throws HgStoreException { try (RocksDBSession dbSession = getSession(graph, partId)) { dbSession.loadSnapshot(snapshotPath, v1); keyCreator.clearCache(partId); factory.destroyGraphDB(dbSession.getGraphName()); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_IMPORT_SNAPSHOT_FAIL, e.toString()); } } @Override public long getLatestSequenceNumber(String graph, int partId) { try (RocksDBSession dbSession = getSession(graph, partId)) { return dbSession.getLatestSequenceNumber(); } } @Override public ScanIterator scanRaw(String graph, int partId, long seqNum) throws HgStoreException { try (RocksDBSession dbSession = getSession(graph, partId)) { return dbSession.sessionOp().scanRaw(null, null, seqNum); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_EXPORT_SNAPSHOT_FAIL, e.toString()); } } @Override public void ingestSstFile(String graph, int partId, Map<byte[], List<String>> sstFiles) throws HgStoreException { try (RocksDBSession dbSession = getSession(graph, partId)) { dbSession.ingestSstFile(sstFiles); } } @Override public boolean cleanPartition(String graph, int partId) { Partition partition = partitionManager.getPartitionFromPD(graph, partId); cleanPartition(graph, partId, partition.getStartKey(), partition.getEndKey(), CleanType.CLEAN_TYPE_KEEP_RANGE); return true; } @Override public boolean cleanPartition(String graph, int partId, long startKey, long endKey, CleanType cleanType) { Partition partition = partitionManager.getPartition(graph, partId); if (partition == null) { return true; } log.info("cleanPartition: graph {}, part id: {}, {} -> {}, cleanType:{}", graph, partId, startKey, endKey, cleanType); var taskManager = HgStoreEngine.getInstance().getPartitionEngine(partId).getTaskManager(); CleanDataRequest request = new CleanDataRequest(); request.setPartitionId(partId); request.setGraphName(graph); request.setKeyStart(startKey); request.setKeyEnd(endKey); request.setCleanType(cleanType); var cleanTask = new CleanTask(partId, graph, AsyncTaskState.START, request); taskManager.putAsyncTask(cleanTask); Utils.runInThread(() -> { cleanPartition(partition, code -> { // in range boolean flag = code >= startKey && code < endKey; return (cleanType == CleanType.CLEAN_TYPE_KEEP_RANGE) == flag; }); // May have been destroyed. if (HgStoreEngine.getInstance().getPartitionEngine(partId) != null) { taskManager.updateAsyncTaskState(partId, graph, cleanTask.getId(), AsyncTaskState.SUCCESS); } }); return true; } /** * Clean up partition data, delete data not belonging to this partition. * Traverse all keys of partId, read code, if code >= splitKey generate a new key, write to newPartId */ private boolean cleanPartition(Partition partition, Function<Integer, Boolean> belongsFunction) { log.info("Partition {}-{} cleanPartition begin... {}", partition.getGraphName(), partition.getId(), partition); int counter = 0; SessionOperator op = getSession(partition.getGraphName(), partition.getId()).sessionOp(); try { ScanIterator cfIterator = op.scanRaw(keyCreator.getStartKey(partition.getId(), partition.getGraphName()), keyCreator.getEndKey(partition.getId(), partition.getGraphName()), 0); while (cfIterator.hasNext()) { ScanIterator iterator = cfIterator.next(); String table = new String(cfIterator.position()); long deleted = 0; long total = 0; while (iterator.hasNext()) { total += 1; RocksDBSession.BackendColumn col = iterator.next(); int keyCode = keyCreator.parseKeyCode(col.name); // if (keyCode < partition.getStartKey() || keyCode >= partition.getEndKey()) { if (!belongsFunction.apply(keyCode)) { if (counter == 0) { op.prepare(); } op.delete(table, col.name); // delete old data if (++counter > batchSize) { op.commit(); counter = 0; } deleted += 1; } } iterator.close(); log.info("partition {}-{}, table:{}, delete keys {}, total:{}", partition.getGraphName(), partition.getId(), table, deleted, total); } cfIterator.close(); } catch (Exception e) { log.error("Partition {}-{} cleanPartition exception {}", partition.getGraphName(), partition.getId(), e); op.rollback(); throw e; } finally { if (counter > 0) { try { op.commit(); } catch (Exception e) { op.rollback(); throw e; } } op.getDBSession().close(); } op.compactRange(); log.info("Partition {}-{} cleanPartition end", partition.getGraphName(), partition.getId()); return true; } @Override public boolean deletePartition(String graph, int partId) { try { deleteGraphDatabase(graph, partId); } catch (Exception e) { log.error("Partition {}-{} deletePartition exception {}", graph, partId, e); } return true; } @Override public List<String> getTableNames(String graph, int partId) { try (RocksDBSession dbSession = getSession(graph, partId)) { List<String> tables = null; tables = dbSession.getTables().keySet().stream().collect(Collectors.toList()); return tables; } } private RocksDBSession getSession(String graph, String table, int partId) throws HgStoreException { RocksDBSession dbSession = getSession(partId); dbSession.checkTable(table); return dbSession; } private RocksDBSession getSession(String graphName, int partId) throws HgStoreException { return getSession(partId); } /** * Get dbsession, do not update dbsession active time */ @Override public RocksDBSession getSession(int partId) throws HgStoreException { // Each partition corresponds to a rocksdb instance, so the rocksdb instance name is rocksdb + partId String dbName = getDbName(partId); RocksDBSession dbSession = factory.queryGraphDB(dbName); if (dbSession == null) { long version = HgStoreEngine.getInstance().getCommittedIndex(partId); dbSession = factory.createGraphDB(partitionManager.getDbDataPath(partId, dbName), dbName, version); if (dbSession == null) { log.info("failed to create a new graph db: {}", dbName); throw new HgStoreException(HgStoreException.EC_RKDB_CREATE_FAIL, "failed to create a new graph db: {}", dbName); } } dbSession.setDisableWAL(true); // raft mode, disable rocksdb log return dbSession; } private void deleteGraphDatabase(String graph, int partId) throws IOException { truncate(graph, partId); } private PartitionManager getPartManager() { return this.partitionManager; } @Override public TxBuilder txBuilder(String graph, int partId) throws HgStoreException { return new TxBuilderImpl(graph, partId, getSession(graph, partId)); } @Override public boolean existsTable(String graph, int partId, String table) { try (RocksDBSession session = getSession(graph, partId)) { return session.tableIsExist(table); } } @Override public void createTable(String graph, int partId, String table) { try (RocksDBSession session = getSession(graph, partId)) { session.checkTable(table); } } @Override public void deleteTable(String graph, int partId, String table) { dropTable(graph, partId, table); // TODO: Check if the table is empty, if empty then truly delete the table // try (RocksDBSession session = getOrCreateGraphDB(graph, partId)) { // session.deleteTables(table); // } } @Override public void dropTable(String graph, int partId, String table) { try (RocksDBSession session = getSession(graph, partId)) { // session.dropTables(table); session.sessionOp().deleteRange(table, keyCreator.getStartKey(partId, graph), keyCreator.getEndKey(partId, graph)); } } /** * Perform compaction on RocksDB */ @Override public boolean dbCompaction(String graphName, int partitionId) { return this.dbCompaction(graphName, partitionId, ""); } /** * Perform compaction on RocksDB */ @Override public boolean dbCompaction(String graphName, int partitionId, String tableName) { try (RocksDBSession session = getSession(graphName, partitionId)) { SessionOperator op = session.sessionOp(); if (tableName.isEmpty()) { op.compactRange(); } else { op.compactRange(tableName); } } log.info("Partition {}-{} dbCompaction end", graphName, partitionId); return true; } /** * Destroy the map, and delete the data file. * * @param graphName * @param partId */ @Override public void destroyGraphDB(String graphName, int partId) throws HgStoreException { // Each graph each partition corresponds to a rocksdb instance, so the rocksdb instance name is rocksdb + partId String dbName = getDbName(partId); factory.destroyGraphDB(dbName); keyCreator.clearCache(partId); } @Override public long count(String graph, String table) { List<Integer> ids = this.getLeaderPartitionIds(graph); Long all = ids.parallelStream().map((id) -> { InnerKeyFilter it = null; try (RocksDBSession dbSession = getSession(graph, table, id)) { long count = 0; SessionOperator op = dbSession.sessionOp(); it = new InnerKeyFilter(op.scan(table, keyCreator.getStartKey(id, graph), keyCreator.getEndKey(id, graph), ScanIterator.Trait.SCAN_LT_END)); while (it.hasNext()) { it.next(); count++; } return count; } catch (Exception e) { throw e; } finally { if (it != null) { try { it.close(); } catch (Exception e) { } } } }).collect(Collectors.summingLong(l -> l)); return all; } @NotThreadSafe private class TxBuilderImpl implements TxBuilder { private final String graph; private final int partId; private final RocksDBSession dbSession; private final SessionOperator op; private TxBuilderImpl(String graph, int partId, RocksDBSession dbSession) { this.graph = graph; this.partId = partId; this.dbSession = dbSession; this.op = this.dbSession.sessionOp(); this.op.prepare(); } @Override public TxBuilder put(int code, String table, byte[] key, byte[] value) throws HgStoreException { try { byte[] targetKey = keyCreator.getKey(this.partId, graph, code, key); this.op.put(table, targetKey, value); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_DOPUT_FAIL, e.toString()); } return this; } @Override public TxBuilder del(int code, String table, byte[] key) throws HgStoreException { try { byte[] targetKey = keyCreator.getKey(this.partId, graph, code, key); this.op.delete(table, targetKey); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_DODEL_FAIL, e.toString()); } return this; } @Override public TxBuilder delSingle(int code, String table, byte[] key) throws HgStoreException { try { byte[] targetKey = keyCreator.getKey(this.partId, graph, code, key); op.deleteSingle(table, targetKey); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RDKDB_DOSINGLEDEL_FAIL, e.toString()); } return this; } @Override public TxBuilder delPrefix(int code, String table, byte[] prefix) throws HgStoreException { try { this.op.deletePrefix(table, keyCreator.getPrefixKey(this.partId, graph, prefix)); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_DODELPREFIX_FAIL, e.toString()); } return this; } @Override public TxBuilder delRange(int code, String table, byte[] start, byte[] end) throws HgStoreException { try { this.op.deleteRange(table, keyCreator.getStartKey(this.partId, graph, start), keyCreator.getEndKey(this.partId, graph, end)); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_DODELRANGE_FAIL, e.toString()); } return this; } @Override public TxBuilder merge(int code, String table, byte[] key, byte[] value) throws HgStoreException { try { byte[] targetKey = keyCreator.getKey(this.partId, graph, code, key); op.merge(table, targetKey, value); } catch (DBStoreException e) { throw new HgStoreException(HgStoreException.EC_RKDB_DOMERGE_FAIL, e.toString()); } return this; } @Override public Tx build() { return new Tx() { @Override public void commit() throws HgStoreException { op.commit(); // After an exception occurs in commit, rollback must be called, otherwise it will cause the lock not to be released. dbSession.close(); } @Override public void rollback() throws HgStoreException { try { op.rollback(); } finally { dbSession.close(); } } }; } } }
googleapis/google-cloud-java
37,618
java-maps-places/proto-google-maps-places-v1/src/main/java/com/google/maps/places/v1/References.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/maps/places/v1/reference.proto // Protobuf Java Version: 3.25.8 package com.google.maps.places.v1; /** * * * <pre> * Experimental: See * https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative * for more details. * * Reference that the generative content is related to. * </pre> * * Protobuf type {@code google.maps.places.v1.References} */ public final class References extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.maps.places.v1.References) ReferencesOrBuilder { private static final long serialVersionUID = 0L; // Use References.newBuilder() to construct. private References(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private References() { reviews_ = java.util.Collections.emptyList(); places_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new References(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.places.v1.ReferenceProto .internal_static_google_maps_places_v1_References_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.places.v1.ReferenceProto .internal_static_google_maps_places_v1_References_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.places.v1.References.class, com.google.maps.places.v1.References.Builder.class); } public static final int REVIEWS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.maps.places.v1.Review> reviews_; /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ @java.lang.Override public java.util.List<com.google.maps.places.v1.Review> getReviewsList() { return reviews_; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.maps.places.v1.ReviewOrBuilder> getReviewsOrBuilderList() { return reviews_; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ @java.lang.Override public int getReviewsCount() { return reviews_.size(); } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ @java.lang.Override public com.google.maps.places.v1.Review getReviews(int index) { return reviews_.get(index); } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ @java.lang.Override public com.google.maps.places.v1.ReviewOrBuilder getReviewsOrBuilder(int index) { return reviews_.get(index); } public static final int PLACES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList places_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @return A list containing the places. */ public com.google.protobuf.ProtocolStringList getPlacesList() { return places_; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The count of places. */ public int getPlacesCount() { return places_.size(); } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the element to return. * @return The places at the given index. */ public java.lang.String getPlaces(int index) { return places_.get(index); } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the value to return. * @return The bytes of the places at the given index. */ public com.google.protobuf.ByteString getPlacesBytes(int index) { return places_.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 { for (int i = 0; i < reviews_.size(); i++) { output.writeMessage(1, reviews_.get(i)); } for (int i = 0; i < places_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, places_.getRaw(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 < reviews_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, reviews_.get(i)); } { int dataSize = 0; for (int i = 0; i < places_.size(); i++) { dataSize += computeStringSizeNoTag(places_.getRaw(i)); } size += dataSize; size += 1 * getPlacesList().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.maps.places.v1.References)) { return super.equals(obj); } com.google.maps.places.v1.References other = (com.google.maps.places.v1.References) obj; if (!getReviewsList().equals(other.getReviewsList())) return false; if (!getPlacesList().equals(other.getPlacesList())) 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 (getReviewsCount() > 0) { hash = (37 * hash) + REVIEWS_FIELD_NUMBER; hash = (53 * hash) + getReviewsList().hashCode(); } if (getPlacesCount() > 0) { hash = (37 * hash) + PLACES_FIELD_NUMBER; hash = (53 * hash) + getPlacesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.maps.places.v1.References parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.places.v1.References parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.places.v1.References parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.places.v1.References 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.maps.places.v1.References parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.maps.places.v1.References parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.maps.places.v1.References parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.places.v1.References 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.maps.places.v1.References parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.maps.places.v1.References 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.maps.places.v1.References parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.maps.places.v1.References 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.maps.places.v1.References 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> * Experimental: See * https://developers.google.com/maps/documentation/places/web-service/experimental/places-generative * for more details. * * Reference that the generative content is related to. * </pre> * * Protobuf type {@code google.maps.places.v1.References} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.maps.places.v1.References) com.google.maps.places.v1.ReferencesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.maps.places.v1.ReferenceProto .internal_static_google_maps_places_v1_References_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.maps.places.v1.ReferenceProto .internal_static_google_maps_places_v1_References_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.maps.places.v1.References.class, com.google.maps.places.v1.References.Builder.class); } // Construct using com.google.maps.places.v1.References.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (reviewsBuilder_ == null) { reviews_ = java.util.Collections.emptyList(); } else { reviews_ = null; reviewsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); places_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.maps.places.v1.ReferenceProto .internal_static_google_maps_places_v1_References_descriptor; } @java.lang.Override public com.google.maps.places.v1.References getDefaultInstanceForType() { return com.google.maps.places.v1.References.getDefaultInstance(); } @java.lang.Override public com.google.maps.places.v1.References build() { com.google.maps.places.v1.References result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.maps.places.v1.References buildPartial() { com.google.maps.places.v1.References result = new com.google.maps.places.v1.References(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.maps.places.v1.References result) { if (reviewsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { reviews_ = java.util.Collections.unmodifiableList(reviews_); bitField0_ = (bitField0_ & ~0x00000001); } result.reviews_ = reviews_; } else { result.reviews_ = reviewsBuilder_.build(); } } private void buildPartial0(com.google.maps.places.v1.References result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { places_.makeImmutable(); result.places_ = places_; } } @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.maps.places.v1.References) { return mergeFrom((com.google.maps.places.v1.References) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.maps.places.v1.References other) { if (other == com.google.maps.places.v1.References.getDefaultInstance()) return this; if (reviewsBuilder_ == null) { if (!other.reviews_.isEmpty()) { if (reviews_.isEmpty()) { reviews_ = other.reviews_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureReviewsIsMutable(); reviews_.addAll(other.reviews_); } onChanged(); } } else { if (!other.reviews_.isEmpty()) { if (reviewsBuilder_.isEmpty()) { reviewsBuilder_.dispose(); reviewsBuilder_ = null; reviews_ = other.reviews_; bitField0_ = (bitField0_ & ~0x00000001); reviewsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getReviewsFieldBuilder() : null; } else { reviewsBuilder_.addAllMessages(other.reviews_); } } } if (!other.places_.isEmpty()) { if (places_.isEmpty()) { places_ = other.places_; bitField0_ |= 0x00000002; } else { ensurePlacesIsMutable(); places_.addAll(other.places_); } 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.maps.places.v1.Review m = input.readMessage(com.google.maps.places.v1.Review.parser(), extensionRegistry); if (reviewsBuilder_ == null) { ensureReviewsIsMutable(); reviews_.add(m); } else { reviewsBuilder_.addMessage(m); } break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensurePlacesIsMutable(); places_.add(s); 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.maps.places.v1.Review> reviews_ = java.util.Collections.emptyList(); private void ensureReviewsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { reviews_ = new java.util.ArrayList<com.google.maps.places.v1.Review>(reviews_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.maps.places.v1.Review, com.google.maps.places.v1.Review.Builder, com.google.maps.places.v1.ReviewOrBuilder> reviewsBuilder_; /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public java.util.List<com.google.maps.places.v1.Review> getReviewsList() { if (reviewsBuilder_ == null) { return java.util.Collections.unmodifiableList(reviews_); } else { return reviewsBuilder_.getMessageList(); } } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public int getReviewsCount() { if (reviewsBuilder_ == null) { return reviews_.size(); } else { return reviewsBuilder_.getCount(); } } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public com.google.maps.places.v1.Review getReviews(int index) { if (reviewsBuilder_ == null) { return reviews_.get(index); } else { return reviewsBuilder_.getMessage(index); } } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder setReviews(int index, com.google.maps.places.v1.Review value) { if (reviewsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureReviewsIsMutable(); reviews_.set(index, value); onChanged(); } else { reviewsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder setReviews(int index, com.google.maps.places.v1.Review.Builder builderForValue) { if (reviewsBuilder_ == null) { ensureReviewsIsMutable(); reviews_.set(index, builderForValue.build()); onChanged(); } else { reviewsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder addReviews(com.google.maps.places.v1.Review value) { if (reviewsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureReviewsIsMutable(); reviews_.add(value); onChanged(); } else { reviewsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder addReviews(int index, com.google.maps.places.v1.Review value) { if (reviewsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureReviewsIsMutable(); reviews_.add(index, value); onChanged(); } else { reviewsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder addReviews(com.google.maps.places.v1.Review.Builder builderForValue) { if (reviewsBuilder_ == null) { ensureReviewsIsMutable(); reviews_.add(builderForValue.build()); onChanged(); } else { reviewsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder addReviews(int index, com.google.maps.places.v1.Review.Builder builderForValue) { if (reviewsBuilder_ == null) { ensureReviewsIsMutable(); reviews_.add(index, builderForValue.build()); onChanged(); } else { reviewsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder addAllReviews( java.lang.Iterable<? extends com.google.maps.places.v1.Review> values) { if (reviewsBuilder_ == null) { ensureReviewsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, reviews_); onChanged(); } else { reviewsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder clearReviews() { if (reviewsBuilder_ == null) { reviews_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { reviewsBuilder_.clear(); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public Builder removeReviews(int index) { if (reviewsBuilder_ == null) { ensureReviewsIsMutable(); reviews_.remove(index); onChanged(); } else { reviewsBuilder_.remove(index); } return this; } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public com.google.maps.places.v1.Review.Builder getReviewsBuilder(int index) { return getReviewsFieldBuilder().getBuilder(index); } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public com.google.maps.places.v1.ReviewOrBuilder getReviewsOrBuilder(int index) { if (reviewsBuilder_ == null) { return reviews_.get(index); } else { return reviewsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public java.util.List<? extends com.google.maps.places.v1.ReviewOrBuilder> getReviewsOrBuilderList() { if (reviewsBuilder_ != null) { return reviewsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(reviews_); } } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public com.google.maps.places.v1.Review.Builder addReviewsBuilder() { return getReviewsFieldBuilder() .addBuilder(com.google.maps.places.v1.Review.getDefaultInstance()); } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public com.google.maps.places.v1.Review.Builder addReviewsBuilder(int index) { return getReviewsFieldBuilder() .addBuilder(index, com.google.maps.places.v1.Review.getDefaultInstance()); } /** * * * <pre> * Reviews that serve as references. * </pre> * * <code>repeated .google.maps.places.v1.Review reviews = 1;</code> */ public java.util.List<com.google.maps.places.v1.Review.Builder> getReviewsBuilderList() { return getReviewsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.maps.places.v1.Review, com.google.maps.places.v1.Review.Builder, com.google.maps.places.v1.ReviewOrBuilder> getReviewsFieldBuilder() { if (reviewsBuilder_ == null) { reviewsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.maps.places.v1.Review, com.google.maps.places.v1.Review.Builder, com.google.maps.places.v1.ReviewOrBuilder>( reviews_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); reviews_ = null; } return reviewsBuilder_; } private com.google.protobuf.LazyStringArrayList places_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensurePlacesIsMutable() { if (!places_.isModifiable()) { places_ = new com.google.protobuf.LazyStringArrayList(places_); } bitField0_ |= 0x00000002; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @return A list containing the places. */ public com.google.protobuf.ProtocolStringList getPlacesList() { places_.makeImmutable(); return places_; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @return The count of places. */ public int getPlacesCount() { return places_.size(); } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the element to return. * @return The places at the given index. */ public java.lang.String getPlaces(int index) { return places_.get(index); } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index of the value to return. * @return The bytes of the places at the given index. */ public com.google.protobuf.ByteString getPlacesBytes(int index) { return places_.getByteString(index); } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param index The index to set the value at. * @param value The places to set. * @return This builder for chaining. */ public Builder setPlaces(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePlacesIsMutable(); places_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param value The places to add. * @return This builder for chaining. */ public Builder addPlaces(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensurePlacesIsMutable(); places_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param values The places to add. * @return This builder for chaining. */ public Builder addAllPlaces(java.lang.Iterable<java.lang.String> values) { ensurePlacesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, places_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearPlaces() { places_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * The list of resource names of the referenced places. This name can be used * in other APIs that accept Place resource names. * </pre> * * <code>repeated string places = 2 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes of the places to add. * @return This builder for chaining. */ public Builder addPlacesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensurePlacesIsMutable(); places_.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.maps.places.v1.References) } // @@protoc_insertion_point(class_scope:google.maps.places.v1.References) private static final com.google.maps.places.v1.References DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.maps.places.v1.References(); } public static com.google.maps.places.v1.References getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<References> PARSER = new com.google.protobuf.AbstractParser<References>() { @java.lang.Override public References 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<References> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<References> getParserForType() { return PARSER; } @java.lang.Override public com.google.maps.places.v1.References getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/flink
37,745
flink-core/src/test/java/org/apache/flink/api/java/typeutils/PojoTypeExtractionTest.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.api.java.typeutils; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.typeinfo.BasicArrayTypeInfo; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.common.typeinfo.TypeHint; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.common.typeutils.CompositeType.FlatFieldDescriptor; import org.apache.flink.api.java.tuple.Tuple1; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.types.Value; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** * Pojo Type tests. * * <p>Pojo is a bean-style class with getters, setters and empty ctor OR a class with all fields * public (or for every private field, there has to be a public getter/setter) everything else is a * generic type (that can't be used for field selection) */ public class PojoTypeExtractionTest { /** Simple test type that implements the {@link Value} interface. */ public static class MyValue implements Value { private static final long serialVersionUID = 8607223484689147046L; @Override public void write(DataOutputView out) throws IOException {} @Override public void read(DataInputView in) throws IOException {} } public static class HasDuplicateField extends WC { @SuppressWarnings("unused") private int count; // duplicate } @Test void testDuplicateFieldException() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(HasDuplicateField.class); assertThat(ti).isInstanceOf(GenericTypeInfo.class); } // test with correct pojo types public static class WC { // is a pojo public ComplexNestedClass complex; // is a pojo private int count; // is a BasicType public WC() {} public int getCount() { return count; } public void setCount(int c) { this.count = c; } } public static class ComplexNestedClass { // pojo public static int ignoreStaticField; public transient int ignoreTransientField; public Date date; // generic type public Integer someNumberWithÜnicödeNäme; // BasicType public float someFloat; // BasicType public Tuple3<Long, Long, String> word; // Tuple Type with three basic types public Object nothing; // generic type public MyValue valueType; // writableType public List<String> collection; } // all public test public static class AllPublic extends ComplexNestedClass { public ArrayList<String> somethingFancy; // generic type public FancyCollectionSubtype<Integer> fancyIds; // generic type public String[] fancyArray; // generic type } public static class FancyCollectionSubtype<T> extends HashSet<T> { private static final long serialVersionUID = -3494469602638179921L; } public static class ParentSettingGenerics extends PojoWithGenerics<Integer, Long> { public String field3; } public static class PojoWithGenerics<T1, T2> { public int key; public T1 field1; public T2 field2; } public static class ComplexHierarchyTop extends ComplexHierarchy<Tuple1<String>> {} public static class ComplexHierarchy<T> extends PojoWithGenerics<FromTuple, T> {} // extends from Tuple and adds a field public static class FromTuple extends Tuple3<String, String, Long> { private static final long serialVersionUID = 1L; public int special; } public static class IncorrectPojo { private int isPrivate; public int getIsPrivate() { return isPrivate; } // setter is missing (intentional) } // correct pojo public static class BeanStylePojo { public String abc; private int field; public int getField() { return this.field; } public void setField(int f) { this.field = f; } } public static class WrongCtorPojo { public int a; public WrongCtorPojo(int a) { this.a = a; } } public static class PojoWithGenericFields { private Collection<String> users; private boolean favorited; public boolean isFavorited() { return favorited; } public void setFavorited(boolean favorited) { this.favorited = favorited; } public Collection<String> getUsers() { return users; } public void setUsers(Collection<String> users) { this.users = users; } } @Test void testPojoWithGenericFields() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(PojoWithGenericFields.class); assertThat(typeForClass).isInstanceOf(PojoTypeInfo.class); } // in this test, the location of the getters and setters is mixed across the type hierarchy. public static class TypedPojoGetterSetterCheck extends GenericPojoGetterSetterCheck<String> { public void setPackageProtected(String in) { this.packageProtected = in; } } public static class GenericPojoGetterSetterCheck<T> { T packageProtected; public T getPackageProtected() { return packageProtected; } } @Test void testIncorrectPojos() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(IncorrectPojo.class); assertThat(typeForClass).isInstanceOf(GenericTypeInfo.class); typeForClass = TypeExtractor.createTypeInfo(WrongCtorPojo.class); assertThat(typeForClass).isInstanceOf(GenericTypeInfo.class); } @Test void testCorrectPojos() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(BeanStylePojo.class); assertThat(typeForClass).isInstanceOf(PojoTypeInfo.class); typeForClass = TypeExtractor.createTypeInfo(TypedPojoGetterSetterCheck.class); assertThat(typeForClass).isInstanceOf(PojoTypeInfo.class); } @Test void testPojoWC() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(WC.class); checkWCPojoAsserts(typeForClass); WC t = new WC(); t.complex = new ComplexNestedClass(); TypeInformation<?> typeForObject = TypeExtractor.getForObject(t); checkWCPojoAsserts(typeForObject); } @SuppressWarnings({"unchecked", "rawtypes"}) private void checkWCPojoAsserts(TypeInformation<?> typeInfo) { assertThat(typeInfo.isBasicType()).isFalse(); assertThat(typeInfo.isTupleType()).isFalse(); assertThat(typeInfo.getTotalFields()).isEqualTo(10); assertThat(typeInfo).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<?> pojoType = (PojoTypeInfo<?>) typeInfo; List<FlatFieldDescriptor> ffd = new ArrayList<FlatFieldDescriptor>(); String[] fields = { "count", "complex.date", "complex.collection", "complex.nothing", "complex.someFloat", "complex.someNumberWithÜnicödeNäme", "complex.valueType", "complex.word.f0", "complex.word.f1", "complex.word.f2" }; int[] positions = {9, 1, 0, 2, 3, 4, 5, 6, 7, 8}; assertThat(fields).hasSameSizeAs(positions); for (int i = 0; i < fields.length; i++) { pojoType.getFlatFields(fields[i], 0, ffd); assertThat(ffd).as("Too many keys returned").hasSize(1); assertThat(ffd.get(0).getPosition()) .as("position of field " + fields[i] + " wrong") .isEqualTo(positions[i]); ffd.clear(); } pojoType.getFlatFields("complex.word.*", 0, ffd); assertThat(ffd).hasSize(3); // check if it returns 5,6,7 for (FlatFieldDescriptor ffdE : ffd) { final int pos = ffdE.getPosition(); assertThat(pos).isGreaterThanOrEqualTo(6).isLessThanOrEqualTo(8); if (pos == 6) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Long.class); } if (pos == 7) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Long.class); } if (pos == 8) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(String.class); } } ffd.clear(); // scala style full tuple selection for pojos pojoType.getFlatFields("complex.word._", 0, ffd); assertThat(ffd).hasSize(3); ffd.clear(); pojoType.getFlatFields("complex.*", 0, ffd); assertThat(ffd).hasSize(9); // check if it returns 0-7 for (FlatFieldDescriptor ffdE : ffd) { final int pos = ffdE.getPosition(); assertThat(ffdE.getPosition()).isGreaterThanOrEqualTo(0).isLessThanOrEqualTo(8); if (pos == 0) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(List.class); } if (pos == 1) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Date.class); } if (pos == 2) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Object.class); } if (pos == 3) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Float.class); } if (pos == 4) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Integer.class); } if (pos == 5) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(MyValue.class); } if (pos == 6) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Long.class); } if (pos == 7) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Long.class); } if (pos == 8) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(String.class); } if (pos == 9) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Integer.class); } } ffd.clear(); pojoType.getFlatFields("*", 0, ffd); assertThat(ffd).hasSize(10); // check if it returns 0-8 for (FlatFieldDescriptor ffdE : ffd) { assertThat(ffdE.getPosition() <= 9).isTrue(); assertThat(0 <= ffdE.getPosition()).isTrue(); if (ffdE.getPosition() == 9) { assertThat(ffdE.getType().getTypeClass()).isEqualTo(Integer.class); } } ffd.clear(); TypeInformation<?> typeComplexNested = pojoType.getTypeAt(0); // ComplexNestedClass complex assertThat(typeComplexNested).isInstanceOf(PojoTypeInfo.class); assertThat(typeComplexNested.getArity()).isEqualTo(7); assertThat(typeComplexNested.getTotalFields()).isEqualTo(9); PojoTypeInfo<?> pojoTypeComplexNested = (PojoTypeInfo<?>) typeComplexNested; boolean dateSeen = false, intSeen = false, floatSeen = false, tupleSeen = false, objectSeen = false, writableSeen = false, collectionSeen = false; for (int i = 0; i < pojoTypeComplexNested.getArity(); i++) { PojoField field = pojoTypeComplexNested.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("date")) { if (dateSeen) { fail("already seen"); } dateSeen = true; assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.DATE_TYPE_INFO); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(Date.class); } else if (name.equals("someNumberWithÜnicödeNäme")) { if (intSeen) { fail("already seen"); } intSeen = true; assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(Integer.class); } else if (name.equals("someFloat")) { if (floatSeen) { fail("already seen"); } floatSeen = true; assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.FLOAT_TYPE_INFO); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(Float.class); } else if (name.equals("word")) { if (tupleSeen) { fail("already seen"); } tupleSeen = true; assertThat(field.getTypeInformation() instanceof TupleTypeInfo<?>).isTrue(); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(Tuple3.class); // do some more advanced checks on the tuple TupleTypeInfo<?> tupleTypeFromComplexNested = (TupleTypeInfo<?>) field.getTypeInformation(); assertThat(tupleTypeFromComplexNested.getTypeAt(0)) .isEqualTo(BasicTypeInfo.LONG_TYPE_INFO); assertThat(tupleTypeFromComplexNested.getTypeAt(1)) .isEqualTo(BasicTypeInfo.LONG_TYPE_INFO); assertThat(tupleTypeFromComplexNested.getTypeAt(2)) .isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } else if (name.equals("nothing")) { if (objectSeen) { fail("already seen"); } objectSeen = true; assertThat(field.getTypeInformation()) .isEqualTo(new GenericTypeInfo<Object>(Object.class)); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(Object.class); } else if (name.equals("valueType")) { if (writableSeen) { fail("already seen"); } writableSeen = true; assertThat(field.getTypeInformation()) .isEqualTo(new ValueTypeInfo<>(MyValue.class)); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(MyValue.class); } else if (name.equals("collection")) { if (collectionSeen) { fail("already seen"); } collectionSeen = true; assertThat(field.getTypeInformation()) .isEqualTo(new NullableListTypeInfo<>(String.class)); } else { fail("Unexpected field " + field); } } assertThat(dateSeen).as("Field was not present").isTrue(); assertThat(intSeen).as("Field was not present").isTrue(); assertThat(floatSeen).as("Field was not present").isTrue(); assertThat(tupleSeen).as("Field was not present").isTrue(); assertThat(objectSeen).as("Field was not present").isTrue(); assertThat(writableSeen).as("Field was not present").isTrue(); assertThat(collectionSeen).as("Field was not present").isTrue(); TypeInformation<?> typeAtOne = pojoType.getTypeAt(1); // int count assertThat(typeAtOne).isInstanceOf(BasicTypeInfo.class); assertThat(typeInfo.getTypeClass()).isEqualTo(WC.class); assertThat(typeInfo.getArity()).isEqualTo(2); } @Test void testPojoAllPublic() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(AllPublic.class); checkAllPublicAsserts(typeForClass); TypeInformation<?> typeForObject = TypeExtractor.getForObject(new AllPublic()); checkAllPublicAsserts(typeForObject); } private void checkAllPublicAsserts(TypeInformation<?> typeInformation) { assertThat(typeInformation).isInstanceOf(PojoTypeInfo.class); assertThat(typeInformation.getArity()).isEqualTo(10); assertThat(typeInformation.getTotalFields()).isEqualTo(12); // check if the three additional fields are identified correctly boolean arrayListSeen = false, multisetSeen = false, strArraySeen = false; PojoTypeInfo<?> pojoTypeForClass = (PojoTypeInfo<?>) typeInformation; for (int i = 0; i < pojoTypeForClass.getArity(); i++) { PojoField field = pojoTypeForClass.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("somethingFancy")) { if (arrayListSeen) { fail("already seen"); } arrayListSeen = true; assertThat(field.getTypeInformation() instanceof GenericTypeInfo).isTrue(); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(ArrayList.class); } else if (name.equals("fancyIds")) { if (multisetSeen) { fail("already seen"); } multisetSeen = true; assertThat(field.getTypeInformation() instanceof GenericTypeInfo).isTrue(); assertThat(field.getTypeInformation().getTypeClass()) .isEqualTo(FancyCollectionSubtype.class); } else if (name.equals("fancyArray")) { if (strArraySeen) { fail("already seen"); } strArraySeen = true; assertThat(field.getTypeInformation()) .isEqualTo(BasicArrayTypeInfo.STRING_ARRAY_TYPE_INFO); assertThat(field.getTypeInformation().getTypeClass()).isEqualTo(String[].class); } else if (Arrays.asList( "date", "someNumberWithÜnicödeNäme", "someFloat", "word", "nothing", "valueType", "collection") .contains(name)) { // ignore these, they are inherited from the ComplexNestedClass } else { fail("Unexpected field " + field); } } assertThat(arrayListSeen).as("Field was not present").isTrue(); assertThat(multisetSeen).as("Field was not present").isTrue(); assertThat(strArraySeen).as("Field was not present").isTrue(); } @Test void testPojoExtendingTuple() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(FromTuple.class); checkFromTuplePojo(typeForClass); FromTuple ft = new FromTuple(); ft.f0 = ""; ft.f1 = ""; ft.f2 = 0L; TypeInformation<?> typeForObject = TypeExtractor.getForObject(ft); checkFromTuplePojo(typeForObject); } private void checkFromTuplePojo(TypeInformation<?> typeInformation) { assertThat(typeInformation).isInstanceOf(PojoTypeInfo.class); assertThat(typeInformation.getTotalFields()).isEqualTo(4); PojoTypeInfo<?> pojoTypeForClass = (PojoTypeInfo<?>) typeInformation; for (int i = 0; i < pojoTypeForClass.getArity(); i++) { PojoField field = pojoTypeForClass.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("special")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } else if (name.equals("f0") || name.equals("f1")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } else if (name.equals("f2")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.LONG_TYPE_INFO); } else { fail("unexpected field"); } } } @Test void testPojoWithGenerics() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(ParentSettingGenerics.class); assertThat(typeForClass).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<?> pojoTypeForClass = (PojoTypeInfo<?>) typeForClass; for (int i = 0; i < pojoTypeForClass.getArity(); i++) { PojoField field = pojoTypeForClass.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("field1")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } else if (name.equals("field2")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.LONG_TYPE_INFO); } else if (name.equals("field3")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } else if (name.equals("key")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } else { fail("Unexpected field " + field); } } } /** Test if the TypeExtractor is accepting untyped generics, making them GenericTypes */ @Test void testPojoWithGenericsSomeFieldsGeneric() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(PojoWithGenerics.class); assertThat(typeForClass).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<?> pojoTypeForClass = (PojoTypeInfo<?>) typeForClass; for (int i = 0; i < pojoTypeForClass.getArity(); i++) { PojoField field = pojoTypeForClass.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("field1")) { assertThat(field.getTypeInformation()) .isEqualTo(new GenericTypeInfo<Object>(Object.class)); } else if (name.equals("field2")) { assertThat(field.getTypeInformation()) .isEqualTo(new GenericTypeInfo<Object>(Object.class)); } else if (name.equals("key")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } else { fail("Unexpected field " + field); } } } @Test void testPojoWithComplexHierarchy() { TypeInformation<?> typeForClass = TypeExtractor.createTypeInfo(ComplexHierarchyTop.class); assertThat(typeForClass).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<?> pojoTypeForClass = (PojoTypeInfo<?>) typeForClass; for (int i = 0; i < pojoTypeForClass.getArity(); i++) { PojoField field = pojoTypeForClass.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("field1")) { assertThat(field.getTypeInformation() instanceof PojoTypeInfo<?>) .isTrue(); // From tuple is pojo (not tuple type!) } else if (name.equals("field2")) { assertThat(field.getTypeInformation() instanceof TupleTypeInfo<?>).isTrue(); assertThat(((TupleTypeInfo<?>) field.getTypeInformation()).getTypeAt(0)) .isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } else if (name.equals("key")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } else { fail("Unexpected field " + field); } } } public static class MyMapper<T> implements MapFunction<PojoWithGenerics<Long, T>, PojoWithGenerics<T, T>> { private static final long serialVersionUID = 1L; @Override public PojoWithGenerics<T, T> map(PojoWithGenerics<Long, T> value) throws Exception { return null; } } @Test void testGenericPojoTypeInference1() { MyMapper<String> function = new MyMapper<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of(new TypeHint<PojoWithGenerics<Long, String>>() {})); assertThat(ti).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<?> pti = (PojoTypeInfo<?>) ti; for (int i = 0; i < pti.getArity(); i++) { PojoField field = pti.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("field1")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } else if (name.equals("field2")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } else if (name.equals("key")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } else { fail("Unexpected field " + field); } } } public static class PojoTuple<A, B, C> extends Tuple3<B, C, Long> { private static final long serialVersionUID = 1L; public A extraField; } public static class MyMapper2<D, E> implements MapFunction<Tuple2<E, D>, PojoTuple<E, D, D>> { private static final long serialVersionUID = 1L; @Override public PojoTuple<E, D, D> map(Tuple2<E, D> value) throws Exception { return null; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference2() { MyMapper2<Boolean, Character> function = new MyMapper2<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of(new TypeHint<Tuple2<Character, Boolean>>() {})); assertThat(ti).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<?> pti = (PojoTypeInfo<?>) ti; for (int i = 0; i < pti.getArity(); i++) { PojoField field = pti.getPojoFieldAt(i); String name = field.getField().getName(); if (name.equals("extraField")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.CHAR_TYPE_INFO); } else if (name.equals("f0")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.BOOLEAN_TYPE_INFO); } else if (name.equals("f1")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.BOOLEAN_TYPE_INFO); } else if (name.equals("f2")) { assertThat(field.getTypeInformation()).isEqualTo(BasicTypeInfo.LONG_TYPE_INFO); } else { fail("Unexpected field " + field); } } } public static class MyMapper3<D, E> implements MapFunction<PojoTuple<E, D, D>, Tuple2<E, D>> { private static final long serialVersionUID = 1L; @Override public Tuple2<E, D> map(PojoTuple<E, D, D> value) throws Exception { return null; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference3() { MyMapper3<Boolean, Character> function = new MyMapper3<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of( new TypeHint<PojoTuple<Character, Boolean, Boolean>>() {})); assertThat(ti).isInstanceOf(TupleTypeInfo.class); TupleTypeInfo<?> tti = (TupleTypeInfo<?>) ti; assertThat(tti.getTypeAt(0)).isEqualTo(BasicTypeInfo.CHAR_TYPE_INFO); assertThat(tti.getTypeAt(1)).isEqualTo(BasicTypeInfo.BOOLEAN_TYPE_INFO); } public static class PojoWithParameterizedFields1<Z> { public Tuple2<Z, Z> field; } public static class MyMapper4<A> implements MapFunction<PojoWithParameterizedFields1<A>, A> { private static final long serialVersionUID = 1L; @Override public A map(PojoWithParameterizedFields1<A> value) throws Exception { return null; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference4() { MyMapper4<Byte> function = new MyMapper4<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of(new TypeHint<PojoWithParameterizedFields1<Byte>>() {})); assertThat(ti).isEqualTo(BasicTypeInfo.BYTE_TYPE_INFO); } public static class PojoWithParameterizedFields2<Z> { public PojoWithGenerics<Z, Z> field; } public static class MyMapper5<A> implements MapFunction<PojoWithParameterizedFields2<A>, A> { private static final long serialVersionUID = 1L; @Override public A map(PojoWithParameterizedFields2<A> value) throws Exception { return null; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference5() { MyMapper5<Byte> function = new MyMapper5<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of(new TypeHint<PojoWithParameterizedFields2<Byte>>() {})); assertThat(ti).isEqualTo(BasicTypeInfo.BYTE_TYPE_INFO); } public static class PojoWithParameterizedFields3<Z> { public Z[] field; } public static class MyMapper6<A> implements MapFunction<PojoWithParameterizedFields3<A>, A> { private static final long serialVersionUID = 1L; @Override public A map(PojoWithParameterizedFields3<A> value) throws Exception { return null; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference6() { MyMapper6<Integer> function = new MyMapper6<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of( new TypeHint<PojoWithParameterizedFields3<Integer>>() {})); assertThat(ti).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } public static class MyMapper7<A> implements MapFunction<PojoWithParameterizedFields4<A>, A> { private static final long serialVersionUID = 1L; @Override public A map(PojoWithParameterizedFields4<A> value) throws Exception { return null; } } public static class PojoWithParameterizedFields4<Z> { public Tuple1<Z>[] field; } @SuppressWarnings({"unchecked", "rawtypes"}) @Test void testGenericPojoTypeInference7() { MyMapper7<Integer> function = new MyMapper7<>(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, TypeInformation.of( new TypeHint<PojoWithParameterizedFields4<Integer>>() {})); assertThat(ti).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); } public static class RecursivePojo1 { public RecursivePojo1 field; } public static class RecursivePojo2 { public Tuple1<RecursivePojo2> field; } public static class RecursivePojo3 { public NestedPojo field; } public static class NestedPojo { public RecursivePojo3 field; } @Test void testRecursivePojo1() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(RecursivePojo1.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); assertThat(((PojoTypeInfo) ti).getPojoFieldAt(0).getTypeInformation().getClass()) .isEqualTo(GenericTypeInfo.class); } @Test void testRecursivePojo2() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(RecursivePojo2.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); PojoField pf = ((PojoTypeInfo) ti).getPojoFieldAt(0); assertThat(pf.getTypeInformation() instanceof TupleTypeInfo).isTrue(); assertThat(((TupleTypeInfo) pf.getTypeInformation()).getTypeAt(0).getClass()) .isEqualTo(GenericTypeInfo.class); } @Test void testRecursivePojo3() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(RecursivePojo3.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); PojoField pf = ((PojoTypeInfo) ti).getPojoFieldAt(0); assertThat(pf.getTypeInformation() instanceof PojoTypeInfo).isTrue(); assertThat( ((PojoTypeInfo) pf.getTypeInformation()) .getPojoFieldAt(0) .getTypeInformation() .getClass()) .isEqualTo(GenericTypeInfo.class); } public static class FooBarPojo { public int foo, bar; public FooBarPojo() {} } public static class DuplicateMapper implements MapFunction<FooBarPojo, Tuple2<FooBarPojo, FooBarPojo>> { @Override public Tuple2<FooBarPojo, FooBarPojo> map(FooBarPojo value) throws Exception { return null; } } @Test void testDualUseOfPojo() { MapFunction<?, ?> function = new DuplicateMapper(); TypeInformation<?> ti = TypeExtractor.getMapReturnTypes( function, (TypeInformation) TypeExtractor.createTypeInfo(FooBarPojo.class)); assertThat(ti).isInstanceOf(TupleTypeInfo.class); TupleTypeInfo<?> tti = ((TupleTypeInfo) ti); assertThat(tti.getTypeAt(0) instanceof PojoTypeInfo).isTrue(); assertThat(tti.getTypeAt(1) instanceof PojoTypeInfo).isTrue(); } public static class PojoWithRecursiveGenericField<K, V> { public PojoWithRecursiveGenericField<K, V> parent; public PojoWithRecursiveGenericField() {} } @Test void testPojoWithRecursiveGenericField() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(PojoWithRecursiveGenericField.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); assertThat(((PojoTypeInfo) ti).getPojoFieldAt(0).getTypeInformation().getClass()) .isEqualTo(GenericTypeInfo.class); } public static class MutualPojoA { public MutualPojoB field; } public static class MutualPojoB { public MutualPojoA field; } @Test void testPojosWithMutualRecursion() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(MutualPojoB.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); TypeInformation<?> pti = ((PojoTypeInfo) ti).getPojoFieldAt(0).getTypeInformation(); assertThat(pti).isInstanceOf(PojoTypeInfo.class); assertThat(((PojoTypeInfo) pti).getPojoFieldAt(0).getTypeInformation().getClass()) .isEqualTo(GenericTypeInfo.class); } public static class Container<T> { public T field; } public static class MyType extends Container<Container<Object>> {} @Test void testRecursivePojoWithTypeVariable() { TypeInformation<?> ti = TypeExtractor.createTypeInfo(MyType.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); TypeInformation<?> pti = ((PojoTypeInfo) ti).getPojoFieldAt(0).getTypeInformation(); assertThat(pti).isInstanceOf(PojoTypeInfo.class); assertThat(((PojoTypeInfo) pti).getPojoFieldAt(0).getTypeInformation().getClass()) .isEqualTo(GenericTypeInfo.class); } /** POJO generated using Lombok. */ @Getter @Setter @NoArgsConstructor public static class TestLombok { private int age = 10; private boolean isHealthy; private String name; } @Test void testLombokPojo() { TypeInformation<TestLombok> ti = TypeExtractor.getForClass(TestLombok.class); assertThat(ti).isInstanceOf(PojoTypeInfo.class); PojoTypeInfo<TestLombok> pti = (PojoTypeInfo<TestLombok>) ti; assertThat(pti.getTypeAt(0)).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); assertThat(pti.getTypeAt(1)).isEqualTo(BasicTypeInfo.BOOLEAN_TYPE_INFO); assertThat(pti.getTypeAt(2)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); } }
googleapis/google-cloud-java
37,649
java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/CreateEnvironmentRequest.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/environment.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * The request message for * [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest} */ public final class CreateEnvironmentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest) CreateEnvironmentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateEnvironmentRequest.newBuilder() to construct. private CreateEnvironmentRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateEnvironmentRequest() { parent_ = ""; environmentId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateEnvironmentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.EnvironmentProto .internal_static_google_cloud_dialogflow_v2beta1_CreateEnvironmentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.EnvironmentProto .internal_static_google_cloud_dialogflow_v2beta1_CreateEnvironmentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.class, com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </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 ENVIRONMENT_FIELD_NUMBER = 2; private com.google.cloud.dialogflow.v2beta1.Environment environment_; /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the environment field is set. */ @java.lang.Override public boolean hasEnvironment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The environment. */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.Environment getEnvironment() { return environment_ == null ? com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance() : environment_; } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder getEnvironmentOrBuilder() { return environment_ == null ? com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance() : environment_; } public static final int ENVIRONMENT_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object environmentId_ = ""; /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The environmentId. */ @java.lang.Override public java.lang.String getEnvironmentId() { java.lang.Object ref = environmentId_; 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(); environmentId_ = s; return s; } } /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for environmentId. */ @java.lang.Override public com.google.protobuf.ByteString getEnvironmentIdBytes() { java.lang.Object ref = environmentId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); environmentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getEnvironment()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(environmentId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, environmentId_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getEnvironment()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(environmentId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, environmentId_); } 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.CreateEnvironmentRequest)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest other = (com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasEnvironment() != other.hasEnvironment()) return false; if (hasEnvironment()) { if (!getEnvironment().equals(other.getEnvironment())) return false; } if (!getEnvironmentId().equals(other.getEnvironmentId())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (hasEnvironment()) { hash = (37 * hash) + ENVIRONMENT_FIELD_NUMBER; hash = (53 * hash) + getEnvironment().hashCode(); } hash = (37 * hash) + ENVIRONMENT_ID_FIELD_NUMBER; hash = (53 * hash) + getEnvironmentId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest 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.CreateEnvironmentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest 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.CreateEnvironmentRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest 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.CreateEnvironmentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest 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.CreateEnvironmentRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest 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.CreateEnvironmentRequest 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.CreateEnvironmentRequest 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.CreateEnvironmentRequest 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 * [Environments.CreateEnvironment][google.cloud.dialogflow.v2beta1.Environments.CreateEnvironment]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest) com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.EnvironmentProto .internal_static_google_cloud_dialogflow_v2beta1_CreateEnvironmentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.EnvironmentProto .internal_static_google_cloud_dialogflow_v2beta1_CreateEnvironmentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.class, com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getEnvironmentFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; environment_ = null; if (environmentBuilder_ != null) { environmentBuilder_.dispose(); environmentBuilder_ = null; } environmentId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.EnvironmentProto .internal_static_google_cloud_dialogflow_v2beta1_CreateEnvironmentRequest_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest build() { com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest buildPartial() { com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest result = new com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.environment_ = environmentBuilder_ == null ? environment_ : environmentBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.environmentId_ = environmentId_; } 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.CreateEnvironmentRequest) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest other) { if (other == com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasEnvironment()) { mergeEnvironment(other.getEnvironment()); } if (!other.getEnvironmentId().isEmpty()) { environmentId_ = other.environmentId_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getEnvironmentFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { environmentId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The agent to create an environment for. * Supported formats: * - `projects/&lt;Project ID&gt;/agent` * - `projects/&lt;Project ID&gt;/locations/&lt;Location ID&gt;/agent` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.dialogflow.v2beta1.Environment environment_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.Environment, com.google.cloud.dialogflow.v2beta1.Environment.Builder, com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder> environmentBuilder_; /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the environment field is set. */ public boolean hasEnvironment() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The environment. */ public com.google.cloud.dialogflow.v2beta1.Environment getEnvironment() { if (environmentBuilder_ == null) { return environment_ == null ? com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance() : environment_; } else { return environmentBuilder_.getMessage(); } } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setEnvironment(com.google.cloud.dialogflow.v2beta1.Environment value) { if (environmentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } environment_ = value; } else { environmentBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setEnvironment( com.google.cloud.dialogflow.v2beta1.Environment.Builder builderForValue) { if (environmentBuilder_ == null) { environment_ = builderForValue.build(); } else { environmentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeEnvironment(com.google.cloud.dialogflow.v2beta1.Environment value) { if (environmentBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && environment_ != null && environment_ != com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance()) { getEnvironmentBuilder().mergeFrom(value); } else { environment_ = value; } } else { environmentBuilder_.mergeFrom(value); } if (environment_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearEnvironment() { bitField0_ = (bitField0_ & ~0x00000002); environment_ = null; if (environmentBuilder_ != null) { environmentBuilder_.dispose(); environmentBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dialogflow.v2beta1.Environment.Builder getEnvironmentBuilder() { bitField0_ |= 0x00000002; onChanged(); return getEnvironmentFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder getEnvironmentOrBuilder() { if (environmentBuilder_ != null) { return environmentBuilder_.getMessageOrBuilder(); } else { return environment_ == null ? com.google.cloud.dialogflow.v2beta1.Environment.getDefaultInstance() : environment_; } } /** * * * <pre> * Required. The environment to create. * </pre> * * <code> * .google.cloud.dialogflow.v2beta1.Environment environment = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.Environment, com.google.cloud.dialogflow.v2beta1.Environment.Builder, com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder> getEnvironmentFieldBuilder() { if (environmentBuilder_ == null) { environmentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.Environment, com.google.cloud.dialogflow.v2beta1.Environment.Builder, com.google.cloud.dialogflow.v2beta1.EnvironmentOrBuilder>( getEnvironment(), getParentForChildren(), isClean()); environment_ = null; } return environmentBuilder_; } private java.lang.Object environmentId_ = ""; /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The environmentId. */ public java.lang.String getEnvironmentId() { java.lang.Object ref = environmentId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); environmentId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for environmentId. */ public com.google.protobuf.ByteString getEnvironmentIdBytes() { java.lang.Object ref = environmentId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); environmentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The environmentId to set. * @return This builder for chaining. */ public Builder setEnvironmentId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } environmentId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearEnvironmentId() { environmentId_ = getDefaultInstance().getEnvironmentId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. The unique id of the new environment. * </pre> * * <code>string environment_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for environmentId to set. * @return This builder for chaining. */ public Builder setEnvironmentIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); environmentId_ = 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.dialogflow.v2beta1.CreateEnvironmentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest) private static final com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest(); } public static com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateEnvironmentRequest> PARSER = new com.google.protobuf.AbstractParser<CreateEnvironmentRequest>() { @java.lang.Override public CreateEnvironmentRequest 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<CreateEnvironmentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateEnvironmentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.CreateEnvironmentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,515
java-network-management/proto-google-cloud-network-management-v1/src/main/java/com/google/cloud/networkmanagement/v1/ForwardInfo.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/networkmanagement/v1/trace.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.networkmanagement.v1; /** * * * <pre> * Details of the final state "forward" and associated resource. * </pre> * * Protobuf type {@code google.cloud.networkmanagement.v1.ForwardInfo} */ public final class ForwardInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.networkmanagement.v1.ForwardInfo) ForwardInfoOrBuilder { private static final long serialVersionUID = 0L; // Use ForwardInfo.newBuilder() to construct. private ForwardInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ForwardInfo() { target_ = 0; resourceUri_ = ""; ipAddress_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ForwardInfo(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkmanagement.v1.TraceProto .internal_static_google_cloud_networkmanagement_v1_ForwardInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkmanagement.v1.TraceProto .internal_static_google_cloud_networkmanagement_v1_ForwardInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkmanagement.v1.ForwardInfo.class, com.google.cloud.networkmanagement.v1.ForwardInfo.Builder.class); } /** * * * <pre> * Forward target types. * </pre> * * Protobuf enum {@code google.cloud.networkmanagement.v1.ForwardInfo.Target} */ public enum Target implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Target not specified. * </pre> * * <code>TARGET_UNSPECIFIED = 0;</code> */ TARGET_UNSPECIFIED(0), /** * * * <pre> * Forwarded to a VPC peering network. * </pre> * * <code>PEERING_VPC = 1;</code> */ PEERING_VPC(1), /** * * * <pre> * Forwarded to a Cloud VPN gateway. * </pre> * * <code>VPN_GATEWAY = 2;</code> */ VPN_GATEWAY(2), /** * * * <pre> * Forwarded to a Cloud Interconnect connection. * </pre> * * <code>INTERCONNECT = 3;</code> */ INTERCONNECT(3), /** * * * <pre> * Forwarded to a Google Kubernetes Engine Container cluster master. * </pre> * * <code>GKE_MASTER = 4 [deprecated = true];</code> */ @java.lang.Deprecated GKE_MASTER(4), /** * * * <pre> * Forwarded to the next hop of a custom route imported from a peering VPC. * </pre> * * <code>IMPORTED_CUSTOM_ROUTE_NEXT_HOP = 5;</code> */ IMPORTED_CUSTOM_ROUTE_NEXT_HOP(5), /** * * * <pre> * Forwarded to a Cloud SQL instance. * </pre> * * <code>CLOUD_SQL_INSTANCE = 6 [deprecated = true];</code> */ @java.lang.Deprecated CLOUD_SQL_INSTANCE(6), /** * * * <pre> * Forwarded to a VPC network in another project. * </pre> * * <code>ANOTHER_PROJECT = 7;</code> */ ANOTHER_PROJECT(7), /** * * * <pre> * Forwarded to an NCC Hub. * </pre> * * <code>NCC_HUB = 8;</code> */ NCC_HUB(8), /** * * * <pre> * Forwarded to a router appliance. * </pre> * * <code>ROUTER_APPLIANCE = 9;</code> */ ROUTER_APPLIANCE(9), UNRECOGNIZED(-1), ; /** * * * <pre> * Target not specified. * </pre> * * <code>TARGET_UNSPECIFIED = 0;</code> */ public static final int TARGET_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Forwarded to a VPC peering network. * </pre> * * <code>PEERING_VPC = 1;</code> */ public static final int PEERING_VPC_VALUE = 1; /** * * * <pre> * Forwarded to a Cloud VPN gateway. * </pre> * * <code>VPN_GATEWAY = 2;</code> */ public static final int VPN_GATEWAY_VALUE = 2; /** * * * <pre> * Forwarded to a Cloud Interconnect connection. * </pre> * * <code>INTERCONNECT = 3;</code> */ public static final int INTERCONNECT_VALUE = 3; /** * * * <pre> * Forwarded to a Google Kubernetes Engine Container cluster master. * </pre> * * <code>GKE_MASTER = 4 [deprecated = true];</code> */ @java.lang.Deprecated public static final int GKE_MASTER_VALUE = 4; /** * * * <pre> * Forwarded to the next hop of a custom route imported from a peering VPC. * </pre> * * <code>IMPORTED_CUSTOM_ROUTE_NEXT_HOP = 5;</code> */ public static final int IMPORTED_CUSTOM_ROUTE_NEXT_HOP_VALUE = 5; /** * * * <pre> * Forwarded to a Cloud SQL instance. * </pre> * * <code>CLOUD_SQL_INSTANCE = 6 [deprecated = true];</code> */ @java.lang.Deprecated public static final int CLOUD_SQL_INSTANCE_VALUE = 6; /** * * * <pre> * Forwarded to a VPC network in another project. * </pre> * * <code>ANOTHER_PROJECT = 7;</code> */ public static final int ANOTHER_PROJECT_VALUE = 7; /** * * * <pre> * Forwarded to an NCC Hub. * </pre> * * <code>NCC_HUB = 8;</code> */ public static final int NCC_HUB_VALUE = 8; /** * * * <pre> * Forwarded to a router appliance. * </pre> * * <code>ROUTER_APPLIANCE = 9;</code> */ public static final int ROUTER_APPLIANCE_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 Target 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 Target forNumber(int value) { switch (value) { case 0: return TARGET_UNSPECIFIED; case 1: return PEERING_VPC; case 2: return VPN_GATEWAY; case 3: return INTERCONNECT; case 4: return GKE_MASTER; case 5: return IMPORTED_CUSTOM_ROUTE_NEXT_HOP; case 6: return CLOUD_SQL_INSTANCE; case 7: return ANOTHER_PROJECT; case 8: return NCC_HUB; case 9: return ROUTER_APPLIANCE; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<Target> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<Target> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<Target>() { public Target findValueByNumber(int number) { return Target.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.networkmanagement.v1.ForwardInfo.getDescriptor() .getEnumTypes() .get(0); } private static final Target[] VALUES = values(); public static Target 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 Target(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.networkmanagement.v1.ForwardInfo.Target) } public static final int TARGET_FIELD_NUMBER = 1; private int target_ = 0; /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @return The enum numeric value on the wire for target. */ @java.lang.Override public int getTargetValue() { return target_; } /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @return The target. */ @java.lang.Override public com.google.cloud.networkmanagement.v1.ForwardInfo.Target getTarget() { com.google.cloud.networkmanagement.v1.ForwardInfo.Target result = com.google.cloud.networkmanagement.v1.ForwardInfo.Target.forNumber(target_); return result == null ? com.google.cloud.networkmanagement.v1.ForwardInfo.Target.UNRECOGNIZED : result; } public static final int RESOURCE_URI_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object resourceUri_ = ""; /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @return The resourceUri. */ @java.lang.Override public java.lang.String getResourceUri() { java.lang.Object ref = resourceUri_; 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(); resourceUri_ = s; return s; } } /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @return The bytes for resourceUri. */ @java.lang.Override public com.google.protobuf.ByteString getResourceUriBytes() { java.lang.Object ref = resourceUri_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resourceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int IP_ADDRESS_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object ipAddress_ = ""; /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @return The ipAddress. */ @java.lang.Override public java.lang.String getIpAddress() { java.lang.Object ref = ipAddress_; 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(); ipAddress_ = s; return s; } } /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @return The bytes for ipAddress. */ @java.lang.Override public com.google.protobuf.ByteString getIpAddressBytes() { java.lang.Object ref = ipAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); ipAddress_ = 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 (target_ != com.google.cloud.networkmanagement.v1.ForwardInfo.Target.TARGET_UNSPECIFIED .getNumber()) { output.writeEnum(1, target_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceUri_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, resourceUri_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(ipAddress_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, ipAddress_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (target_ != com.google.cloud.networkmanagement.v1.ForwardInfo.Target.TARGET_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, target_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceUri_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, resourceUri_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(ipAddress_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, ipAddress_); } 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.networkmanagement.v1.ForwardInfo)) { return super.equals(obj); } com.google.cloud.networkmanagement.v1.ForwardInfo other = (com.google.cloud.networkmanagement.v1.ForwardInfo) obj; if (target_ != other.target_) return false; if (!getResourceUri().equals(other.getResourceUri())) return false; if (!getIpAddress().equals(other.getIpAddress())) 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) + TARGET_FIELD_NUMBER; hash = (53 * hash) + target_; hash = (37 * hash) + RESOURCE_URI_FIELD_NUMBER; hash = (53 * hash) + getResourceUri().hashCode(); hash = (37 * hash) + IP_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getIpAddress().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.networkmanagement.v1.ForwardInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkmanagement.v1.ForwardInfo 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.networkmanagement.v1.ForwardInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkmanagement.v1.ForwardInfo 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.networkmanagement.v1.ForwardInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkmanagement.v1.ForwardInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkmanagement.v1.ForwardInfo parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkmanagement.v1.ForwardInfo 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.networkmanagement.v1.ForwardInfo parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.networkmanagement.v1.ForwardInfo 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.networkmanagement.v1.ForwardInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkmanagement.v1.ForwardInfo 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.networkmanagement.v1.ForwardInfo 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> * Details of the final state "forward" and associated resource. * </pre> * * Protobuf type {@code google.cloud.networkmanagement.v1.ForwardInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.networkmanagement.v1.ForwardInfo) com.google.cloud.networkmanagement.v1.ForwardInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkmanagement.v1.TraceProto .internal_static_google_cloud_networkmanagement_v1_ForwardInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkmanagement.v1.TraceProto .internal_static_google_cloud_networkmanagement_v1_ForwardInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkmanagement.v1.ForwardInfo.class, com.google.cloud.networkmanagement.v1.ForwardInfo.Builder.class); } // Construct using com.google.cloud.networkmanagement.v1.ForwardInfo.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; target_ = 0; resourceUri_ = ""; ipAddress_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.networkmanagement.v1.TraceProto .internal_static_google_cloud_networkmanagement_v1_ForwardInfo_descriptor; } @java.lang.Override public com.google.cloud.networkmanagement.v1.ForwardInfo getDefaultInstanceForType() { return com.google.cloud.networkmanagement.v1.ForwardInfo.getDefaultInstance(); } @java.lang.Override public com.google.cloud.networkmanagement.v1.ForwardInfo build() { com.google.cloud.networkmanagement.v1.ForwardInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.networkmanagement.v1.ForwardInfo buildPartial() { com.google.cloud.networkmanagement.v1.ForwardInfo result = new com.google.cloud.networkmanagement.v1.ForwardInfo(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.networkmanagement.v1.ForwardInfo result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.target_ = target_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.resourceUri_ = resourceUri_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.ipAddress_ = ipAddress_; } } @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.networkmanagement.v1.ForwardInfo) { return mergeFrom((com.google.cloud.networkmanagement.v1.ForwardInfo) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.networkmanagement.v1.ForwardInfo other) { if (other == com.google.cloud.networkmanagement.v1.ForwardInfo.getDefaultInstance()) return this; if (other.target_ != 0) { setTargetValue(other.getTargetValue()); } if (!other.getResourceUri().isEmpty()) { resourceUri_ = other.resourceUri_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getIpAddress().isEmpty()) { ipAddress_ = other.ipAddress_; 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 8: { target_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 18: { resourceUri_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { ipAddress_ = 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 int target_ = 0; /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @return The enum numeric value on the wire for target. */ @java.lang.Override public int getTargetValue() { return target_; } /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @param value The enum numeric value on the wire for target to set. * @return This builder for chaining. */ public Builder setTargetValue(int value) { target_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @return The target. */ @java.lang.Override public com.google.cloud.networkmanagement.v1.ForwardInfo.Target getTarget() { com.google.cloud.networkmanagement.v1.ForwardInfo.Target result = com.google.cloud.networkmanagement.v1.ForwardInfo.Target.forNumber(target_); return result == null ? com.google.cloud.networkmanagement.v1.ForwardInfo.Target.UNRECOGNIZED : result; } /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @param value The target to set. * @return This builder for chaining. */ public Builder setTarget(com.google.cloud.networkmanagement.v1.ForwardInfo.Target value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; target_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Target type where this packet is forwarded to. * </pre> * * <code>.google.cloud.networkmanagement.v1.ForwardInfo.Target target = 1;</code> * * @return This builder for chaining. */ public Builder clearTarget() { bitField0_ = (bitField0_ & ~0x00000001); target_ = 0; onChanged(); return this; } private java.lang.Object resourceUri_ = ""; /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @return The resourceUri. */ public java.lang.String getResourceUri() { java.lang.Object ref = resourceUri_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceUri_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @return The bytes for resourceUri. */ public com.google.protobuf.ByteString getResourceUriBytes() { java.lang.Object ref = resourceUri_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resourceUri_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @param value The resourceUri to set. * @return This builder for chaining. */ public Builder setResourceUri(java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceUri_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @return This builder for chaining. */ public Builder clearResourceUri() { resourceUri_ = getDefaultInstance().getResourceUri(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * URI of the resource that the packet is forwarded to. * </pre> * * <code>string resource_uri = 2;</code> * * @param value The bytes for resourceUri to set. * @return This builder for chaining. */ public Builder setResourceUriBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceUri_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object ipAddress_ = ""; /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @return The ipAddress. */ public java.lang.String getIpAddress() { java.lang.Object ref = ipAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); ipAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @return The bytes for ipAddress. */ public com.google.protobuf.ByteString getIpAddressBytes() { java.lang.Object ref = ipAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); ipAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @param value The ipAddress to set. * @return This builder for chaining. */ public Builder setIpAddress(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ipAddress_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @return This builder for chaining. */ public Builder clearIpAddress() { ipAddress_ = getDefaultInstance().getIpAddress(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * IP address of the target (if applicable). * </pre> * * <code>string ip_address = 3 [(.google.api.field_info) = { ... }</code> * * @param value The bytes for ipAddress to set. * @return This builder for chaining. */ public Builder setIpAddressBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ipAddress_ = 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.networkmanagement.v1.ForwardInfo) } // @@protoc_insertion_point(class_scope:google.cloud.networkmanagement.v1.ForwardInfo) private static final com.google.cloud.networkmanagement.v1.ForwardInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.networkmanagement.v1.ForwardInfo(); } public static com.google.cloud.networkmanagement.v1.ForwardInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ForwardInfo> PARSER = new com.google.protobuf.AbstractParser<ForwardInfo>() { @java.lang.Override public ForwardInfo 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<ForwardInfo> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ForwardInfo> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.networkmanagement.v1.ForwardInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,578
java-accessapproval/proto-google-cloud-accessapproval-v1/src/main/java/com/google/cloud/accessapproval/v1/ListApprovalRequestsMessage.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/accessapproval/v1/accessapproval.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.accessapproval.v1; /** * * * <pre> * Request to list approval requests. * </pre> * * Protobuf type {@code google.cloud.accessapproval.v1.ListApprovalRequestsMessage} */ public final class ListApprovalRequestsMessage extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.accessapproval.v1.ListApprovalRequestsMessage) ListApprovalRequestsMessageOrBuilder { private static final long serialVersionUID = 0L; // Use ListApprovalRequestsMessage.newBuilder() to construct. private ListApprovalRequestsMessage(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListApprovalRequestsMessage() { parent_ = ""; filter_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListApprovalRequestsMessage(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.accessapproval.v1.AccessApprovalProto .internal_static_google_cloud_accessapproval_v1_ListApprovalRequestsMessage_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.accessapproval.v1.AccessApprovalProto .internal_static_google_cloud_accessapproval_v1_ListApprovalRequestsMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.class, com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.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> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</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> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</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 = 3; private int pageSize_ = 0; /** * * * <pre> * Requested page size. * </pre> * * <code>int32 page_size = 3;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_); } if (pageSize_ != 0) { output.writeInt32(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage)) { return super.equals(obj); } com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage other = (com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage) 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.cloud.accessapproval.v1.ListApprovalRequestsMessage parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage 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.accessapproval.v1.ListApprovalRequestsMessage parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage 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.accessapproval.v1.ListApprovalRequestsMessage parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage 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.accessapproval.v1.ListApprovalRequestsMessage parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage 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.accessapproval.v1.ListApprovalRequestsMessage parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage 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.accessapproval.v1.ListApprovalRequestsMessage 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 list approval requests. * </pre> * * Protobuf type {@code google.cloud.accessapproval.v1.ListApprovalRequestsMessage} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.accessapproval.v1.ListApprovalRequestsMessage) com.google.cloud.accessapproval.v1.ListApprovalRequestsMessageOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.accessapproval.v1.AccessApprovalProto .internal_static_google_cloud_accessapproval_v1_ListApprovalRequestsMessage_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.accessapproval.v1.AccessApprovalProto .internal_static_google_cloud_accessapproval_v1_ListApprovalRequestsMessage_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.class, com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.Builder.class); } // Construct using com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.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.cloud.accessapproval.v1.AccessApprovalProto .internal_static_google_cloud_accessapproval_v1_ListApprovalRequestsMessage_descriptor; } @java.lang.Override public com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage getDefaultInstanceForType() { return com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.getDefaultInstance(); } @java.lang.Override public com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage build() { com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage buildPartial() { com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage result = new com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage 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.cloud.accessapproval.v1.ListApprovalRequestsMessage) { return mergeFrom((com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage other) { if (other == com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000002; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000004; break; } // case 24 case 34: { pageToken_ = 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 java.lang.Object parent_ = ""; /** * * * <pre> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.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> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.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> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.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> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * The parent resource. This may be "projects/{project}", * "folders/{folder}", or "organizations/{organization}". * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</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> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</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> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</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> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A filter on the type of approval requests to retrieve. Must be one of the * following values: * * * [not set]: Requests that are pending or have active approvals. * * ALL: All requests. * * PENDING: Only pending requests. * * ACTIVE: Only active (i.e. currently approved) requests. * * DISMISSED: Only requests that have been dismissed, or requests that * are not approved and past expiration. * * EXPIRED: Only requests that have been approved, and the approval has * expired. * * HISTORY: Active, dismissed and expired requests. * </pre> * * <code>string filter = 2;</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> * Requested page size. * </pre> * * <code>int32 page_size = 3;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Requested page size. * </pre> * * <code>int32 page_size = 3;</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> * Requested page size. * </pre> * * <code>int32 page_size = 3;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000004); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</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> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * A token identifying the page of results to return. * </pre> * * <code>string page_token = 4;</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.cloud.accessapproval.v1.ListApprovalRequestsMessage) } // @@protoc_insertion_point(class_scope:google.cloud.accessapproval.v1.ListApprovalRequestsMessage) private static final com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage(); } public static com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListApprovalRequestsMessage> PARSER = new com.google.protobuf.AbstractParser<ListApprovalRequestsMessage>() { @java.lang.Override public ListApprovalRequestsMessage 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<ListApprovalRequestsMessage> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListApprovalRequestsMessage> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.accessapproval.v1.ListApprovalRequestsMessage getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,889
java-aiplatform/google-cloud-aiplatform/src/main/java/com/google/cloud/aiplatform/v1beta1/ReasoningEngineExecutionServiceClient.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.v1beta1; import com.google.api.HttpBody; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.paging.AbstractFixedSizeCollection; import com.google.api.gax.paging.AbstractPage; import com.google.api.gax.paging.AbstractPagedListResponse; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.ServerStreamingCallable; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.aiplatform.v1beta1.stub.ReasoningEngineExecutionServiceStub; import com.google.cloud.aiplatform.v1beta1.stub.ReasoningEngineExecutionServiceStubSettings; 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.common.util.concurrent.MoreExecutors; 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 java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: A service for executing queries on Reasoning Engine. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * QueryReasoningEngineRequest request = * QueryReasoningEngineRequest.newBuilder() * .setName( * ReasoningEngineName.of("[PROJECT]", "[LOCATION]", "[REASONING_ENGINE]") * .toString()) * .setInput(Struct.newBuilder().build()) * .setClassMethod("classMethod-937857927") * .build(); * QueryReasoningEngineResponse response = * reasoningEngineExecutionServiceClient.queryReasoningEngine(request); * } * }</pre> * * <p>Note: close() needs to be called on the ReasoningEngineExecutionServiceClient object to clean * up resources such as threads. In the example above, try-with-resources is used, which * automatically calls close(). * * <table> * <caption>Methods</caption> * <tr> * <th>Method</th> * <th>Description</th> * <th>Method Variants</th> * </tr> * <tr> * <td><p> QueryReasoningEngine</td> * <td><p> Queries using a reasoning engine.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> queryReasoningEngine(QueryReasoningEngineRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> queryReasoningEngineCallable() * </ul> * </td> * </tr> * <tr> * <td><p> StreamQueryReasoningEngine</td> * <td><p> Streams queries using a reasoning engine.</td> * <td> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> streamQueryReasoningEngineCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ListLocations</td> * <td><p> Lists information about the supported locations for this service.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> listLocations(ListLocationsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> listLocationsPagedCallable() * <li><p> listLocationsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GetLocation</td> * <td><p> Gets information about a location.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> getLocation(GetLocationRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getLocationCallable() * </ul> * </td> * </tr> * <tr> * <td><p> SetIamPolicy</td> * <td><p> Sets the access control policy on the specified resource. Replacesany existing policy. * <p> Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> setIamPolicy(SetIamPolicyRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> setIamPolicyCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GetIamPolicy</td> * <td><p> Gets the access control policy for a resource. Returns an empty policyif the resource exists and does not have a policy set.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> getIamPolicy(GetIamPolicyRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> getIamPolicyCallable() * </ul> * </td> * </tr> * <tr> * <td><p> TestIamPermissions</td> * <td><p> Returns permissions that a caller has on the specified resource. If theresource does not exist, this will return an empty set ofpermissions, not a `NOT_FOUND` error. * <p> Note: This operation is designed to be used for buildingpermission-aware UIs and command-line tools, not for authorizationchecking. This operation may "fail open" without warning.</td> * <td> * <p>Request object method variants only take one parameter, a request object, which must be constructed before the call.</p> * <ul> * <li><p> testIamPermissions(TestIamPermissionsRequest request) * </ul> * <p>Callable method variants take no parameters and return an immutable API callable object, which can be used to initiate calls to the service.</p> * <ul> * <li><p> testIamPermissionsCallable() * </ul> * </td> * </tr> * </table> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of * ReasoningEngineExecutionServiceSettings to create(). For example: * * <p>To customize credentials: * * <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 * ReasoningEngineExecutionServiceSettings reasoningEngineExecutionServiceSettings = * ReasoningEngineExecutionServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create(reasoningEngineExecutionServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <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 * ReasoningEngineExecutionServiceSettings reasoningEngineExecutionServiceSettings = * ReasoningEngineExecutionServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create(reasoningEngineExecutionServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @BetaApi @Generated("by gapic-generator-java") public class ReasoningEngineExecutionServiceClient implements BackgroundResource { private final ReasoningEngineExecutionServiceSettings settings; private final ReasoningEngineExecutionServiceStub stub; /** Constructs an instance of ReasoningEngineExecutionServiceClient with default settings. */ public static final ReasoningEngineExecutionServiceClient create() throws IOException { return create(ReasoningEngineExecutionServiceSettings.newBuilder().build()); } /** * Constructs an instance of ReasoningEngineExecutionServiceClient, using the given settings. The * channels are created based on the settings passed in, or defaults for any settings that are not * set. */ public static final ReasoningEngineExecutionServiceClient create( ReasoningEngineExecutionServiceSettings settings) throws IOException { return new ReasoningEngineExecutionServiceClient(settings); } /** * Constructs an instance of ReasoningEngineExecutionServiceClient, using the given stub for * making calls. This is for advanced usage - prefer using * create(ReasoningEngineExecutionServiceSettings). */ public static final ReasoningEngineExecutionServiceClient create( ReasoningEngineExecutionServiceStub stub) { return new ReasoningEngineExecutionServiceClient(stub); } /** * Constructs an instance of ReasoningEngineExecutionServiceClient, using the given settings. This * is protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected ReasoningEngineExecutionServiceClient(ReasoningEngineExecutionServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((ReasoningEngineExecutionServiceStubSettings) settings.getStubSettings()).createStub(); } protected ReasoningEngineExecutionServiceClient(ReasoningEngineExecutionServiceStub stub) { this.settings = null; this.stub = stub; } public final ReasoningEngineExecutionServiceSettings getSettings() { return settings; } public ReasoningEngineExecutionServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Queries using a reasoning engine. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * QueryReasoningEngineRequest request = * QueryReasoningEngineRequest.newBuilder() * .setName( * ReasoningEngineName.of("[PROJECT]", "[LOCATION]", "[REASONING_ENGINE]") * .toString()) * .setInput(Struct.newBuilder().build()) * .setClassMethod("classMethod-937857927") * .build(); * QueryReasoningEngineResponse response = * reasoningEngineExecutionServiceClient.queryReasoningEngine(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final QueryReasoningEngineResponse queryReasoningEngine( QueryReasoningEngineRequest request) { return queryReasoningEngineCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Queries using a reasoning engine. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * QueryReasoningEngineRequest request = * QueryReasoningEngineRequest.newBuilder() * .setName( * ReasoningEngineName.of("[PROJECT]", "[LOCATION]", "[REASONING_ENGINE]") * .toString()) * .setInput(Struct.newBuilder().build()) * .setClassMethod("classMethod-937857927") * .build(); * ApiFuture<QueryReasoningEngineResponse> future = * reasoningEngineExecutionServiceClient.queryReasoningEngineCallable().futureCall(request); * // Do something. * QueryReasoningEngineResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<QueryReasoningEngineRequest, QueryReasoningEngineResponse> queryReasoningEngineCallable() { return stub.queryReasoningEngineCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Streams queries using a reasoning engine. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * StreamQueryReasoningEngineRequest request = * StreamQueryReasoningEngineRequest.newBuilder() * .setName( * ReasoningEngineName.of("[PROJECT]", "[LOCATION]", "[REASONING_ENGINE]") * .toString()) * .setInput(Struct.newBuilder().build()) * .setClassMethod("classMethod-937857927") * .build(); * ServerStream<HttpBody> stream = * reasoningEngineExecutionServiceClient.streamQueryReasoningEngineCallable().call(request); * for (HttpBody response : stream) { * // Do something when a response is received. * } * } * }</pre> */ public final ServerStreamingCallable<StreamQueryReasoningEngineRequest, HttpBody> streamQueryReasoningEngineCallable() { return stub.streamQueryReasoningEngineCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Location element : * reasoningEngineExecutionServiceClient.listLocations(request).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListLocationsPagedResponse listLocations(ListLocationsRequest request) { return listLocationsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Location> future = * reasoningEngineExecutionServiceClient.listLocationsPagedCallable().futureCall(request); * // Do something. * for (Location element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListLocationsRequest, ListLocationsPagedResponse> listLocationsPagedCallable() { return stub.listLocationsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Lists information about the supported locations for this service. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * ListLocationsRequest request = * ListLocationsRequest.newBuilder() * .setName("name3373707") * .setFilter("filter-1274492040") * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListLocationsResponse response = * reasoningEngineExecutionServiceClient.listLocationsCallable().call(request); * for (Location element : response.getLocationsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListLocationsRequest, ListLocationsResponse> listLocationsCallable() { return stub.listLocationsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets information about a location. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * Location response = reasoningEngineExecutionServiceClient.getLocation(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Location getLocation(GetLocationRequest request) { return getLocationCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets information about a location. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); * ApiFuture<Location> future = * reasoningEngineExecutionServiceClient.getLocationCallable().futureCall(request); * // Do something. * Location response = future.get(); * } * }</pre> */ public final UnaryCallable<GetLocationRequest, Location> getLocationCallable() { return stub.getLocationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Sets the access control policy on the specified resource. Replacesany existing policy. * * <p>Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * SetIamPolicyRequest request = * SetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setPolicy(Policy.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * Policy response = reasoningEngineExecutionServiceClient.setIamPolicy(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Policy setIamPolicy(SetIamPolicyRequest request) { return setIamPolicyCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Sets the access control policy on the specified resource. Replacesany existing policy. * * <p>Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED`errors. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * SetIamPolicyRequest request = * SetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setPolicy(Policy.newBuilder().build()) * .setUpdateMask(FieldMask.newBuilder().build()) * .build(); * ApiFuture<Policy> future = * reasoningEngineExecutionServiceClient.setIamPolicyCallable().futureCall(request); * // Do something. * Policy response = future.get(); * } * }</pre> */ public final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() { return stub.setIamPolicyCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets the access control policy for a resource. Returns an empty policyif the resource exists * and does not have a policy set. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * GetIamPolicyRequest request = * GetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setOptions(GetPolicyOptions.newBuilder().build()) * .build(); * Policy response = reasoningEngineExecutionServiceClient.getIamPolicy(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Policy getIamPolicy(GetIamPolicyRequest request) { return getIamPolicyCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Gets the access control policy for a resource. Returns an empty policyif the resource exists * and does not have a policy set. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * GetIamPolicyRequest request = * GetIamPolicyRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .setOptions(GetPolicyOptions.newBuilder().build()) * .build(); * ApiFuture<Policy> future = * reasoningEngineExecutionServiceClient.getIamPolicyCallable().futureCall(request); * // Do something. * Policy response = future.get(); * } * }</pre> */ public final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() { return stub.getIamPolicyCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns permissions that a caller has on the specified resource. If theresource does not exist, * this will return an empty set ofpermissions, not a `NOT_FOUND` error. * * <p>Note: This operation is designed to be used for buildingpermission-aware UIs and * command-line tools, not for authorizationchecking. This operation may "fail open" without * warning. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * TestIamPermissionsRequest request = * TestIamPermissionsRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .addAllPermissions(new ArrayList<String>()) * .build(); * TestIamPermissionsResponse response = * reasoningEngineExecutionServiceClient.testIamPermissions(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsRequest request) { return testIamPermissionsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns permissions that a caller has on the specified resource. If theresource does not exist, * this will return an empty set ofpermissions, not a `NOT_FOUND` error. * * <p>Note: This operation is designed to be used for buildingpermission-aware UIs and * command-line tools, not for authorizationchecking. This operation may "fail open" without * warning. * * <p>Sample code: * * <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 * try (ReasoningEngineExecutionServiceClient reasoningEngineExecutionServiceClient = * ReasoningEngineExecutionServiceClient.create()) { * TestIamPermissionsRequest request = * TestIamPermissionsRequest.newBuilder() * .setResource( * EndpointName.ofProjectLocationEndpointName( * "[PROJECT]", "[LOCATION]", "[ENDPOINT]") * .toString()) * .addAllPermissions(new ArrayList<String>()) * .build(); * ApiFuture<TestIamPermissionsResponse> future = * reasoningEngineExecutionServiceClient.testIamPermissionsCallable().futureCall(request); * // Do something. * TestIamPermissionsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse> testIamPermissionsCallable() { return stub.testIamPermissionsCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } public static class ListLocationsPagedResponse extends AbstractPagedListResponse< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage, ListLocationsFixedSizeCollection> { public static ApiFuture<ListLocationsPagedResponse> createAsync( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ApiFuture<ListLocationsResponse> futureResponse) { ApiFuture<ListLocationsPage> futurePage = ListLocationsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListLocationsPagedResponse(input), MoreExecutors.directExecutor()); } private ListLocationsPagedResponse(ListLocationsPage page) { super(page, ListLocationsFixedSizeCollection.createEmptyCollection()); } } public static class ListLocationsPage extends AbstractPage< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage> { private ListLocationsPage( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ListLocationsResponse response) { super(context, response); } private static ListLocationsPage createEmptyPage() { return new ListLocationsPage(null, null); } @Override protected ListLocationsPage createPage( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ListLocationsResponse response) { return new ListLocationsPage(context, response); } @Override public ApiFuture<ListLocationsPage> createPageAsync( PageContext<ListLocationsRequest, ListLocationsResponse, Location> context, ApiFuture<ListLocationsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListLocationsFixedSizeCollection extends AbstractFixedSizeCollection< ListLocationsRequest, ListLocationsResponse, Location, ListLocationsPage, ListLocationsFixedSizeCollection> { private ListLocationsFixedSizeCollection(List<ListLocationsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListLocationsFixedSizeCollection createEmptyCollection() { return new ListLocationsFixedSizeCollection(null, 0); } @Override protected ListLocationsFixedSizeCollection createCollection( List<ListLocationsPage> pages, int collectionSize) { return new ListLocationsFixedSizeCollection(pages, collectionSize); } } }
googleapis/google-cloud-java
37,690
java-speech/proto-google-cloud-speech-v2/src/main/java/com/google/cloud/speech/v2/ListCustomClassesResponse.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/speech/v2/cloud_speech.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.speech.v2; /** * * * <pre> * Response message for the * [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] method. * </pre> * * Protobuf type {@code google.cloud.speech.v2.ListCustomClassesResponse} */ public final class ListCustomClassesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v2.ListCustomClassesResponse) ListCustomClassesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListCustomClassesResponse.newBuilder() to construct. private ListCustomClassesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListCustomClassesResponse() { customClasses_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListCustomClassesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ListCustomClassesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ListCustomClassesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.ListCustomClassesResponse.class, com.google.cloud.speech.v2.ListCustomClassesResponse.Builder.class); } public static final int CUSTOM_CLASSES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.speech.v2.CustomClass> customClasses_; /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.speech.v2.CustomClass> getCustomClassesList() { return customClasses_; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.speech.v2.CustomClassOrBuilder> getCustomClassesOrBuilderList() { return customClasses_; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ @java.lang.Override public int getCustomClassesCount() { return customClasses_.size(); } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ @java.lang.Override public com.google.cloud.speech.v2.CustomClass getCustomClasses(int index) { return customClasses_.get(index); } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ @java.lang.Override public com.google.cloud.speech.v2.CustomClassOrBuilder getCustomClassesOrBuilder(int index) { return customClasses_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </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 < customClasses_.size(); i++) { output.writeMessage(1, customClasses_.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 < customClasses_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, customClasses_.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.speech.v2.ListCustomClassesResponse)) { return super.equals(obj); } com.google.cloud.speech.v2.ListCustomClassesResponse other = (com.google.cloud.speech.v2.ListCustomClassesResponse) obj; if (!getCustomClassesList().equals(other.getCustomClassesList())) 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 (getCustomClassesCount() > 0) { hash = (37 * hash) + CUSTOM_CLASSES_FIELD_NUMBER; hash = (53 * hash) + getCustomClassesList().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.speech.v2.ListCustomClassesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.ListCustomClassesResponse 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.speech.v2.ListCustomClassesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.ListCustomClassesResponse 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.speech.v2.ListCustomClassesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.ListCustomClassesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v2.ListCustomClassesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.ListCustomClassesResponse 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.speech.v2.ListCustomClassesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.ListCustomClassesResponse 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.speech.v2.ListCustomClassesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.ListCustomClassesResponse 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.speech.v2.ListCustomClassesResponse 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 * [ListCustomClasses][google.cloud.speech.v2.Speech.ListCustomClasses] method. * </pre> * * Protobuf type {@code google.cloud.speech.v2.ListCustomClassesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v2.ListCustomClassesResponse) com.google.cloud.speech.v2.ListCustomClassesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ListCustomClassesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ListCustomClassesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.ListCustomClassesResponse.class, com.google.cloud.speech.v2.ListCustomClassesResponse.Builder.class); } // Construct using com.google.cloud.speech.v2.ListCustomClassesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (customClassesBuilder_ == null) { customClasses_ = java.util.Collections.emptyList(); } else { customClasses_ = null; customClassesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ListCustomClassesResponse_descriptor; } @java.lang.Override public com.google.cloud.speech.v2.ListCustomClassesResponse getDefaultInstanceForType() { return com.google.cloud.speech.v2.ListCustomClassesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v2.ListCustomClassesResponse build() { com.google.cloud.speech.v2.ListCustomClassesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v2.ListCustomClassesResponse buildPartial() { com.google.cloud.speech.v2.ListCustomClassesResponse result = new com.google.cloud.speech.v2.ListCustomClassesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.speech.v2.ListCustomClassesResponse result) { if (customClassesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { customClasses_ = java.util.Collections.unmodifiableList(customClasses_); bitField0_ = (bitField0_ & ~0x00000001); } result.customClasses_ = customClasses_; } else { result.customClasses_ = customClassesBuilder_.build(); } } private void buildPartial0(com.google.cloud.speech.v2.ListCustomClassesResponse 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.speech.v2.ListCustomClassesResponse) { return mergeFrom((com.google.cloud.speech.v2.ListCustomClassesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v2.ListCustomClassesResponse other) { if (other == com.google.cloud.speech.v2.ListCustomClassesResponse.getDefaultInstance()) return this; if (customClassesBuilder_ == null) { if (!other.customClasses_.isEmpty()) { if (customClasses_.isEmpty()) { customClasses_ = other.customClasses_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureCustomClassesIsMutable(); customClasses_.addAll(other.customClasses_); } onChanged(); } } else { if (!other.customClasses_.isEmpty()) { if (customClassesBuilder_.isEmpty()) { customClassesBuilder_.dispose(); customClassesBuilder_ = null; customClasses_ = other.customClasses_; bitField0_ = (bitField0_ & ~0x00000001); customClassesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCustomClassesFieldBuilder() : null; } else { customClassesBuilder_.addAllMessages(other.customClasses_); } } } 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.speech.v2.CustomClass m = input.readMessage( com.google.cloud.speech.v2.CustomClass.parser(), extensionRegistry); if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.add(m); } else { customClassesBuilder_.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.speech.v2.CustomClass> customClasses_ = java.util.Collections.emptyList(); private void ensureCustomClassesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { customClasses_ = new java.util.ArrayList<com.google.cloud.speech.v2.CustomClass>(customClasses_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v2.CustomClass, com.google.cloud.speech.v2.CustomClass.Builder, com.google.cloud.speech.v2.CustomClassOrBuilder> customClassesBuilder_; /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public java.util.List<com.google.cloud.speech.v2.CustomClass> getCustomClassesList() { if (customClassesBuilder_ == null) { return java.util.Collections.unmodifiableList(customClasses_); } else { return customClassesBuilder_.getMessageList(); } } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public int getCustomClassesCount() { if (customClassesBuilder_ == null) { return customClasses_.size(); } else { return customClassesBuilder_.getCount(); } } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v2.CustomClass getCustomClasses(int index) { if (customClassesBuilder_ == null) { return customClasses_.get(index); } else { return customClassesBuilder_.getMessage(index); } } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder setCustomClasses(int index, com.google.cloud.speech.v2.CustomClass value) { if (customClassesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCustomClassesIsMutable(); customClasses_.set(index, value); onChanged(); } else { customClassesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder setCustomClasses( int index, com.google.cloud.speech.v2.CustomClass.Builder builderForValue) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.set(index, builderForValue.build()); onChanged(); } else { customClassesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses(com.google.cloud.speech.v2.CustomClass value) { if (customClassesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCustomClassesIsMutable(); customClasses_.add(value); onChanged(); } else { customClassesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses(int index, com.google.cloud.speech.v2.CustomClass value) { if (customClassesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCustomClassesIsMutable(); customClasses_.add(index, value); onChanged(); } else { customClassesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses( com.google.cloud.speech.v2.CustomClass.Builder builderForValue) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.add(builderForValue.build()); onChanged(); } else { customClassesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder addCustomClasses( int index, com.google.cloud.speech.v2.CustomClass.Builder builderForValue) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.add(index, builderForValue.build()); onChanged(); } else { customClassesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder addAllCustomClasses( java.lang.Iterable<? extends com.google.cloud.speech.v2.CustomClass> values) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, customClasses_); onChanged(); } else { customClassesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder clearCustomClasses() { if (customClassesBuilder_ == null) { customClasses_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { customClassesBuilder_.clear(); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public Builder removeCustomClasses(int index) { if (customClassesBuilder_ == null) { ensureCustomClassesIsMutable(); customClasses_.remove(index); onChanged(); } else { customClassesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v2.CustomClass.Builder getCustomClassesBuilder(int index) { return getCustomClassesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v2.CustomClassOrBuilder getCustomClassesOrBuilder(int index) { if (customClassesBuilder_ == null) { return customClasses_.get(index); } else { return customClassesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public java.util.List<? extends com.google.cloud.speech.v2.CustomClassOrBuilder> getCustomClassesOrBuilderList() { if (customClassesBuilder_ != null) { return customClassesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(customClasses_); } } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v2.CustomClass.Builder addCustomClassesBuilder() { return getCustomClassesFieldBuilder() .addBuilder(com.google.cloud.speech.v2.CustomClass.getDefaultInstance()); } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public com.google.cloud.speech.v2.CustomClass.Builder addCustomClassesBuilder(int index) { return getCustomClassesFieldBuilder() .addBuilder(index, com.google.cloud.speech.v2.CustomClass.getDefaultInstance()); } /** * * * <pre> * The list of requested CustomClasses. * </pre> * * <code>repeated .google.cloud.speech.v2.CustomClass custom_classes = 1;</code> */ public java.util.List<com.google.cloud.speech.v2.CustomClass.Builder> getCustomClassesBuilderList() { return getCustomClassesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v2.CustomClass, com.google.cloud.speech.v2.CustomClass.Builder, com.google.cloud.speech.v2.CustomClassOrBuilder> getCustomClassesFieldBuilder() { if (customClassesBuilder_ == null) { customClassesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.speech.v2.CustomClass, com.google.cloud.speech.v2.CustomClass.Builder, com.google.cloud.speech.v2.CustomClassOrBuilder>( customClasses_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); customClasses_ = null; } return customClassesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as * [page_token][google.cloud.speech.v2.ListCustomClassesRequest.page_token] to * retrieve the next page. If this field is omitted, there are no subsequent * pages. This token expires after 72 hours. * </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.speech.v2.ListCustomClassesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v2.ListCustomClassesResponse) private static final com.google.cloud.speech.v2.ListCustomClassesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v2.ListCustomClassesResponse(); } public static com.google.cloud.speech.v2.ListCustomClassesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListCustomClassesResponse> PARSER = new com.google.protobuf.AbstractParser<ListCustomClassesResponse>() { @java.lang.Override public ListCustomClassesResponse 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<ListCustomClassesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListCustomClassesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v2.ListCustomClassesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,700
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SetIamPolicyLicenseRequest.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 Licenses.SetIamPolicy. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.SetIamPolicyLicenseRequest} */ public final class SetIamPolicyLicenseRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.SetIamPolicyLicenseRequest) SetIamPolicyLicenseRequestOrBuilder { private static final long serialVersionUID = 0L; // Use SetIamPolicyLicenseRequest.newBuilder() to construct. private SetIamPolicyLicenseRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private SetIamPolicyLicenseRequest() { project_ = ""; resource_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new SetIamPolicyLicenseRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SetIamPolicyLicenseRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SetIamPolicyLicenseRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.class, com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.Builder.class); } private int bitField0_; public static final int GLOBAL_SET_POLICY_REQUEST_RESOURCE_FIELD_NUMBER = 337048498; private com.google.cloud.compute.v1.GlobalSetPolicyRequest globalSetPolicyRequestResource_; /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the globalSetPolicyRequestResource field is set. */ @java.lang.Override public boolean hasGlobalSetPolicyRequestResource() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The globalSetPolicyRequestResource. */ @java.lang.Override public com.google.cloud.compute.v1.GlobalSetPolicyRequest getGlobalSetPolicyRequestResource() { return globalSetPolicyRequestResource_ == null ? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance() : globalSetPolicyRequestResource_; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder getGlobalSetPolicyRequestResourceOrBuilder() { return globalSetPolicyRequestResource_ == null ? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance() : globalSetPolicyRequestResource_; } 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 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(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.writeMessage(337048498, getGlobalSetPolicyRequestResource()); } 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(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.computeMessageSize( 337048498, getGlobalSetPolicyRequestResource()); } 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.SetIamPolicyLicenseRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.SetIamPolicyLicenseRequest other = (com.google.cloud.compute.v1.SetIamPolicyLicenseRequest) obj; if (hasGlobalSetPolicyRequestResource() != other.hasGlobalSetPolicyRequestResource()) return false; if (hasGlobalSetPolicyRequestResource()) { if (!getGlobalSetPolicyRequestResource().equals(other.getGlobalSetPolicyRequestResource())) return false; } if (!getProject().equals(other.getProject())) 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 (hasGlobalSetPolicyRequestResource()) { hash = (37 * hash) + GLOBAL_SET_POLICY_REQUEST_RESOURCE_FIELD_NUMBER; hash = (53 * hash) + getGlobalSetPolicyRequestResource().hashCode(); } hash = (37 * hash) + PROJECT_FIELD_NUMBER; hash = (53 * hash) + getProject().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.SetIamPolicyLicenseRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest 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.SetIamPolicyLicenseRequest 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 Licenses.SetIamPolicy. See the method description for details. * </pre> * * Protobuf type {@code google.cloud.compute.v1.SetIamPolicyLicenseRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.SetIamPolicyLicenseRequest) com.google.cloud.compute.v1.SetIamPolicyLicenseRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SetIamPolicyLicenseRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_SetIamPolicyLicenseRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.class, com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getGlobalSetPolicyRequestResourceFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; globalSetPolicyRequestResource_ = null; if (globalSetPolicyRequestResourceBuilder_ != null) { globalSetPolicyRequestResourceBuilder_.dispose(); globalSetPolicyRequestResourceBuilder_ = null; } project_ = ""; 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_SetIamPolicyLicenseRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.SetIamPolicyLicenseRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.SetIamPolicyLicenseRequest build() { com.google.cloud.compute.v1.SetIamPolicyLicenseRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.SetIamPolicyLicenseRequest buildPartial() { com.google.cloud.compute.v1.SetIamPolicyLicenseRequest result = new com.google.cloud.compute.v1.SetIamPolicyLicenseRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.compute.v1.SetIamPolicyLicenseRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.globalSetPolicyRequestResource_ = globalSetPolicyRequestResourceBuilder_ == null ? globalSetPolicyRequestResource_ : globalSetPolicyRequestResourceBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.project_ = project_; } if (((from_bitField0_ & 0x00000004) != 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.SetIamPolicyLicenseRequest) { return mergeFrom((com.google.cloud.compute.v1.SetIamPolicyLicenseRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.SetIamPolicyLicenseRequest other) { if (other == com.google.cloud.compute.v1.SetIamPolicyLicenseRequest.getDefaultInstance()) return this; if (other.hasGlobalSetPolicyRequestResource()) { mergeGlobalSetPolicyRequestResource(other.getGlobalSetPolicyRequestResource()); } if (!other.getProject().isEmpty()) { project_ = other.project_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getResource().isEmpty()) { resource_ = other.resource_; 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 1566449778: { resource_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 1566449778 case 1820481738: { project_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 1820481738 case -1598579310: { input.readMessage( getGlobalSetPolicyRequestResourceFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case -1598579310 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.compute.v1.GlobalSetPolicyRequest globalSetPolicyRequestResource_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.GlobalSetPolicyRequest, com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder, com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder> globalSetPolicyRequestResourceBuilder_; /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the globalSetPolicyRequestResource field is set. */ public boolean hasGlobalSetPolicyRequestResource() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The globalSetPolicyRequestResource. */ public com.google.cloud.compute.v1.GlobalSetPolicyRequest getGlobalSetPolicyRequestResource() { if (globalSetPolicyRequestResourceBuilder_ == null) { return globalSetPolicyRequestResource_ == null ? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance() : globalSetPolicyRequestResource_; } else { return globalSetPolicyRequestResourceBuilder_.getMessage(); } } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setGlobalSetPolicyRequestResource( com.google.cloud.compute.v1.GlobalSetPolicyRequest value) { if (globalSetPolicyRequestResourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } globalSetPolicyRequestResource_ = value; } else { globalSetPolicyRequestResourceBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setGlobalSetPolicyRequestResource( com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder builderForValue) { if (globalSetPolicyRequestResourceBuilder_ == null) { globalSetPolicyRequestResource_ = builderForValue.build(); } else { globalSetPolicyRequestResourceBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeGlobalSetPolicyRequestResource( com.google.cloud.compute.v1.GlobalSetPolicyRequest value) { if (globalSetPolicyRequestResourceBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && globalSetPolicyRequestResource_ != null && globalSetPolicyRequestResource_ != com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance()) { getGlobalSetPolicyRequestResourceBuilder().mergeFrom(value); } else { globalSetPolicyRequestResource_ = value; } } else { globalSetPolicyRequestResourceBuilder_.mergeFrom(value); } if (globalSetPolicyRequestResource_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearGlobalSetPolicyRequestResource() { bitField0_ = (bitField0_ & ~0x00000001); globalSetPolicyRequestResource_ = null; if (globalSetPolicyRequestResourceBuilder_ != null) { globalSetPolicyRequestResourceBuilder_.dispose(); globalSetPolicyRequestResourceBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder getGlobalSetPolicyRequestResourceBuilder() { bitField0_ |= 0x00000001; onChanged(); return getGlobalSetPolicyRequestResourceFieldBuilder().getBuilder(); } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder getGlobalSetPolicyRequestResourceOrBuilder() { if (globalSetPolicyRequestResourceBuilder_ != null) { return globalSetPolicyRequestResourceBuilder_.getMessageOrBuilder(); } else { return globalSetPolicyRequestResource_ == null ? com.google.cloud.compute.v1.GlobalSetPolicyRequest.getDefaultInstance() : globalSetPolicyRequestResource_; } } /** * * * <pre> * The body resource for this request * </pre> * * <code> * .google.cloud.compute.v1.GlobalSetPolicyRequest global_set_policy_request_resource = 337048498 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.GlobalSetPolicyRequest, com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder, com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder> getGlobalSetPolicyRequestResourceFieldBuilder() { if (globalSetPolicyRequestResourceBuilder_ == null) { globalSetPolicyRequestResourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.compute.v1.GlobalSetPolicyRequest, com.google.cloud.compute.v1.GlobalSetPolicyRequest.Builder, com.google.cloud.compute.v1.GlobalSetPolicyRequestOrBuilder>( getGlobalSetPolicyRequestResource(), getParentForChildren(), isClean()); globalSetPolicyRequestResource_ = null; } return globalSetPolicyRequestResourceBuilder_; } 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 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_ |= 0x00000004; 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_ & ~0x00000004); 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_ |= 0x00000004; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.SetIamPolicyLicenseRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.SetIamPolicyLicenseRequest) private static final com.google.cloud.compute.v1.SetIamPolicyLicenseRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.SetIamPolicyLicenseRequest(); } public static com.google.cloud.compute.v1.SetIamPolicyLicenseRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<SetIamPolicyLicenseRequest> PARSER = new com.google.protobuf.AbstractParser<SetIamPolicyLicenseRequest>() { @java.lang.Override public SetIamPolicyLicenseRequest 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<SetIamPolicyLicenseRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<SetIamPolicyLicenseRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.SetIamPolicyLicenseRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/closure-compiler
36,738
test/com/google/javascript/jscomp/RescopeGlobalSymbolsTest.java
/* * Copyright 2011 The Closure Compiler Authors. * * 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.javascript.jscomp; import static com.google.javascript.jscomp.deps.ModuleLoader.LOAD_WARNING; import com.google.javascript.jscomp.testing.JSChunkGraphBuilder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Unit tests for {@link RescopeGlobalSymbols} */ @RunWith(JUnit4.class) public final class RescopeGlobalSymbolsTest extends CompilerTestCase { private static final String NAMESPACE = "_"; private boolean assumeCrossModuleNames = true; @Override protected CompilerPass getProcessor(Compiler compiler) { return new RescopeGlobalSymbols(compiler, NAMESPACE, false, assumeCrossModuleNames); } @Override @Before public void setUp() throws Exception { super.setUp(); assumeCrossModuleNames = true; } @Test public void testVarDeclarations() { test("var a = 1;", "_.a = 1;"); test("var a = 1, b = 2, c = 3;", "_.a = 1; _.b = 2; _.c = 3;"); test( "var a = 'str', b = 1, c = { foo: 'bar' }, d = function() {};", "_.a = 'str'; _.b = 1; _.c = { foo: 'bar' }; _.d = function() {};"); test("if(1){var x = 1;}", "if(1){_.x = 1;}"); test("var x;", ""); test("var a, b = 1;", "_.b = 1"); } @Test public void testVarDeclarations_allSameModule() { assumeCrossModuleNames = false; testSame("var a = 1;"); testSame("var a = 1, b = 2, c = 3;"); testSame("var a = 'str', b = 1, c = { foo: 'bar' }, d = function() {};"); testSame("if(1){var x = 1;}"); testSame("var x;"); testSame("var a, b = 1;"); } @Test public void testVarDeclarations_export() { assumeCrossModuleNames = false; test("var _dumpException = 1;", "_._dumpException = 1"); } @Test public void testVarDeclarations_acrossModules() { assumeCrossModuleNames = false; test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("var a = 1;").addChunk("a").build()), expected("_.a = 1", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a = 1, b = 2, c = 3;") .addChunk("a;c;") .build()), expected("var b;_.a = 1; b = 2; _.c = 3;", "_.a;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a = 1, b = 2, c = 3;") .addChunk("b;c;") .build()), expected("var a;a = 1; _.b = 2; _.c = 3;", "_.b;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a = 1, b = 2, c = 3;b;c;") .addChunk("a;c;") .build()), expected("var b;_.a = 1; b = 2; _.c = 3;b;_.c", "_.a;_.c")); test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("var a, b = 1;").addChunk("b").build()), expected("var a;_.b = 1;", "_.b")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a, b = 1, c = 2;") .addChunk("b") .build()), expected("var a, c;_.b = 1;c = 2", "_.b")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a, b = 1, c = 2;") .addChunk("a") .build()), expected("var b, c;b = 1;c = 2", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a=1; var b=2,c=3;") .addChunk("a;c;") .build()), expected("var b;_.a=1;b=2;_.c=3", "_.a;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("1;var a, b = 1, c = 2;") .addChunk("b") .build()), expected("var a, c;1;_.b = 1;c = 2", "_.b")); } @Test public void testLetDeclarations() { test("let a = 1;", "_.a = 1;"); test("let a = 1, b = 2, c = 3;", "_.a = 1; _.b = 2; _.c = 3;"); test( "let a = 'str', b = 1, c = { foo: 'bar' }, d = function() {};", "_.a = 'str'; _.b = 1; _.c = { foo: 'bar' }; _.d = function() {};"); testSame("if(1){let x = 1;}"); test("let x;", ""); test("let a, b = 1;", "_.b = 1"); } @Test public void testLetDeclarations_allSameModule() { assumeCrossModuleNames = false; testSame("let a = 1;"); testSame("let a = 1, b = 2, c = 3;"); testSame("let a = 'str', b = 1, c = { foo: 'bar' }, d = function() {};"); testSame("if(1){let x = 1;}"); testSame("let x;"); testSame("let a, b = 1;"); } @Test public void testLetDeclarations_export() { assumeCrossModuleNames = false; test("let _dumpException = 1;", "_._dumpException = 1"); } @Test public void testLetDeclarations_acrossModules() { assumeCrossModuleNames = false; // test references across modules. test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("let a = 1;").addChunk("a").build()), expected("_.a = 1", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("let a = 1, b = 2, c = 3;") .addChunk("a;c;") .build()), expected("var b;_.a = 1; b = 2; _.c = 3;", "_.a;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("let a = 1, b = 2, c = 3;") .addChunk("b;c;") .build()), expected("var a;a = 1; _.b = 2; _.c = 3;", "_.b;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("let a = 1, b = 2, c = 3;b;c;") .addChunk("a;c;") .build()), expected("var b;_.a = 1; b = 2; _.c = 3;b;_.c", "_.a;_.c")); test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("let a, b = 1;").addChunk("b").build()), expected("var a;_.b = 1;", "_.b")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("let a, b = 1, c = 2;") .addChunk("b") .build()), expected("var a, c;_.b = 1;c = 2", "_.b")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("let a, b = 1, c = 2;") .addChunk("a") .build()), expected("var b, c;b = 1;c = 2", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("let a=1; let b=2,c=3;") .addChunk("a;c;") .build()), expected("var b;_.a=1;b=2;_.c=3", "_.a;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("1;let a, b = 1, c = 2;") .addChunk("b") .build()), expected("var a, c;1;_.b = 1;c = 2", "_.b")); // test non-globals with same name as cross-module globals. testSame( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("1;let a, b = 1, c = 2;") .addChunk("if (true) { let b = 3; b; }") .build())); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("1;let a, b = 1, c = 2;") .addChunk("b; if (true) { let b = 3; b; }") .build()), expected("var a, c; 1;_.b = 1;c = 2", "_.b; if (true) { let b = 3; b; }")); } @Test public void testConstDeclarations() { test("const a = 1;", "_.a = 1;"); test("const a = 1, b = 2, c = 3;", "_.a = 1; _.b = 2; _.c = 3;"); test( "const a = 'str', b = 1, c = { foo: 'bar' }, d = function() {};", "_.a = 'str'; _.b = 1; _.c = { foo: 'bar' }; _.d = function() {};"); testSame("if(1){const x = 1;}"); } @Test public void testConstDeclarations_allSameModule() { assumeCrossModuleNames = false; testSame("const a = 1;"); testSame("const a = 1, b = 2, c = 3;"); testSame("const a = 'str', b = 1, c = { foo: 'bar' }, d = function() {};"); testSame("if(1){const x = 1;}"); } @Test public void testConstDeclarations_export() { assumeCrossModuleNames = false; test("const _dumpException = 1;", "_._dumpException = 1"); } @Test public void testConstDeclarations_acrossModules() { assumeCrossModuleNames = false; // test references across modules. test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("const a = 1;").addChunk("a").build()), expected("_.a = 1", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("const a = 1, b = 2, c = 3;") .addChunk("a;c;") .build()), expected("var b;_.a = 1; b = 2; _.c = 3;", "_.a;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("const a = 1, b = 2, c = 3;") .addChunk("b;c;") .build()), expected("var a;a = 1; _.b = 2; _.c = 3;", "_.b;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("const a = 1, b = 2, c = 3;b;c;") .addChunk("a;c;") .build()), expected("var b;_.a = 1; b = 2; _.c = 3;b;_.c", "_.a;_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("const a=1; const b=2,c=3;") .addChunk("a;c;") .build()), expected("var b;_.a=1;b=2;_.c=3", "_.a;_.c")); // test non-globals with same name as cross-module globals. testSame( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("1;const a = 1, b = 1, c = 2;") .addChunk("if (true) { const b = 3; b; }") .build())); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("1;const a = 1, b = 1, c = 2;") .addChunk("b; if (true) { const b = 3; b; }") .build()), expected("var a, c; 1;a = 1; _.b = 1;c = 2", "_.b; if (true) { const b = 3; b; }")); } @Test public void testObjectDestructuringDeclarations() { test("var {a} = {}; a;", "({a: _.a} = {}); _.a;"); test("var {a: a} = {}; a;", "({a: _.a} = {}); _.a;"); test("var {key: a} = {}; a;", "({key: _.a} = {}); _.a;"); test("var {a: {b}} = {}; b;", "({a: {b: _.b}} = {}); _.b;"); test("var {a: {key: b}} = {}; b;", "({a: {key: _.b}} = {}); _.b;"); test("var {['computed']: a} = {}; a;", "({['computed']: _.a} = {}); _.a;"); test( "var {...a} = {a: 1, b: 2, c: 3}; a;", // "({..._.a} = {a: 1, b: 2, c: 3}); _.a;"); test( "var {a, ...b} = {x: 1, y: 2, z: 3}; a; b;", "({a: _.a, ..._.b} = {x: 1, y: 2, z: 3}); _.a; _.b;"); test("var {a = 3} = {}; a;", "({a: _.a = 3} = {}); _.a"); test("var {key: a = 3} = {}; a;", "({key: _.a = 3} = {}); _.a"); test("var {a} = {}, [b] = [], c = 3", "({a: _.a} = {}); [_.b] = []; _.c = 3;"); } @Test public void testObjectDestructuringDeclarations_allSameModule() { assumeCrossModuleNames = false; testSame("var {a} = {}; a;"); testSame("var {a: a} = {}; a;"); testSame("var {key: a} = {}; a;"); testSame("var {a: {b: b}} = {}; b;"); testSame("var {['computed']: a} = {}; a;"); testSame("var {a: a = 3} = {}; a;"); testSame("var {key: a = 3} = {}; a;"); testSame("var {['computed']: a = 3} = {}; a;"); testSame("var {a} = {}, b = 3;"); testSame("var [a] = [], b = 3;"); testSame("var a = 1, [b] = [], {c} = {};"); testSame("var {...a} = {x: 1, y: 2, z: 3}; a;"); testSame("var {a, ...b} = {x: 1, y: 2, z: 3}; a; b;"); } @Test public void testObjectDestructuringDeclarations_acrossModules() { assumeCrossModuleNames = false; test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("var {a: a} = {};").addChunk("a").build()), expected("({a: _.a} = {});", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var {a: a, b: b, c: c} = {};") .addChunk("a; c;") .build()), expected("var b;({a: _.a, b: b, c: _.c} = {});", "_.a; _.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var {a: a, b: b, c: c} = {};") .addChunk("b; c;") .build()), expected("var a;({a: a, b: _.b, c: _.c} = {});", "_.b; _.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var {a: a, b: b, c: c} = {}; b; c;") .addChunk("a; c;") .build()), expected("var b;({a: _.a, b: b, c: _.c} = {});b;_.c;", "_.a; _.c")); // Test var declarations containing a mix of destructuring and regular names test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("var {a} = {}, b;").addChunk("a").build()), expected("var b; ({a: _.a} = {});", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var {a} = {}, b = 3;") .addChunk("b") .build()), expected("var a; ({a} = {}); _.b = 3;", "_.b")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var {a: a, ...c} = {};") .addChunk("a;") .build()), expected("var c; ({a: _.a, ...c} = {});", "_.a;")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var {a: a, ...c} = {};") .addChunk("c;") .build()), expected("var a; ({a: a, ..._.c} = {});", "_.c")); } @Test public void testObjectDestructuringAssignments() { test("var a, b; ({key1: a, key2: b} = {}); a; b;", "({key1: _.a, key2: _.b} = {}); _.a; _.b;"); // Test a destructuring assignment with mixed global and local variables. test( "var a; if (true) { let b; ({key1: a, key2: b} = {}); b; } a;", "if (true) { let b; ({key1: _.a, key2: b} = {}); b; } _.a;"); test("var obj = {}; ({a: obj.a} = {}); obj.a;", "_.obj = {}; ({a: _.obj.a} = {}); _.obj.a;"); test( "var obj = {}; ({a: obj['foo bar']} = {}); obj['foo bar'];", " _.obj = {}; ({a: _.obj['foo bar']} = {}); _.obj['foo bar'];"); test( "var a = {}; ({...a.b} = {a: 1, b: 2, c: 3}); a.b;", // "_.a = {}; ({..._.a.b} = {a: 1, b: 2, c: 3}); _.a.b;"); test( "var a = {}; ({c, ...a.b} = {a: 1, b: 2, c: 3}); a.b;", // "_.a = {}; ({c, ..._.a.b} = {a: 1, b: 2, c: 3}); _.a.b;"); } @Test public void testArrayDestructuringDeclarations() { test("var [a] = [1]; a", "[_.a] = [1]; _.a;"); test("var [a, b, c] = [1, 2, 3]; a; b; c;", "[_.a, _.b, _.c] = [1, 2, 3]; _.a; _.b; _.c"); test("var [[a, b], c] = []; a; b; c", "[[_.a, _.b], _.c] = []; _.a; _.b; _.c;"); test("var [a = 5] = [1]; a", "[_.a = 5] = [1]; _.a;"); test("var [a, b = 5] = [1]; a; b;", "[_.a, _.b = 5] = [1]; _.a; _.b;"); test("var [...a] = [1, 2, 3]; a;", "[..._.a] = [1, 2, 3]; _.a;"); test("var [a, ...b] = [1, 2, 3]; a; b;", "[_.a, ..._.b] = [1, 2, 3]; _.a; _.b;"); test("var [a] = 1, b = 2; a; b;", "[_.a] = 1; _.b = 2; _.a; _.b;"); } @Test public void testArrayDestructuringDeclarations_sameModule() { assumeCrossModuleNames = false; testSame("var [a] = [1]; a"); testSame("var [a, b] = [1, 2]; a; b;"); testSame("var [[a, b], c] = []; a; b; c"); testSame("var [a = 5] = [1]; a"); testSame("var [a, b = 5] = [1]; a; b;"); testSame("var [...a] = [1, 2, 3]; a;"); testSame("var [a, ...b] = [1, 2, 3]; a; b;"); } @Test public void testArrayDestructuringDeclarations_acrossModules() { assumeCrossModuleNames = false; test( srcs(JSChunkGraphBuilder.forUnordered().addChunk("var [a] = [];").addChunk("a").build()), expected("[_.a] = [];", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var [a, b, c] = [];") .addChunk("a; c;") .build()), expected("var b; [_.a, b, _.c] = [];", "_.a; _.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var [a, b, c] = [];") .addChunk("b; c;") .build()), expected("var a; [a, _.b, _.c] = [];", "_.b; _.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var [a, b, c] = []; b; c;") .addChunk("a; c;") .build()), expected("var b; [_.a, b, _.c] = []; b; _.c;", "_.a; _.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var [a, ...c] = [];") .addChunk("a;") .build()), expected("var c; ([_.a, ...c] = []);", "_.a;")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var [a, ...c] = [];") .addChunk("c;") .build()), expected("var a; ([a, ..._.c] = []);", "_.c")); } @Test public void testArrayDestructuringAssignments() { test("var a, b; [a, b] = []; a; b;", "[_.a, _.b] = []; _.a; _.b;"); // Test a destructuring assignment with mixed global and local variables. test( "var a; if (true) { let b; [a, b] = []; b; } a;", "if (true) { let b; [_.a, b] = []; b; } _.a;"); // Test assignments to qualified names and quoted properties. test("var obj = {}; [obj.a] = []; obj.a;", "_.obj = {}; [_.obj.a] = []; _.obj.a;"); test( "var obj = {}; [ obj['foo bar']] = []; obj['foo bar'];", " _.obj = {}; [_.obj['foo bar']] = []; _.obj['foo bar'];"); test( "var a = {}; ([...a.b] = [1, 2, 3]); a.b;", // "_.a = {}; ([..._.a.b] = [1, 2, 3]); _.a.b;"); test( "var a = {}; ([c, ...a.b] = [1, 2, 3]); a.b;", // "_.a = {}; ([c, ..._.a.b] = [1, 2, 3]); _.a.b;"); } @Test public void testClasses() { test("class A {}", "_.A = class {};"); test("class A {} class B extends A {}", "_.A = class {}; _.B = class extends _.A {}"); test("class A {} let a = new A;", "_.A = class {}; _.a = new _.A;"); test( """ const PI = 3.14; class A { static printPi() { console.log(PI); } } A.printPi(); """, """ _.PI = 3.14; _.A = class { static printPi() { console.log(_.PI); } } _.A.printPi(); """); // Test that class expression names are not rewritten. test("var A = class Name {};", "_.A = class Name {};"); test("var A = class A {};", "_.A = class A {};"); } @Test public void testClasses_nonGlobal() { testSame("if (true) { class A {} }"); test("function foo() { class A {} }", "_.foo = function() { class A {} };"); test("const A = 5; { class A {} }", "_.A = 5; { class A {} }"); } @Test public void testClasses_allSameModule() { assumeCrossModuleNames = false; test("class A {}", "var A = class {};"); test("class A {} class B extends A {}", "var A = class {}; var B = class extends A {}"); testSame("if (true) { class A {} }"); } @Test public void testForLoops() { assumeCrossModuleNames = false; test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("for (var i = 0, c = 2; i < 1000; i++);") .addChunk("c") .build()), expected("var i;for (i = 0, _.c = 2; i < 1000; i++);", "_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var i = 0, c = 2; i < 1000; i++);") .addChunk("i") .build()), expected("var c;for ( _.i = 0, c = 2; _.i < 1000; _.i++);", "_.i")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var {i: i, c: c} = {}; i < 1000; i++);") .addChunk("c") .build()), expected("var i; for ( ({i: i, c: _.c} = {}); i < 1000; i++);", "_.c")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var [i, c] = [0, 2]; i < 1000; i++);") .addChunk("c;") .build()), expected("var i; for ( [i, _.c] = [0, 2]; i < 1000; i++);", "_.c;")); } @Test public void testForLoops_acrossModules() { test("for (var i = 0; i < 1000; i++);", "for (_.i = 0; _.i < 1000; _.i++);"); test("for (var i = 0, c = 2; i < 1000; i++);", "for (_.i = 0, _.c = 2; _.i < 1000; _.i++);"); test( "for (var i = 0, c = 2, d = 3; i < 1000; i++);", "for (_.i = 0, _.c = 2, _.d = 3; _.i < 1000; _.i++);"); test( "for (var i = 0, c = 2, d = 3, e = 4; i < 1000; i++);", "for (_.i = 0, _.c = 2, _.d = 3, _.e = 4; _.i < 1000; _.i++);"); test("for (var i = 0; i < 1000;)i++;", "for (_.i = 0; _.i < 1000;)_.i++;"); test("for (var i = 0,b; i < 1000;)i++;b++", "for (_.i = 0,_.b; _.i < 1000;)_.i++;_.b++"); test("var o={};for (var i in o)i++;", "_.o={};for (_.i in _.o)_.i++;"); // Test destructuring. test("for (var [i] = [0]; i < 1000; i++);", "for ([_.i] = [0]; _.i < 1000; _.i++);"); test("for (var {i: i} = {}; i < 1000; i++);", " for (({i: _.i} = {}); _.i < 1000; _.i++);"); testSame("for (let [i] = [0]; i < 1000; i++);"); } @Test public void testForInLoops_allSameModule() { assumeCrossModuleNames = false; testSame("for (var i in {});"); testSame("for (var [a] in {});"); testSame("for (var {a: a} in {});"); } @Test public void testForInLoops_acrossModules() { assumeCrossModuleNames = false; test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("for (var i in {});") .addChunk("i") .build()), expected("for (_.i in {});", "_.i")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var [ a, b] in {});") .addChunk("a;") .build()), expected("var b; for ( [_.a, b] in {});", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var {i: i, c: c} in {});") .addChunk("c") .build()), expected("var i; for ( {i: i, c: _.c} in {});", "_.c")); } @Test public void testForOfLoops_allSameModule() { assumeCrossModuleNames = false; testSame("for (var i of [1, 2, 3]);"); testSame("for (var [a] of []);"); testSame("for (var {a: a} of {});"); } @Test public void testForOfLoops_acrossModules() { assumeCrossModuleNames = false; test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("for (var i of []);") .addChunk("i") .build()), expected("for (_.i of []);", "_.i")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var [ a, b] of []);") .addChunk("a;") .build()), expected("var b; for ( [_.a, b] of []);", "_.a")); test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for (var {i: i, c: c} of []);") .addChunk("c") .build()), expected("var i; for ( {i: i, c: _.c} of []);", "_.c")); } @Test public void testForAwaitOfLoops_allSameModule() { assumeCrossModuleNames = false; testSame("async () => { for await (var i of [1, 2, 3]);}"); testSame("async () => { for await (var [a] of []);}"); testSame("async () => { for await (var {a: a} of {});}"); } @Test public void testForAwaitOfLoops_acrossModules() { // TODO(b/128938049): re-enable it once we support top-level await. assumeCrossModuleNames = false; testError( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("for await (var i of []);") .addChunk("i") .build()), RhinoErrorReporter.PARSE_ERROR); testError( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for await (var [ a, b] of []);") .addChunk("a;") .build()), RhinoErrorReporter.PARSE_ERROR); testError( srcs( JSChunkGraphBuilder.forUnordered() .addChunk(" for await (var {i: i, c: c} of []);") .addChunk("c") .build()), RhinoErrorReporter.PARSE_ERROR); } @Test public void testFunctionStatements() { test("function test(){}", "_.test=function (){}"); // Ignore block-scoped function declarations. testSame("if(1) function test(){}"); test("async function test() {}", "_.test = async function() {}"); test("function *test() {}", "_.test = function *() {}"); } @Test public void testFunctionStatements_allSameModule() { assumeCrossModuleNames = false; test("function f() {}", "var f = function() {}"); testSame("if (true) { function f() {} }"); } @Test public void testFunctionStatements_freeCallSemantics1() { disableCompareAsTree(); // This triggers free call. test( "function x(){this};var y=function(){var val=x()||{}}", "_.x=function(){this};_.y=function(){var val=(0,_.x)()||{}}"); test("function x(){this;x()}", "_.x=function(){this;(0,_.x)()}"); test("var a=function(){this};a()", "_.a=function(){this};(0,_.a)()"); // Always trigger free calls for variables assigned through destructuring. test("var {a: a} = {a: function() {}}; a();", "({a:_.a}={a:function(){}});(0,_.a)()"); test("var ns = {}; ns.a = function() {}; ns.a()", "_.ns={};_.ns.a=function(){};_.ns.a()"); } @Test public void testFunctionStatements_freeCallSemantics2() { // Cases where free call forcing through (0, foo)() is not necessary. test("var a=function(){};a()", "_.a=function(){};_.a()"); test("function a(){};a()", "_.a=function(){};;_.a()"); test("var a;a=function(){};a()", "_.a=function(){};_.a()"); // Test that calls to arrow functions are not forced to be free calls test("var a = () => {}; a();", "_.a = () => {}; _.a();"); test("var a = () => this; a();", "_.a = () => this; _.a();"); } @Test public void testFunctionStatements_freeCallSemantics3() { disableCompareAsTree(); // Ambiguous cases. test("var a=1;a=function(){};a()", "_.a=1;_.a=function(){};(0,_.a)()"); test("var b;var a=b;a()", "_.a=_.b;(0,_.a)()"); } @Test public void testFunctionStatements_defaultParameters() { test("var a = 1; function f(param = a) {}", "_.a = 1; _.f = function(param = _.a) {}"); } @Test public void testDeeperScopes() { test("var a = function(b){return b}", "_.a = function(b){return b}"); test("var a = function(b){var a; return a+b}", "_.a = function(b){var a; return a+b}"); test("var a = function(a,b){return a+b}", "_.a = function(a,b){return a+b}"); test( "var x=1,a = function(b){var a; return a+b+x}", "_.x=1;_.a = function(b){var a; return a+b+_.x}"); test( "var x=1,a = function(b){return function(){var a;return a+b+x}}", "_.x=1;_.a = function(b){return function(){var a; return a+b+_.x}}"); } @Test public void testTryCatch() { test("try{var a = 1}catch(e){throw e}", "try{_.a = 1}catch(e){throw e}"); } @Test public void testShadowInFunctionScope() { test("var _ = 1; (function () { _ = 2 })()", "_._ = 1; (function () { _._ = 2 })()"); test( "function foo() { var _ = {}; _.foo = foo; _.bar = 1; }", "_.foo = function () { var _$ = {}; _$.foo = _.foo; _$.bar = 1}"); test( "function foo() { var {key: _} = {}; _.foo = foo; _.bar = 1; }", "_.foo = function () { var {key: _$} = {}; _$.foo = _.foo; _$.bar = 1}"); test( """ function foo() { var _ = {}; _.foo = foo; _.bar = 1; (function() { var _ = 0;})() } """, """ _.foo = function () { var _$ = {}; _$.foo = _.foo; _$.bar = 1; (function() { var _$ = 0;})() } """); test( """ function foo() { var _ = {}; _.foo = foo; _.bar = 1; var _$ = 1; } """, """ _.foo = function () { var _$ = {}; _$.foo = _.foo; _$.bar = 1; var _$$ = 1; } """); test( """ function foo() { var _ = {}; _.foo = foo; _.bar = 1; var _$ = 1; (function() { _ = _$ })() } """, """ _.foo = function () { var _$ = {}; _$.foo = _.foo; _$.bar = 1; var _$$ = 1; (function() { _$ = _$$ })() } """); test( """ function foo() { var _ = {}; _.foo = foo; _.bar = 1; var _$ = 1, _$$ = 2 (function() { _ = _$ = _$$; var _$, _$$$ })() } """, """ _.foo = function () { var _$ = {}; _$.foo = _.foo; _$.bar = 1; var _$$ = 1, _$$$ = 2 (function() { _$ = _$$ = _$$$; var _$$, _$$$$ })() } """); test( "var a = 5; function foo(_) { return _; }", "_.a = 5; _.foo = function(_$) { return _$; }"); test( "var a = 5; function foo({key: _}) { return _; }", "_.a = 5; _.foo = function({key: _$}) { return _$; }"); test( "var a = 5; function foo([_]) { return _; }", "_.a = 5; _.foo = function([_$]) { return _$; }"); // We accept this unnecessary renaming as acceptable to simplify pattern // matching in the traversal. test("function foo() { var _$a = 1;}", "_.foo = function () { var _$a$ = 1;}"); } @Test public void testShadowInBlockScope() { test( "var foo = 1; if (true) { const _ = {}; _.foo = foo; _.bar = 1; }", "_.foo = 1; if (true) { const _$ = {}; _$.foo = _.foo; _$.bar = 1}"); test( "var foo = 1; if (true) { const {key: _} = {}; _.foo = foo; _.bar = 1; }", "_.foo = 1; if (true) { const {key: _$} = {}; _$.foo = _.foo; _$.bar = 1}"); test( "var foo = 1; if (true) { const _ = {}; _.foo = foo; _.bar = 1; const _$ = 1; }", "_.foo = 1; if (true) { const _$ = {}; _$.foo = _.foo; _$.bar = 1; const _$$ = 1; }"); test( "var foo = 1; if (true) { const [_] = [{}]; _.foo = foo; }", " _.foo = 1; if (true) { const [_$] = [{}]; _$.foo = _.foo; }"); } @Test public void testExterns() { test(externs("var document;"), srcs("document"), expected("document")); test( externs("var document;"), srcs("document.getElementsByTagName('test')"), expected("document.getElementsByTagName('test')")); test( externs("var document;"), srcs("document.getElementsByTagName('test')"), expected("document.getElementsByTagName('test')")); test( externs("var document;document.getElementsByTagName"), srcs("document.getElementsByTagName('test')"), expected("document.getElementsByTagName('test')")); test( externs("var document,navigator"), srcs("document.navigator;navigator"), expected("document.navigator;navigator")); test( externs("var iframes"), srcs("function test() { iframes.resize(); }"), expected("_.test = function() { iframes.resize(); }")); test(externs("var iframes"), srcs("var foo = iframes;"), expected("_.foo = iframes;")); test(externs("class A {}"), srcs("A"), expected("A")); // Special names. test( externs("var arguments, window, eval;"), srcs("arguments;window;eval;"), expected("arguments;window;eval;")); // Actually not an extern. test(externs(""), srcs("document"), expected("document")); // Javascript builtin objects testSame( """ Object;Function;Array;String;Boolean;Number;Math; Date;RegExp;JSON;Error;EvalError;ReferenceError; SyntaxError;TypeError;URIError; """); } @Test public void testSameVarDeclaredInExternsAndSource() { test( externs("/** @const */ var ns = {}; function f() {}"), srcs("/** @const */ var ns = ns || {};"), expected("/** @const */ ns = ns || {};")); test(externs("var x;"), srcs("var x = 1; x = 2;"), expected("x = 1; x = 2;")); test( externs("var x;"), srcs("function f() { var x; x = 1; }"), expected("_.f = function() { var x; x = 1; }")); test( externs("var x;"), srcs("function f() { x = 1; }"), expected("_.f = function() { x = 1; };")); test(externs("var x, y;"), srcs("var x = 1, y = 2;"), expected("x = 1; y = 2;")); test(externs("var x, y;"), srcs("var x, y = 2;"), expected("y = 2;")); test(externs("var x;"), srcs("var x = 1, y = 2;"), expected("x = 1; _.y = 2;")); test(externs("var x;"), srcs("var y = 2, x = 1;"), expected("_.y = 2; x = 1;")); test(externs("var x;"), srcs("var y, x = 1;"), expected("x = 1;")); test( externs("var foo;"), srcs("var foo = function(x) { if (x > 0) { var y = foo; } };"), expected("foo = function(x) { if (x > 0) { var y = foo; } };")); // The parameter x doesn't conflict with the x in the source test(externs("function f(x) {}"), srcs("var f = 1; var x = 2;"), expected("f = 1; _.x = 2;")); } @Test public void testSameVarDeclaredInExternsAndSource2() { assumeCrossModuleNames = false; test( srcs( JSChunkGraphBuilder.forUnordered() .addChunk( """ Foo = function() { this.b = ns; }; var f = function(a) { if (a instanceof Foo && a.b === ns) {} }, ns = {}, g = function(a) { var b = new Foo; }; """) .addChunk("f; g;") .build()), expected( """ var ns; Foo = function() { this.b = ns; }; _.f = function(a) { if (a instanceof Foo && a.b === ns) {} }; ns = {}; _.g = function(a) { var b = new Foo; }; """, "_.f; _.g;")); test( externs("var y;"), srcs("var x = 1, y = 2; function f() { return x + y; }"), expected("var x; x = 1; y = 2; var f = function() { return x + y; }")); } @Test public void testArrowFunctions() { test("const fn = () => 3;", "_.fn = () => 3;"); test("const PI = 3.14; const fn = () => PI;", "_.PI = 3.14; _.fn = () => _.PI"); test("let a = 3; const fn = () => a = 4;", "_.a = 3; _.fn = () => _.a = 4;"); test("const PI = 3.14; (() => PI)()", "_.PI = 3.14; (() => _.PI)();"); test("const PI = 3.14; (() => { return PI; })()", "_.PI = 3.14; (() => { return _.PI; })()"); } @Test public void testEnhancedObjectLiterals() { test("var a = 3; var obj = {[a]: a};", "_.a = 3; _.obj = {[_.a]: _.a};"); test( "var g = 3; var obj = {a() {}, b() { return g; }};", "_.g = 3; _.obj = {a() {}, b() { return _.g; }};"); test("var a = 1; var obj = {a}", "_.a = 1; _.obj = {a: _.a};"); } @Test public void testEs6Modules() { ignoreWarnings(LOAD_WARNING); // Test that this pass does nothing to ES6 modules. testSame("var a = 3; a; export default a;"); assumeCrossModuleNames = false; testSame( srcs( JSChunkGraphBuilder.forUnordered() .addChunk("var a = 3; export {a};") .addChunk("import {a} from './input0';") .build())); } @Test public void testEmptyDestructuring() { testSame("var {} = {};"); } }
googleapis/google-cloud-java
37,689
java-eventarc/proto-google-cloud-eventarc-v1/src/main/java/com/google/cloud/eventarc/v1/CreateChannelConnectionRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/eventarc/v1/eventarc.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.eventarc.v1; /** * * * <pre> * The request message for the CreateChannelConnection method. * </pre> * * Protobuf type {@code google.cloud.eventarc.v1.CreateChannelConnectionRequest} */ public final class CreateChannelConnectionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.eventarc.v1.CreateChannelConnectionRequest) CreateChannelConnectionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateChannelConnectionRequest.newBuilder() to construct. private CreateChannelConnectionRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateChannelConnectionRequest() { parent_ = ""; channelConnectionId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateChannelConnectionRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.eventarc.v1.EventarcProto .internal_static_google_cloud_eventarc_v1_CreateChannelConnectionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.eventarc.v1.EventarcProto .internal_static_google_cloud_eventarc_v1_CreateChannelConnectionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.class, com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </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 CHANNEL_CONNECTION_FIELD_NUMBER = 2; private com.google.cloud.eventarc.v1.ChannelConnection channelConnection_; /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the channelConnection field is set. */ @java.lang.Override public boolean hasChannelConnection() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The channelConnection. */ @java.lang.Override public com.google.cloud.eventarc.v1.ChannelConnection getChannelConnection() { return channelConnection_ == null ? com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance() : channelConnection_; } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.eventarc.v1.ChannelConnectionOrBuilder getChannelConnectionOrBuilder() { return channelConnection_ == null ? com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance() : channelConnection_; } public static final int CHANNEL_CONNECTION_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object channelConnectionId_ = ""; /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The channelConnectionId. */ @java.lang.Override public java.lang.String getChannelConnectionId() { java.lang.Object ref = channelConnectionId_; 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(); channelConnectionId_ = s; return s; } } /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for channelConnectionId. */ @java.lang.Override public com.google.protobuf.ByteString getChannelConnectionIdBytes() { java.lang.Object ref = channelConnectionId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); channelConnectionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getChannelConnection()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(channelConnectionId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, channelConnectionId_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getChannelConnection()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(channelConnectionId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, channelConnectionId_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.eventarc.v1.CreateChannelConnectionRequest)) { return super.equals(obj); } com.google.cloud.eventarc.v1.CreateChannelConnectionRequest other = (com.google.cloud.eventarc.v1.CreateChannelConnectionRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasChannelConnection() != other.hasChannelConnection()) return false; if (hasChannelConnection()) { if (!getChannelConnection().equals(other.getChannelConnection())) return false; } if (!getChannelConnectionId().equals(other.getChannelConnectionId())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (hasChannelConnection()) { hash = (37 * hash) + CHANNEL_CONNECTION_FIELD_NUMBER; hash = (53 * hash) + getChannelConnection().hashCode(); } hash = (37 * hash) + CHANNEL_CONNECTION_ID_FIELD_NUMBER; hash = (53 * hash) + getChannelConnectionId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.eventarc.v1.CreateChannelConnectionRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * The request message for the CreateChannelConnection method. * </pre> * * Protobuf type {@code google.cloud.eventarc.v1.CreateChannelConnectionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.eventarc.v1.CreateChannelConnectionRequest) com.google.cloud.eventarc.v1.CreateChannelConnectionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.eventarc.v1.EventarcProto .internal_static_google_cloud_eventarc_v1_CreateChannelConnectionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.eventarc.v1.EventarcProto .internal_static_google_cloud_eventarc_v1_CreateChannelConnectionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.class, com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.Builder.class); } // Construct using com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getChannelConnectionFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; channelConnection_ = null; if (channelConnectionBuilder_ != null) { channelConnectionBuilder_.dispose(); channelConnectionBuilder_ = null; } channelConnectionId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.eventarc.v1.EventarcProto .internal_static_google_cloud_eventarc_v1_CreateChannelConnectionRequest_descriptor; } @java.lang.Override public com.google.cloud.eventarc.v1.CreateChannelConnectionRequest getDefaultInstanceForType() { return com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.eventarc.v1.CreateChannelConnectionRequest build() { com.google.cloud.eventarc.v1.CreateChannelConnectionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.eventarc.v1.CreateChannelConnectionRequest buildPartial() { com.google.cloud.eventarc.v1.CreateChannelConnectionRequest result = new com.google.cloud.eventarc.v1.CreateChannelConnectionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.eventarc.v1.CreateChannelConnectionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.channelConnection_ = channelConnectionBuilder_ == null ? channelConnection_ : channelConnectionBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.channelConnectionId_ = channelConnectionId_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.eventarc.v1.CreateChannelConnectionRequest) { return mergeFrom((com.google.cloud.eventarc.v1.CreateChannelConnectionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.eventarc.v1.CreateChannelConnectionRequest other) { if (other == com.google.cloud.eventarc.v1.CreateChannelConnectionRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasChannelConnection()) { mergeChannelConnection(other.getChannelConnection()); } if (!other.getChannelConnectionId().isEmpty()) { channelConnectionId_ = other.channelConnectionId_; bitField0_ |= 0x00000004; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage( getChannelConnectionFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { channelConnectionId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent collection in which to add this channel connection. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.cloud.eventarc.v1.ChannelConnection channelConnection_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.eventarc.v1.ChannelConnection, com.google.cloud.eventarc.v1.ChannelConnection.Builder, com.google.cloud.eventarc.v1.ChannelConnectionOrBuilder> channelConnectionBuilder_; /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the channelConnection field is set. */ public boolean hasChannelConnection() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The channelConnection. */ public com.google.cloud.eventarc.v1.ChannelConnection getChannelConnection() { if (channelConnectionBuilder_ == null) { return channelConnection_ == null ? com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance() : channelConnection_; } else { return channelConnectionBuilder_.getMessage(); } } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setChannelConnection(com.google.cloud.eventarc.v1.ChannelConnection value) { if (channelConnectionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } channelConnection_ = value; } else { channelConnectionBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setChannelConnection( com.google.cloud.eventarc.v1.ChannelConnection.Builder builderForValue) { if (channelConnectionBuilder_ == null) { channelConnection_ = builderForValue.build(); } else { channelConnectionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeChannelConnection(com.google.cloud.eventarc.v1.ChannelConnection value) { if (channelConnectionBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && channelConnection_ != null && channelConnection_ != com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance()) { getChannelConnectionBuilder().mergeFrom(value); } else { channelConnection_ = value; } } else { channelConnectionBuilder_.mergeFrom(value); } if (channelConnection_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearChannelConnection() { bitField0_ = (bitField0_ & ~0x00000002); channelConnection_ = null; if (channelConnectionBuilder_ != null) { channelConnectionBuilder_.dispose(); channelConnectionBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.eventarc.v1.ChannelConnection.Builder getChannelConnectionBuilder() { bitField0_ |= 0x00000002; onChanged(); return getChannelConnectionFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.eventarc.v1.ChannelConnectionOrBuilder getChannelConnectionOrBuilder() { if (channelConnectionBuilder_ != null) { return channelConnectionBuilder_.getMessageOrBuilder(); } else { return channelConnection_ == null ? com.google.cloud.eventarc.v1.ChannelConnection.getDefaultInstance() : channelConnection_; } } /** * * * <pre> * Required. Channel connection to create. * </pre> * * <code> * .google.cloud.eventarc.v1.ChannelConnection channel_connection = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.eventarc.v1.ChannelConnection, com.google.cloud.eventarc.v1.ChannelConnection.Builder, com.google.cloud.eventarc.v1.ChannelConnectionOrBuilder> getChannelConnectionFieldBuilder() { if (channelConnectionBuilder_ == null) { channelConnectionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.eventarc.v1.ChannelConnection, com.google.cloud.eventarc.v1.ChannelConnection.Builder, com.google.cloud.eventarc.v1.ChannelConnectionOrBuilder>( getChannelConnection(), getParentForChildren(), isClean()); channelConnection_ = null; } return channelConnectionBuilder_; } private java.lang.Object channelConnectionId_ = ""; /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The channelConnectionId. */ public java.lang.String getChannelConnectionId() { java.lang.Object ref = channelConnectionId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); channelConnectionId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for channelConnectionId. */ public com.google.protobuf.ByteString getChannelConnectionIdBytes() { java.lang.Object ref = channelConnectionId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); channelConnectionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The channelConnectionId to set. * @return This builder for chaining. */ public Builder setChannelConnectionId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } channelConnectionId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearChannelConnectionId() { channelConnectionId_ = getDefaultInstance().getChannelConnectionId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Required. The user-provided ID to be assigned to the channel connection. * </pre> * * <code>string channel_connection_id = 3 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for channelConnectionId to set. * @return This builder for chaining. */ public Builder setChannelConnectionIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); channelConnectionId_ = 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.eventarc.v1.CreateChannelConnectionRequest) } // @@protoc_insertion_point(class_scope:google.cloud.eventarc.v1.CreateChannelConnectionRequest) private static final com.google.cloud.eventarc.v1.CreateChannelConnectionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.eventarc.v1.CreateChannelConnectionRequest(); } public static com.google.cloud.eventarc.v1.CreateChannelConnectionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateChannelConnectionRequest> PARSER = new com.google.protobuf.AbstractParser<CreateChannelConnectionRequest>() { @java.lang.Override public CreateChannelConnectionRequest 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<CreateChannelConnectionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateChannelConnectionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.eventarc.v1.CreateChannelConnectionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/kudu
37,897
java/kudu-client/src/test/java/org/apache/kudu/client/TestKuduSession.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.kudu.client; import static org.apache.kudu.test.ClientTestUtil.countRowsInScan; import static org.apache.kudu.test.ClientTestUtil.createBasicSchemaInsert; import static org.apache.kudu.test.ClientTestUtil.createSchemaWithImmutableColumns; import static org.apache.kudu.test.ClientTestUtil.getBasicCreateTableOptions; import static org.apache.kudu.test.ClientTestUtil.getBasicTableOptionsWithNonCoveredRange; import static org.apache.kudu.test.ClientTestUtil.scanTableToStrings; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import com.google.common.collect.ImmutableList; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.apache.kudu.ColumnSchema; import org.apache.kudu.Schema; import org.apache.kudu.Type; import org.apache.kudu.test.ClientTestUtil; import org.apache.kudu.test.KuduTestHarness; public class TestKuduSession { private static final String tableName = "TestKuduSession"; private static final Schema basicSchema = ClientTestUtil.getBasicSchema(); private KuduClient client; private AsyncKuduClient asyncClient; @Rule public KuduTestHarness harness = new KuduTestHarness(); @Before public void setUp() { client = harness.getClient(); asyncClient = harness.getAsyncClient(); } @Test(timeout = 100000) public void testBasicOps() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); for (int i = 0; i < 10; i++) { session.apply(createInsert(table, i)); } assertEquals(10, countRowsInScan(client.newScannerBuilder(table).build())); OperationResponse resp = session.apply(createInsert(table, 0)); assertTrue(resp.hasRowError()); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); for (int i = 10; i < 20; i++) { session.apply(createInsert(table, i)); } session.flush(); assertEquals(20, countRowsInScan(client.newScannerBuilder(table).build())); } @Test(timeout = 100000) public void testIgnoreAllDuplicateRows() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setIgnoreAllDuplicateRows(true); for (int i = 0; i < 10; i++) { session.apply(createInsert(table, i)); } // Test all of the various flush modes to be sure we correctly handle errors in // individual operations and batches. for (SessionConfiguration.FlushMode mode : SessionConfiguration.FlushMode.values()) { session.setFlushMode(mode); for (int i = 0; i < 10; i++) { OperationResponse resp = session.apply(createInsert(table, i)); if (mode == SessionConfiguration.FlushMode.AUTO_FLUSH_SYNC) { assertFalse(resp.hasRowError()); } } if (mode == SessionConfiguration.FlushMode.MANUAL_FLUSH) { List<OperationResponse> responses = session.flush(); for (OperationResponse resp : responses) { assertFalse(resp.hasRowError()); } } else if (mode == SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND) { while (session.hasPendingOperations()) { Thread.sleep(100); } assertEquals(0, session.countPendingErrors()); } } } @Test(timeout = 100000) public void testIgnoreAllNotFoundRows() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setIgnoreAllNotFoundRows(true); // Test all of the various flush modes to be sure we correctly handle errors in // individual operations and batches. for (SessionConfiguration.FlushMode mode : SessionConfiguration.FlushMode.values()) { session.setFlushMode(mode); for (int i = 0; i < 10; i++) { session.apply(createDelete(table, i)); OperationResponse resp = session.apply(createInsert(table, i)); if (mode == SessionConfiguration.FlushMode.AUTO_FLUSH_SYNC) { assertFalse(resp.hasRowError()); } } if (mode == SessionConfiguration.FlushMode.MANUAL_FLUSH) { List<OperationResponse> responses = session.flush(); for (OperationResponse resp : responses) { assertFalse(resp.hasRowError()); } } else if (mode == SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND) { while (session.hasPendingOperations()) { Thread.sleep(100); } assertEquals(0, session.countPendingErrors()); } } } @Test(timeout = 100000) public void testBatchWithSameRow() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); // Insert 25 rows, one per batch, along with 50 updates for each, and a delete at the end, // while also clearing the cache between each batch half the time. The delete is added here // so that a misplaced update would fail if it happens later than its delete. for (int i = 0; i < 25; i++) { session.apply(createInsert(table, i)); for (int j = 0; j < 50; j++) { Update update = table.newUpdate(); PartialRow row = update.getRow(); row.addInt(basicSchema.getColumnByIndex(0).getName(), i); row.addInt(basicSchema.getColumnByIndex(1).getName(), 1000); session.apply(update); } Delete del = table.newDelete(); PartialRow row = del.getRow(); row.addInt(basicSchema.getColumnByIndex(0).getName(), i); session.apply(del); session.flush(); if (i % 2 == 0) { asyncClient.emptyTabletsCacheForTable(table.getTableId()); } } assertEquals(0, countRowsInScan(client.newScannerBuilder(table).build())); } @Test(timeout = 100000) public void testDeleteWithFullRow() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); List<PartialRow> rows = new ArrayList<>(); for (int i = 0; i < 25; i++) { Insert insert = createInsert(table, i); rows.add(insert.getRow()); session.apply(insert); } session.flush(); for (PartialRow row : rows) { Operation del; if (row.getInt(0) % 2 == 0) { del = table.newDelete(); } else { del = table.newDeleteIgnore(); } del.setRow(row); session.apply(del); } session.flush(); assertEquals(0, session.countPendingErrors()); assertEquals(0, countRowsInScan(client.newScannerBuilder(table).build())); } /** Regression test for KUDU-3198. Delete with full row from a 64-column table. */ @Test(timeout = 100000) public void testDeleteWithFullRowFrom64ColumnTable() throws Exception { ArrayList<ColumnSchema> columns = new ArrayList<>(64); columns.add(new ColumnSchema.ColumnSchemaBuilder("key", Type.INT32).key(true).build()); for (int i = 1; i < 64; i++) { columns.add(new ColumnSchema.ColumnSchemaBuilder("column_" + i, Type.STRING) .nullable(true) .build()); } Schema schema = new Schema(columns); KuduTable table = client.createTable(tableName, schema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); // Insert 25 rows and then delete them. List<PartialRow> rows = new ArrayList<>(); for (int i = 0; i < 25; i++) { Insert insert = table.newInsert(); PartialRow row = insert.getRow(); row.addInt(0, 1); for (int j = 1; j < 64; j++) { if (j % 2 == 0) { row.setNull(j); } else { row.addString(j, "val_" + j); } } rows.add(row); session.apply(insert); } session.flush(); for (PartialRow row : rows) { Operation del; if (row.getInt(0) % 2 == 0) { del = table.newDelete(); } else { del = table.newDeleteIgnore(); } del.setRow(row); session.apply(del); } session.flush(); assertEquals(0, session.countPendingErrors()); assertEquals(0, countRowsInScan(client.newScannerBuilder(table).build())); } /** * Regression test for KUDU-1402. Calls to session.flush() should return an empty list * instead of null. * @throws Exception */ @Test(timeout = 100000) public void testEmptyFlush() throws Exception { KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); List<OperationResponse> result = session.flush(); assertNotNull(result); assertTrue(result.isEmpty()); } /** * Regression test for KUDU-1226. Calls to session.flush() concurrent with AUTO_FLUSH_BACKGROUND * can end up giving ConvertBatchToListOfResponsesCB a list with nulls if a tablet was already * flushed. Only happens with multiple tablets. */ @Test(timeout = 100000) public void testConcurrentFlushes() throws Exception { CreateTableOptions builder = getBasicCreateTableOptions(); int numTablets = 4; int numRowsPerTablet = 100; // Create a 4 tablets table split on 1000, 2000, and 3000. for (int i = 1; i < numTablets; i++) { PartialRow split = basicSchema.newPartialRow(); split.addInt(0, i * numRowsPerTablet); builder.addSplitRow(split); } KuduTable table = client.createTable(tableName, basicSchema, builder); // Configure the session to background flush as often as it can (every 1ms). KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND); session.setFlushInterval(1); // Fill each tablet in parallel 1 by 1 then flush. Without the fix this would quickly get an // NPE. for (int i = 0; i < numRowsPerTablet; i++) { for (int j = 0; j < numTablets; j++) { session.apply(createInsert(table, i + (numRowsPerTablet * j))); } session.flush(); } } @Test(timeout = 10000) public void testOverWritingValues() throws Exception { final KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); final KuduSession session = client.newSession(); Insert insert = createInsert(table, 0); PartialRow row = insert.getRow(); // Overwrite all the normal columns. int magicNumber = 9999; row.addInt(1, magicNumber); row.addInt(2, magicNumber); row.addBoolean(4, false); // Spam the string column since it's backed by an array. for (int i = 0; i <= magicNumber; i++) { row.addString(3, i + ""); } // We're supposed to keep a constant size. assertEquals(5, row.getVarLengthData().size()); session.apply(insert); KuduScanner scanner = client.newScannerBuilder(table).build(); RowResult rr = scanner.nextRows().next(); assertEquals(magicNumber, rr.getInt(1)); assertEquals(magicNumber, rr.getInt(2)); assertEquals(magicNumber + "", rr.getString(3)); assertEquals(false, rr.getBoolean(4)); // Test setting a value post-apply. try { row.addInt(1, 0); fail("Row should be frozen and throw"); } catch (IllegalStateException ex) { // Ok. } } private void doVerifyMetrics(KuduSession session, long successfulInserts, long insertIgnoreErrors, long successfulUpserts, long upsertIgnoreErrors, long successfulUpdates, long updateIgnoreErrors, long successfulDeletes, long deleteIgnoreErrors) { ResourceMetrics metrics = session.getWriteOpMetrics(); assertEquals(successfulInserts, metrics.getMetric("successful_inserts")); assertEquals(insertIgnoreErrors, metrics.getMetric("insert_ignore_errors")); assertEquals(successfulUpserts, metrics.getMetric("successful_upserts")); assertEquals(upsertIgnoreErrors, metrics.getMetric("upsert_ignore_errors")); assertEquals(successfulUpdates, metrics.getMetric("successful_updates")); assertEquals(updateIgnoreErrors, metrics.getMetric("update_ignore_errors")); assertEquals(successfulDeletes, metrics.getMetric("successful_deletes")); assertEquals(deleteIgnoreErrors, metrics.getMetric("delete_ignore_errors")); } @Test(timeout = 10000) public void testUpsert() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Test an Upsert that acts as an Insert. assertFalse(session.apply(createUpsert(table, 1, 1, false)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals( "INT32 key=1, INT32 column1_i=1, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); doVerifyMetrics(session, 0, 0, 1, 0, 0, 0, 0, 0); // Test an Upsert that acts as an Update. assertFalse(session.apply(createUpsert(table, 1, 2, false)).hasRowError()); rowStrings = scanTableToStrings(table); assertEquals( "INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); doVerifyMetrics(session, 0, 0, 2, 0, 0, 0, 0, 0); } @Test(timeout = 10000) public void testInsertIgnoreAfterInsertHasNoRowError() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); session.apply(createInsert(table, 1)); session.apply(createUpsert(table, 1, 1, false)); session.apply(createInsertIgnore(table, 1)); List<OperationResponse> results = session.flush(); doVerifyMetrics(session, 1, 1, 1, 0, 0, 0, 0, 0); for (OperationResponse result : results) { assertFalse(result.toString(), result.hasRowError()); } List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals( "INT32 key=1, INT32 column1_i=1, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); } @Test(timeout = 10000) public void testInsertAfterInsertIgnoreHasRowError() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); session.apply(createInsertIgnore(table, 1)); session.apply(createInsert(table, 1)); List<OperationResponse> results = session.flush(); doVerifyMetrics(session, 1, 0, 0, 0, 0, 0, 0, 0); assertFalse(results.get(0).toString(), results.get(0).hasRowError()); assertTrue(results.get(1).toString(), results.get(1).hasRowError()); assertTrue(results.get(1).getRowError().getErrorStatus().isAlreadyPresent()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals( "INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); } @Test(timeout = 10000) public void testInsertIgnore() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Test insert ignore implements normal insert. assertFalse(session.apply(createInsertIgnore(table, 1)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals( "INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); doVerifyMetrics(session, 1, 0, 0, 0, 0, 0, 0, 0); // Test insert ignore does not return a row error. assertFalse(session.apply(createInsertIgnore(table, 1)).hasRowError()); rowStrings = scanTableToStrings(table); assertEquals( "INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); doVerifyMetrics(session, 1, 1, 0, 0, 0, 0, 0, 0); } @Test(timeout = 10000) public void testUpdateIgnore() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Test update ignore does not return a row error. assertFalse(session.apply(createUpdateIgnore(table, 1, 1, false)).hasRowError()); assertEquals(0, scanTableToStrings(table).size()); doVerifyMetrics(session, 0, 0, 0, 0, 0, 1, 0, 0); assertFalse(session.apply(createInsert(table, 1)).hasRowError()); assertEquals(1, scanTableToStrings(table).size()); doVerifyMetrics(session, 1, 0, 0, 0, 0, 1, 0, 0); // Test update ignore implements normal update. assertFalse(session.apply(createUpdateIgnore(table, 1, 2, false)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals( "INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true", rowStrings.get(0)); doVerifyMetrics(session, 1, 0, 0, 0, 1, 1, 0, 0); } @Test(timeout = 10000) public void testDeleteIgnore() throws Exception { KuduTable table = client.createTable(tableName, basicSchema, getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Test delete ignore does not return a row error. assertFalse(session.apply(createDeleteIgnore(table, 1)).hasRowError()); doVerifyMetrics(session, 0, 0, 0, 0, 0, 0, 0, 1); assertFalse(session.apply(createInsert(table, 1)).hasRowError()); assertEquals(1, scanTableToStrings(table).size()); doVerifyMetrics(session, 1, 0, 0, 0, 0, 0, 0, 1); // Test delete ignore implements normal delete. assertFalse(session.apply(createDeleteIgnore(table, 1)).hasRowError()); assertEquals(0, scanTableToStrings(table).size()); doVerifyMetrics(session, 1, 0, 0, 0, 0, 0, 1, 1); } @Test(timeout = 10000) public void testInsertManualFlushNonCoveredRange() throws Exception { CreateTableOptions createOptions = getBasicTableOptionsWithNonCoveredRange(); createOptions.setNumReplicas(1); client.createTable(tableName, basicSchema, createOptions); KuduTable table = client.openTable(tableName); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); // Insert in reverse sorted order so that more table location lookups occur // (the extra results in table location lookups always occur past the inserted key). List<Integer> nonCoveredKeys = ImmutableList.of(350, 300, 199, 150, 100, -1, -50); for (int key : nonCoveredKeys) { assertNull(session.apply(createBasicSchemaInsert(table, key))); } List<OperationResponse> results = session.flush(); assertEquals(nonCoveredKeys.size(), results.size()); for (OperationResponse result : results) { assertTrue(result.hasRowError()); assertTrue(result.getRowError().getErrorStatus().isNotFound()); } // Insert a batch of some valid and some invalid. for (int key = 90; key < 110; key++) { session.apply(createBasicSchemaInsert(table, key)); } results = session.flush(); int failures = 0; for (OperationResponse result : results) { if (result.hasRowError()) { failures++; assertTrue(result.getRowError().getErrorStatus().isNotFound()); } } assertEquals(10, failures); } @Test(timeout = 10000) public void testInsertManualFlushResponseOrder() throws Exception { CreateTableOptions createOptions = getBasicTableOptionsWithNonCoveredRange(); createOptions.setNumReplicas(1); client.createTable(tableName, basicSchema, createOptions); KuduTable table = client.openTable(tableName); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); // Insert a batch of some valid and some invalid. for (int i = 0; i < 10; i++) { assertNull(session.apply(createBasicSchemaInsert(table, 100 + i * 10))); assertNull(session.apply(createBasicSchemaInsert(table, 200 + i * 10))); } List<OperationResponse> results = session.flush(); assertEquals(20, results.size()); for (int i = 0; i < 20; i++) { OperationResponse result = results.get(i); if (i % 2 == 0) { assertTrue(result.hasRowError()); assertTrue(result.getRowError().getErrorStatus().isNotFound()); } else { assertFalse(result.hasRowError()); } } } @Test(timeout = 10000) public void testNonCoveredRangeException() throws Exception { CreateTableOptions createOptions = getBasicTableOptionsWithNonCoveredRange(); createOptions.setNumReplicas(1); client.createTable(tableName, basicSchema, createOptions); KuduTable table = client.openTable(tableName); Insert insert = createInsert(table, 150); //AUTO_FLUSH_SYNC case KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_SYNC); OperationResponse apply = session.apply(insert); assertTrue(apply.hasRowError()); System.err.println(apply.getRowError().getErrorStatus().getMessage()); assertTrue(apply.getRowError().getErrorStatus().getMessage().contains( "does not exist in table: TestKuduSession")); //AUTO_FLUSH_BACKGROUND case session.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND); assertEquals(null, session.apply(insert)); List<OperationResponse> autoFlushResult = session.flush(); assertEquals(1, autoFlushResult.size()); OperationResponse responseAuto = autoFlushResult.get(0); assertTrue(responseAuto.hasRowError()); assertTrue(responseAuto.getRowError().getErrorStatus().getMessage().contains( "does not exist in table: TestKuduSession")); //MANUAL_FLUSH case session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH); assertEquals(null, session.apply(insert)); List<OperationResponse> manualFlushResult = session.flush(); assertEquals(1, manualFlushResult.size()); OperationResponse responseManual = manualFlushResult.get(0); assertTrue(responseManual.hasRowError()); assertTrue(responseManual.getRowError().getErrorStatus().getMessage().contains( "does not exist in table: TestKuduSession")); } @Test(timeout = 10000) public void testInsertAutoFlushSyncNonCoveredRange() throws Exception { CreateTableOptions createOptions = getBasicTableOptionsWithNonCoveredRange(); createOptions.setNumReplicas(1); client.createTable(tableName, basicSchema, createOptions); KuduTable table = client.openTable(tableName); KuduSession session = client.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_SYNC); List<Integer> nonCoveredKeys = ImmutableList.of(350, 300, 199, 150, 100, -1, -50); for (int key : nonCoveredKeys) { OperationResponse response = session.apply(createBasicSchemaInsert(table, key)); assertTrue(response.hasRowError()); assertTrue(response.getRowError().getErrorStatus().isNotFound()); } } @Test(timeout = 10000) public void testInsertAutoFlushBackgroundNonCoveredRange() throws Exception { CreateTableOptions createOptions = getBasicTableOptionsWithNonCoveredRange(); createOptions.setNumReplicas(1); client.createTable(tableName, basicSchema, createOptions); KuduTable table = client.openTable(tableName); AsyncKuduSession session = asyncClient.newSession(); session.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND); List<Integer> nonCoveredKeys = ImmutableList.of(350, 300, 199, 150, 100, -1, -50); for (int key : nonCoveredKeys) { OperationResponse result = session.apply(createBasicSchemaInsert(table, key)).join(5000); assertTrue(result.hasRowError()); assertTrue(result.getRowError().getErrorStatus().isNotFound()); } RowErrorsAndOverflowStatus errors = session.getPendingErrors(); assertEquals(nonCoveredKeys.size(), errors.getRowErrors().length); for (RowError error : errors.getRowErrors()) { assertTrue(error.getErrorStatus().isNotFound()); } // Insert a batch of some valid and some invalid. for (int key = 90; key < 110; key++) { session.apply(createBasicSchemaInsert(table, key)); } session.flush().join(5000); errors = session.getPendingErrors(); assertEquals(10, errors.getRowErrors().length); for (RowError error : errors.getRowErrors()) { assertTrue(error.getErrorStatus().isNotFound()); } } @Test(timeout = 10000) public void testUpdateOnTableWithImmutableColumn() throws Exception { // Create a table with an immutable column. KuduTable table = client.createTable( tableName, createSchemaWithImmutableColumns(), getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Insert some data and verify it. assertFalse(session.apply(createInsertOnTableWithImmutableColumn(table, 1)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals("INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true, INT32 column5_i=6", rowStrings.get(0)); // successfulInserts++ doVerifyMetrics(session, 1, 0, 0, 0, 0, 0, 0, 0); // Test an Update can update row without immutable column set. final String expectRow = "INT32 key=1, INT32 column1_i=3, INT32 column2_i=3, " + "STRING column3_s=NULL, BOOL column4_b=true, INT32 column5_i=6"; assertFalse(session.apply(createUpdateOnTableWithImmutableColumn( table, 1, false)).hasRowError()); rowStrings = scanTableToStrings(table); assertEquals(expectRow, rowStrings.get(0)); // successfulUpdates++ doVerifyMetrics(session, 1, 0, 0, 0, 1, 0, 0, 0); // Test an Update results in an error when attempting to update row having at least // one column with the immutable attribute set. OperationResponse resp = session.apply(createUpdateOnTableWithImmutableColumn( table, 1, true)); assertTrue(resp.hasRowError()); assertTrue(resp.getRowError().getErrorStatus().isImmutable()); Assert.assertThat(resp.getRowError().getErrorStatus().toString(), CoreMatchers.containsString("Immutable: UPDATE not allowed for " + "immutable column: column5_i INT32 NULLABLE IMMUTABLE")); // nothing changed rowStrings = scanTableToStrings(table); assertEquals(expectRow, rowStrings.get(0)); doVerifyMetrics(session, 1, 0, 0, 0, 1, 0, 0, 0); } @Test(timeout = 10000) public void testUpdateIgnoreOnTableWithImmutableColumn() throws Exception { // Create a table with an immutable column. KuduTable table = client.createTable( tableName, createSchemaWithImmutableColumns(), getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Insert some data and verify it. assertFalse(session.apply(createInsertOnTableWithImmutableColumn(table, 1)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals("INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=a string, BOOL column4_b=true, INT32 column5_i=6", rowStrings.get(0)); // successfulInserts++ doVerifyMetrics(session, 1, 0, 0, 0, 0, 0, 0, 0); final String expectRow = "INT32 key=1, INT32 column1_i=3, INT32 column2_i=3, " + "STRING column3_s=NULL, BOOL column4_b=true, INT32 column5_i=6"; // Test an UpdateIgnore can update a row without changing the immutable column cell, // the error of updating the immutable column will be ignored. assertFalse(session.apply(createUpdateIgnoreOnTableWithImmutableColumn( table, 1, true)).hasRowError()); rowStrings = scanTableToStrings(table); assertEquals(expectRow, rowStrings.get(0)); // successfulUpdates++, updateIgnoreErrors++ doVerifyMetrics(session, 1, 0, 0, 0, 1, 1, 0, 0); // Test an UpdateIgnore only on immutable column. Note that this will result in // a 'Invalid argument: No fields updated' error. OperationResponse resp = session.apply(createUpdateIgnoreOnTableWithImmutableColumn( table, 1, false)); assertTrue(resp.hasRowError()); assertTrue(resp.getRowError().getErrorStatus().isInvalidArgument()); Assert.assertThat(resp.getRowError().getErrorStatus().toString(), CoreMatchers.containsString("Invalid argument: No fields updated, " + "key is: (int32 key=<redacted>)")); // nothing changed rowStrings = scanTableToStrings(table); assertEquals(expectRow, rowStrings.get(0)); doVerifyMetrics(session, 1, 0, 0, 0, 1, 1, 0, 0); } @Test(timeout = 10000) public void testUpsertIgnoreOnTableWithImmutableColumn() throws Exception { // Create a table with an immutable column. KuduTable table = client.createTable( tableName, createSchemaWithImmutableColumns(), getBasicCreateTableOptions()); KuduSession session = client.newSession(); // Insert some data and verify it. assertFalse(session.apply(createUpsertIgnoreOnTableWithImmutableColumn( table, 1, 2, true)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals("INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=NULL, BOOL column4_b=true, INT32 column5_i=4", rowStrings.get(0)); // successfulUpserts++ doVerifyMetrics(session, 0, 0, 1, 0, 0, 0, 0, 0); // Test an UpsertIgnore can update row without immutable column set. assertFalse(session.apply(createUpsertIgnoreOnTableWithImmutableColumn( table, 1, 3, false)).hasRowError()); rowStrings = scanTableToStrings(table); assertEquals("INT32 key=1, INT32 column1_i=3, INT32 column2_i=3, " + "STRING column3_s=NULL, BOOL column4_b=true, INT32 column5_i=4", rowStrings.get(0)); // successfulUpserts++ doVerifyMetrics(session, 0, 0, 2, 0, 0, 0, 0, 0); // Test an UpsertIgnore can update row with immutable column set. assertFalse(session.apply(createUpsertIgnoreOnTableWithImmutableColumn( table, 1, 4, true)).hasRowError()); rowStrings = scanTableToStrings(table); assertEquals("INT32 key=1, INT32 column1_i=4, INT32 column2_i=3, " + "STRING column3_s=NULL, BOOL column4_b=true, INT32 column5_i=4", rowStrings.get(0)); // successfulUpserts++, upsertIgnoreErrors++ doVerifyMetrics(session, 0, 0, 3, 1, 0, 0, 0, 0); } @Test(timeout = 10000) public void testUpsertOnTableWithImmutableColumn() throws Exception { // Create a table with an immutable column. KuduTable table = client.createTable( tableName, createSchemaWithImmutableColumns(), getBasicCreateTableOptions()); KuduSession session = client.newSession(); final String expectRow = "INT32 key=1, INT32 column1_i=2, INT32 column2_i=3, " + "STRING column3_s=NULL, BOOL column4_b=true, INT32 column5_i=4"; // Insert some data and verify it. assertFalse(session.apply(createUpsertOnTableWithImmutableColumn( table, 1, 2, true)).hasRowError()); List<String> rowStrings = scanTableToStrings(table); assertEquals(1, rowStrings.size()); assertEquals(expectRow, rowStrings.get(0)); // successfulUpserts++ doVerifyMetrics(session, 0, 0, 1, 0, 0, 0, 0, 0); // Test an Upsert attemp to update an immutable column, which will result an error. OperationResponse resp = session.apply(createUpsertOnTableWithImmutableColumn( table, 1, 3, true)); assertTrue(resp.hasRowError()); assertTrue(resp.getRowError().getErrorStatus().isImmutable()); Assert.assertThat(resp.getRowError().getErrorStatus().toString(), CoreMatchers.containsString("Immutable: UPDATE not allowed for " + "immutable column: column5_i INT32 NULLABLE IMMUTABLE")); // nothing changed rowStrings = scanTableToStrings(table); assertEquals(expectRow, rowStrings.get(0)); doVerifyMetrics(session, 0, 0, 1, 0, 0, 0, 0, 0); } private Insert createInsert(KuduTable table, int key) { return createBasicSchemaInsert(table, key); } private Insert createInsertOnTableWithImmutableColumn(KuduTable table, int key) { Insert insert = createBasicSchemaInsert(table, key); insert.getRow().addInt(5, 6); return insert; } private Update createUpdateOnTableWithImmutableColumn(KuduTable table, int key, boolean updateImmutableColumn) { Update update = table.newUpdate(); populateUpdateRow(update.getRow(), key, key * 3, true); if (updateImmutableColumn) { update.getRow().addInt(5, 6); } return update; } private UpdateIgnore createUpdateIgnoreOnTableWithImmutableColumn( KuduTable table, int key, boolean updateNonImmutableColumns) { UpdateIgnore updateIgnore = table.newUpdateIgnore(); if (updateNonImmutableColumns) { populateUpdateRow(updateIgnore.getRow(), key, key * 3, true); } else { updateIgnore.getRow().addInt(0, key); } updateIgnore.getRow().addInt(5, 6); return updateIgnore; } private UpsertIgnore createUpsertIgnoreOnTableWithImmutableColumn( KuduTable table, int key, int times, boolean updateImmutableColumn) { UpsertIgnore upsertIgnore = table.newUpsertIgnore(); populateUpdateRow(upsertIgnore.getRow(), key, key * times, true); if (updateImmutableColumn) { upsertIgnore.getRow().addInt(5, key * times * 2); } return upsertIgnore; } private Upsert createUpsertOnTableWithImmutableColumn( KuduTable table, int key, int times, boolean updateImmutableColumn) { Upsert upsert = table.newUpsert(); populateUpdateRow(upsert.getRow(), key, key * times, true); if (updateImmutableColumn) { upsert.getRow().addInt(5, key * times * 2); } return upsert; } private Upsert createUpsert(KuduTable table, int key, int secondVal, boolean hasNull) { Upsert upsert = table.newUpsert(); populateUpdateRow(upsert.getRow(), key, secondVal, hasNull); return upsert; } private UpdateIgnore createUpdateIgnore(KuduTable table, int key, int secondVal, boolean hasNull) { UpdateIgnore updateIgnore = table.newUpdateIgnore(); populateUpdateRow(updateIgnore.getRow(), key, secondVal, hasNull); return updateIgnore; } private void populateUpdateRow(PartialRow row, int key, int secondVal, boolean hasNull) { row.addInt(0, key); row.addInt(1, secondVal); row.addInt(2, 3); if (hasNull) { row.setNull(3); } else { row.addString(3, "a string"); } row.addBoolean(4, true); } private Delete createDelete(KuduTable table, int key) { Delete delete = table.newDelete(); PartialRow row = delete.getRow(); row.addInt(0, key); return delete; } private DeleteIgnore createDeleteIgnore(KuduTable table, int key) { DeleteIgnore deleteIgnore = table.newDeleteIgnore(); PartialRow row = deleteIgnore.getRow(); row.addInt(0, key); return deleteIgnore; } protected InsertIgnore createInsertIgnore(KuduTable table, int key) { InsertIgnore insertIgnore = table.newInsertIgnore(); PartialRow row = insertIgnore.getRow(); row.addInt(0, key); row.addInt(1, 2); row.addInt(2, 3); row.addString(3, "a string"); row.addBoolean(4, true); return insertIgnore; } }
googleapis/google-cloud-java
37,690
java-beyondcorp-appconnections/google-cloud-beyondcorp-appconnections/src/test/java/com/google/cloud/beyondcorp/appconnections/v1/AppConnectionsServiceClientTest.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.beyondcorp.appconnections.v1; import static com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceClient.ListAppConnectionsPagedResponse; import static com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceClient.ListLocationsPagedResponse; import static com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceClient.ResolveAppConnectionsPagedResponse; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.api.gax.grpc.testing.MockGrpcService; import com.google.api.gax.grpc.testing.MockServiceHelper; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.api.gax.rpc.StatusCode; 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.common.collect.Lists; import com.google.iam.v1.AuditConfig; import com.google.iam.v1.Binding; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.GetPolicyOptions; 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.AbstractMessage; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import com.google.protobuf.Timestamp; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutionException; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class AppConnectionsServiceClientTest { private static MockAppConnectionsService mockAppConnectionsService; private static MockIAMPolicy mockIAMPolicy; private static MockLocations mockLocations; private static MockServiceHelper mockServiceHelper; private LocalChannelProvider channelProvider; private AppConnectionsServiceClient client; @BeforeClass public static void startStaticServer() { mockAppConnectionsService = new MockAppConnectionsService(); mockLocations = new MockLocations(); mockIAMPolicy = new MockIAMPolicy(); mockServiceHelper = new MockServiceHelper( UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList( mockAppConnectionsService, mockLocations, mockIAMPolicy)); mockServiceHelper.start(); } @AfterClass public static void stopServer() { mockServiceHelper.stop(); } @Before public void setUp() throws IOException { mockServiceHelper.reset(); channelProvider = mockServiceHelper.createChannelProvider(); AppConnectionsServiceSettings settings = AppConnectionsServiceSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = AppConnectionsServiceClient.create(settings); } @After public void tearDown() throws Exception { client.close(); } @Test public void listAppConnectionsTest() throws Exception { AppConnection responsesElement = AppConnection.newBuilder().build(); ListAppConnectionsResponse expectedResponse = ListAppConnectionsResponse.newBuilder() .setNextPageToken("") .addAllAppConnections(Arrays.asList(responsesElement)) .build(); mockAppConnectionsService.addResponse(expectedResponse); LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); ListAppConnectionsPagedResponse pagedListResponse = client.listAppConnections(parent); List<AppConnection> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getAppConnectionsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListAppConnectionsRequest actualRequest = ((ListAppConnectionsRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listAppConnectionsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); client.listAppConnections(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listAppConnectionsTest2() throws Exception { AppConnection responsesElement = AppConnection.newBuilder().build(); ListAppConnectionsResponse expectedResponse = ListAppConnectionsResponse.newBuilder() .setNextPageToken("") .addAllAppConnections(Arrays.asList(responsesElement)) .build(); mockAppConnectionsService.addResponse(expectedResponse); String parent = "parent-995424086"; ListAppConnectionsPagedResponse pagedListResponse = client.listAppConnections(parent); List<AppConnection> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getAppConnectionsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListAppConnectionsRequest actualRequest = ((ListAppConnectionsRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listAppConnectionsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { String parent = "parent-995424086"; client.listAppConnections(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getAppConnectionTest() throws Exception { AppConnection expectedResponse = AppConnection.newBuilder() .setName(AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .putAllLabels(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .setUid("uid115792") .setApplicationEndpoint(AppConnection.ApplicationEndpoint.newBuilder().build()) .addAllConnectors(new ArrayList<String>()) .setGateway(AppConnection.Gateway.newBuilder().build()) .build(); mockAppConnectionsService.addResponse(expectedResponse); AppConnectionName name = AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]"); AppConnection actualResponse = client.getAppConnection(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetAppConnectionRequest actualRequest = ((GetAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getAppConnectionExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { AppConnectionName name = AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]"); client.getAppConnection(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getAppConnectionTest2() throws Exception { AppConnection expectedResponse = AppConnection.newBuilder() .setName(AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .putAllLabels(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .setUid("uid115792") .setApplicationEndpoint(AppConnection.ApplicationEndpoint.newBuilder().build()) .addAllConnectors(new ArrayList<String>()) .setGateway(AppConnection.Gateway.newBuilder().build()) .build(); mockAppConnectionsService.addResponse(expectedResponse); String name = "name3373707"; AppConnection actualResponse = client.getAppConnection(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetAppConnectionRequest actualRequest = ((GetAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getAppConnectionExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { String name = "name3373707"; client.getAppConnection(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void createAppConnectionTest() throws Exception { AppConnection expectedResponse = AppConnection.newBuilder() .setName(AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .putAllLabels(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .setUid("uid115792") .setApplicationEndpoint(AppConnection.ApplicationEndpoint.newBuilder().build()) .addAllConnectors(new ArrayList<String>()) .setGateway(AppConnection.Gateway.newBuilder().build()) .build(); Operation resultOperation = Operation.newBuilder() .setName("createAppConnectionTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockAppConnectionsService.addResponse(resultOperation); LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); AppConnection appConnection = AppConnection.newBuilder().build(); String appConnectionId = "appConnectionId-1293292198"; AppConnection actualResponse = client.createAppConnectionAsync(parent, appConnection, appConnectionId).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateAppConnectionRequest actualRequest = ((CreateAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertEquals(appConnection, actualRequest.getAppConnection()); Assert.assertEquals(appConnectionId, actualRequest.getAppConnectionId()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createAppConnectionExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); AppConnection appConnection = AppConnection.newBuilder().build(); String appConnectionId = "appConnectionId-1293292198"; client.createAppConnectionAsync(parent, appConnection, appConnectionId).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void createAppConnectionTest2() throws Exception { AppConnection expectedResponse = AppConnection.newBuilder() .setName(AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .putAllLabels(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .setUid("uid115792") .setApplicationEndpoint(AppConnection.ApplicationEndpoint.newBuilder().build()) .addAllConnectors(new ArrayList<String>()) .setGateway(AppConnection.Gateway.newBuilder().build()) .build(); Operation resultOperation = Operation.newBuilder() .setName("createAppConnectionTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockAppConnectionsService.addResponse(resultOperation); String parent = "parent-995424086"; AppConnection appConnection = AppConnection.newBuilder().build(); String appConnectionId = "appConnectionId-1293292198"; AppConnection actualResponse = client.createAppConnectionAsync(parent, appConnection, appConnectionId).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CreateAppConnectionRequest actualRequest = ((CreateAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertEquals(appConnection, actualRequest.getAppConnection()); Assert.assertEquals(appConnectionId, actualRequest.getAppConnectionId()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void createAppConnectionExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { String parent = "parent-995424086"; AppConnection appConnection = AppConnection.newBuilder().build(); String appConnectionId = "appConnectionId-1293292198"; client.createAppConnectionAsync(parent, appConnection, appConnectionId).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void updateAppConnectionTest() throws Exception { AppConnection expectedResponse = AppConnection.newBuilder() .setName(AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setCreateTime(Timestamp.newBuilder().build()) .setUpdateTime(Timestamp.newBuilder().build()) .putAllLabels(new HashMap<String, String>()) .setDisplayName("displayName1714148973") .setUid("uid115792") .setApplicationEndpoint(AppConnection.ApplicationEndpoint.newBuilder().build()) .addAllConnectors(new ArrayList<String>()) .setGateway(AppConnection.Gateway.newBuilder().build()) .build(); Operation resultOperation = Operation.newBuilder() .setName("updateAppConnectionTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockAppConnectionsService.addResponse(resultOperation); AppConnection appConnection = AppConnection.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); AppConnection actualResponse = client.updateAppConnectionAsync(appConnection, updateMask).get(); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateAppConnectionRequest actualRequest = ((UpdateAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(appConnection, actualRequest.getAppConnection()); Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateAppConnectionExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { AppConnection appConnection = AppConnection.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); client.updateAppConnectionAsync(appConnection, updateMask).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void deleteAppConnectionTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("deleteAppConnectionTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockAppConnectionsService.addResponse(resultOperation); AppConnectionName name = AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]"); client.deleteAppConnectionAsync(name).get(); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); DeleteAppConnectionRequest actualRequest = ((DeleteAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void deleteAppConnectionExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { AppConnectionName name = AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]"); client.deleteAppConnectionAsync(name).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void deleteAppConnectionTest2() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); Operation resultOperation = Operation.newBuilder() .setName("deleteAppConnectionTest") .setDone(true) .setResponse(Any.pack(expectedResponse)) .build(); mockAppConnectionsService.addResponse(resultOperation); String name = "name3373707"; client.deleteAppConnectionAsync(name).get(); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); DeleteAppConnectionRequest actualRequest = ((DeleteAppConnectionRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void deleteAppConnectionExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { String name = "name3373707"; client.deleteAppConnectionAsync(name).get(); Assert.fail("No exception raised"); } catch (ExecutionException e) { Assert.assertEquals(InvalidArgumentException.class, e.getCause().getClass()); InvalidArgumentException apiException = ((InvalidArgumentException) e.getCause()); Assert.assertEquals(StatusCode.Code.INVALID_ARGUMENT, apiException.getStatusCode().getCode()); } } @Test public void resolveAppConnectionsTest() throws Exception { ResolveAppConnectionsResponse.AppConnectionDetails responsesElement = ResolveAppConnectionsResponse.AppConnectionDetails.newBuilder().build(); ResolveAppConnectionsResponse expectedResponse = ResolveAppConnectionsResponse.newBuilder() .setNextPageToken("") .addAllAppConnectionDetails(Arrays.asList(responsesElement)) .build(); mockAppConnectionsService.addResponse(expectedResponse); LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); ResolveAppConnectionsPagedResponse pagedListResponse = client.resolveAppConnections(parent); List<ResolveAppConnectionsResponse.AppConnectionDetails> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getAppConnectionDetailsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ResolveAppConnectionsRequest actualRequest = ((ResolveAppConnectionsRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void resolveAppConnectionsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]"); client.resolveAppConnections(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void resolveAppConnectionsTest2() throws Exception { ResolveAppConnectionsResponse.AppConnectionDetails responsesElement = ResolveAppConnectionsResponse.AppConnectionDetails.newBuilder().build(); ResolveAppConnectionsResponse expectedResponse = ResolveAppConnectionsResponse.newBuilder() .setNextPageToken("") .addAllAppConnectionDetails(Arrays.asList(responsesElement)) .build(); mockAppConnectionsService.addResponse(expectedResponse); String parent = "parent-995424086"; ResolveAppConnectionsPagedResponse pagedListResponse = client.resolveAppConnections(parent); List<ResolveAppConnectionsResponse.AppConnectionDetails> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getAppConnectionDetailsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockAppConnectionsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ResolveAppConnectionsRequest actualRequest = ((ResolveAppConnectionsRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void resolveAppConnectionsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockAppConnectionsService.addException(exception); try { String parent = "parent-995424086"; client.resolveAppConnections(parent); 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(); mockLocations.addResponse(expectedResponse); ListLocationsRequest request = ListLocationsRequest.newBuilder() .setName("name3373707") .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<AbstractMessage> actualRequests = mockLocations.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListLocationsRequest actualRequest = ((ListLocationsRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertEquals(request.getFilter(), actualRequest.getFilter()); Assert.assertEquals(request.getPageSize(), actualRequest.getPageSize()); Assert.assertEquals(request.getPageToken(), actualRequest.getPageToken()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listLocationsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockLocations.addException(exception); try { ListLocationsRequest request = ListLocationsRequest.newBuilder() .setName("name3373707") .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(); mockLocations.addResponse(expectedResponse); GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); Location actualResponse = client.getLocation(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockLocations.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetLocationRequest actualRequest = ((GetLocationRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getLocationExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockLocations.addException(exception); try { GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build(); client.getLocation(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void setIamPolicyTest() throws Exception { Policy expectedResponse = Policy.newBuilder() .setVersion(351608024) .addAllBindings(new ArrayList<Binding>()) .addAllAuditConfigs(new ArrayList<AuditConfig>()) .setEtag(ByteString.EMPTY) .build(); mockIAMPolicy.addResponse(expectedResponse); SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder() .setResource( AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setPolicy(Policy.newBuilder().build()) .setUpdateMask(FieldMask.newBuilder().build()) .build(); Policy actualResponse = client.setIamPolicy(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests(); Assert.assertEquals(1, actualRequests.size()); SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0)); Assert.assertEquals(request.getResource(), actualRequest.getResource()); Assert.assertEquals(request.getPolicy(), actualRequest.getPolicy()); Assert.assertEquals(request.getUpdateMask(), actualRequest.getUpdateMask()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void setIamPolicyExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockIAMPolicy.addException(exception); try { SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder() .setResource( AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setPolicy(Policy.newBuilder().build()) .setUpdateMask(FieldMask.newBuilder().build()) .build(); client.setIamPolicy(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getIamPolicyTest() throws Exception { Policy expectedResponse = Policy.newBuilder() .setVersion(351608024) .addAllBindings(new ArrayList<Binding>()) .addAllAuditConfigs(new ArrayList<AuditConfig>()) .setEtag(ByteString.EMPTY) .build(); mockIAMPolicy.addResponse(expectedResponse); GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder() .setResource( AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setOptions(GetPolicyOptions.newBuilder().build()) .build(); Policy actualResponse = client.getIamPolicy(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0)); Assert.assertEquals(request.getResource(), actualRequest.getResource()); Assert.assertEquals(request.getOptions(), actualRequest.getOptions()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getIamPolicyExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockIAMPolicy.addException(exception); try { GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder() .setResource( AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .setOptions(GetPolicyOptions.newBuilder().build()) .build(); client.getIamPolicy(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void testIamPermissionsTest() throws Exception { TestIamPermissionsResponse expectedResponse = TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList<String>()).build(); mockIAMPolicy.addResponse(expectedResponse); TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() .setResource( AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .addAllPermissions(new ArrayList<String>()) .build(); TestIamPermissionsResponse actualResponse = client.testIamPermissions(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockIAMPolicy.getRequests(); Assert.assertEquals(1, actualRequests.size()); TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0)); Assert.assertEquals(request.getResource(), actualRequest.getResource()); Assert.assertEquals(request.getPermissionsList(), actualRequest.getPermissionsList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void testIamPermissionsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockIAMPolicy.addException(exception); try { TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() .setResource( AppConnectionName.of("[PROJECT]", "[LOCATION]", "[APP_CONNECTION]").toString()) .addAllPermissions(new ArrayList<String>()) .build(); client.testIamPermissions(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
apache/storm
37,632
storm-core/test/jvm/org/apache/storm/integration/TopologyIntegrationTest.java
/* * Copyright 2018 The Apache Software Foundation. * * 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.apache.storm.integration; import static org.apache.storm.AssertLoop.assertAcked; import static org.apache.storm.AssertLoop.assertFailed; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItem; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import org.apache.storm.Testing; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.generated.StormTopology; import org.apache.storm.generated.SubmitOptions; import org.apache.storm.generated.TopologyInitialStatus; import org.apache.storm.hooks.BaseTaskHook; import org.apache.storm.hooks.BaseWorkerHook; import org.apache.storm.hooks.info.BoltAckInfo; import org.apache.storm.hooks.info.BoltExecuteInfo; import org.apache.storm.hooks.info.BoltFailInfo; import org.apache.storm.hooks.info.EmitInfo; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.task.WorkerUserContext; import org.apache.storm.testing.AckFailMapTracker; import org.apache.storm.testing.CompleteTopologyParam; import org.apache.storm.testing.FeederSpout; import org.apache.storm.testing.FixedTuple; import org.apache.storm.testing.FixedTupleSpout; import org.apache.storm.testing.IntegrationTest; import org.apache.storm.testing.MockedSources; import org.apache.storm.testing.TestAggregatesCounter; import org.apache.storm.testing.TestConfBolt; import org.apache.storm.testing.TestGlobalCount; import org.apache.storm.testing.TestPlannerSpout; import org.apache.storm.testing.TestWordCounter; import org.apache.storm.testing.TestWordSpout; import org.apache.storm.testing.TrackedTopology; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.TopologyBuilder; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.topology.base.BaseRichSpout; import org.apache.storm.topology.base.BaseTickTupleAwareRichBolt; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @IntegrationTest public class TopologyIntegrationTest { @ParameterizedTest @ValueSource(strings = {"true", "false"}) public void testBasicTopology(boolean useLocalMessaging) throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withSupervisors(4) .withDaemonConf(Collections.singletonMap(Config.STORM_LOCAL_MODE_ZMQ, !useLocalMessaging)) .build()) { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 3); builder.setBolt("2", new TestWordCounter(), 4).fieldsGrouping("1", new Fields("word")); builder.setBolt("3", new TestGlobalCount()).globalGrouping("1"); builder.setBolt("4", new TestAggregatesCounter()).globalGrouping("2"); StormTopology topology = builder.createTopology(); Map<String, Object> stormConf = new HashMap<>(); stormConf.put(Config.TOPOLOGY_WORKERS, 2); stormConf.put(Config.TOPOLOGY_TESTING_ALWAYS_TRY_SERIALIZE, true); List<FixedTuple> testTuples = Stream.of("nathan", "bob", "joey", "nathan") .map(value -> new FixedTuple(new Values(value))) .collect(Collectors.toList()); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", testTuples)); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); completeTopologyParams.setMockedSources(mockedSources); completeTopologyParams.setStormConf(stormConf); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topology, completeTopologyParams); assertThat(Testing.readTuples(results, "1"), containsInAnyOrder( new Values("nathan"), new Values("nathan"), new Values("bob"), new Values("joey"))); assertThat(Testing.readTuples(results, "2"), containsInAnyOrder( new Values("nathan", 1), new Values("nathan", 2), new Values("bob", 1), new Values("joey", 1) )); assertThat(Testing.readTuples(results, "3"), contains( new Values(1), new Values(2), new Values(3), new Values(4) )); assertThat(Testing.readTuples(results, "4"), contains( new Values(1), new Values(2), new Values(3), new Values(4) )); } } private static class EmitTaskIdBolt extends BaseRichBolt { private int taskIndex; private OutputCollector collector; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("tid")); } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; this.taskIndex = context.getThisTaskIndex(); } @Override public void execute(Tuple input) { collector.emit(input, new Values(taskIndex)); collector.ack(input); } } @Test public void testMultiTasksPerCluster() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withSupervisors(4) .build()) { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true)); builder.setBolt("2", new EmitTaskIdBolt(), 3).allGrouping("1") .addConfigurations(Collections.singletonMap(Config.TOPOLOGY_TASKS, 6)); StormTopology topology = builder.createTopology(); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", Collections.singletonList(new FixedTuple(new Values("a"))))); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); completeTopologyParams.setMockedSources(mockedSources); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topology, completeTopologyParams); assertThat(Testing.readTuples(results, "2"), containsInAnyOrder( new Values(0), new Values(1), new Values(2), new Values(3), new Values(4), new Values(5) )); } } @Test public void testTimeout() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withSupervisors(4) .withDaemonConf(Collections.singletonMap(Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS, true)) .build()) { FeederSpout feeder = new FeederSpout(new Fields("field1")); AckFailMapTracker tracker = new AckFailMapTracker(); feeder.setAckFailDelegate(tracker); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", feeder); builder.setBolt("2", new AckEveryOtherBolt()).globalGrouping("1"); StormTopology topology = builder.createTopology(); cluster.submitTopology("timeout-tester", Collections.singletonMap(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS, 10), topology); cluster.advanceClusterTime(11); feeder.feed(new Values("a"), 1); feeder.feed(new Values("b"), 2); feeder.feed(new Values("c"), 3); cluster.advanceClusterTime(9); assertAcked(tracker, 1, 3); assertThat(tracker.isFailed(2), is(false)); cluster.advanceClusterTime(12); assertFailed(tracker, 2); } } private static class ResetTimeoutBolt extends BaseRichBolt { private int tupleCounter = 1; private Tuple firstTuple = null; private OutputCollector collector; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { if (tupleCounter == 1) { firstTuple = input; } else if (tupleCounter == 2) { collector.resetTimeout(firstTuple); } else if (tupleCounter == 5) { collector.ack(firstTuple); collector.ack(input); } else { collector.resetTimeout(firstTuple); collector.ack(input); } tupleCounter++; } } @Test public void testResetTimeout() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withDaemonConf(Collections.singletonMap(Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS, true)) .build()) { FeederSpout feeder = new FeederSpout(new Fields("field1")); AckFailMapTracker tracker = new AckFailMapTracker(); feeder.setAckFailDelegate(tracker); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", feeder); builder.setBolt("2", new ResetTimeoutBolt()).globalGrouping("1"); StormTopology topology = builder.createTopology(); cluster.submitTopology("reset-timeout-tester", Collections.singletonMap(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS, 10), topology); //The first tuple wil be used to check timeout reset feeder.feed(new Values("a"), 1); //The second tuple is used to wait for the spout to rotate its pending map feeder.feed(new Values("b"), 2); cluster.advanceClusterTime(9); //The other tuples are used to reset the first tuple's timeout, //and to wait for the message to get through to the spout (acks use the same path as timeout resets) feeder.feed(new Values("c"), 3); assertAcked(tracker, 3); cluster.advanceClusterTime(9); feeder.feed(new Values("d"), 4); assertAcked(tracker, 4); cluster.advanceClusterTime(2); //The time is now twice the message timeout, the second tuple should expire since it was not acked //Waiting for this also ensures that the first tuple gets failed if reset-timeout doesn't work assertFailed(tracker, 2); //Put in a tuple to cause the first tuple to be acked feeder.feed(new Values("e"), 5); assertAcked(tracker, 5); //The first tuple should be acked, and should not have failed assertThat(tracker.isFailed(1), is(false)); assertAcked(tracker, 1); } } private StormTopology mkValidateTopology() { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 3); builder.setBolt("2", new TestWordCounter(), 4).fieldsGrouping("1", new Fields("word")); return builder.createTopology(); } private StormTopology mkInvalidateTopology1() { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 3); builder.setBolt("2", new TestWordCounter(), 4).fieldsGrouping("3", new Fields("word")); return builder.createTopology(); } private StormTopology mkInvalidateTopology2() { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 3); builder.setBolt("2", new TestWordCounter(), 4).fieldsGrouping("1", new Fields("non-exists-field")); return builder.createTopology(); } private StormTopology mkInvalidateTopology3() { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 3); builder.setBolt("2", new TestWordCounter(), 4).fieldsGrouping("1", "non-exists-stream", new Fields("word")); return builder.createTopology(); } private boolean tryCompleteWordCountTopology(LocalCluster cluster, StormTopology topology) throws Exception { try { List<FixedTuple> testTuples = Stream.of("nathan", "bob", "joey", "nathan") .map(value -> new FixedTuple(new Values(value))) .collect(Collectors.toList()); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", testTuples)); CompleteTopologyParam completeTopologyParam = new CompleteTopologyParam(); completeTopologyParam.setMockedSources(mockedSources); completeTopologyParam.setStormConf(Collections.singletonMap(Config.TOPOLOGY_WORKERS, 2)); Testing.completeTopology(cluster, topology, completeTopologyParam); return false; } catch (InvalidTopologyException e) { return true; } } @Test public void testValidateTopologystructure() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withDaemonConf(Collections.singletonMap(Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS, true)) .build()) { assertThat(tryCompleteWordCountTopology(cluster, mkValidateTopology()), is(false)); assertThat(tryCompleteWordCountTopology(cluster, mkInvalidateTopology1()), is(true)); assertThat(tryCompleteWordCountTopology(cluster, mkInvalidateTopology2()), is(true)); assertThat(tryCompleteWordCountTopology(cluster, mkInvalidateTopology3()), is(true)); } } @Test public void testSystemStream() throws Exception { //this test works because mocking a spout splits up the tuples evenly among the tasks try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .build()) { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 3); builder.setBolt("2", new IdentityBolt(), 1) .fieldsGrouping("1", new Fields("word")) .globalGrouping("1", "__system"); StormTopology topology = builder.createTopology(); Map<String, Object> stormConf = new HashMap<>(); stormConf.put(Config.TOPOLOGY_WORKERS, 2); List<FixedTuple> testTuples = Stream.of("a", "b", "c") .map(value -> new FixedTuple(new Values(value))) .collect(Collectors.toList()); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", testTuples)); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); completeTopologyParams.setMockedSources(mockedSources); completeTopologyParams.setStormConf(stormConf); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topology, completeTopologyParams); assertThat(Testing.readTuples(results, "2"), containsInAnyOrder( new Values("a"), new Values("b"), new Values("c") )); } } private static class BranchingBolt extends BaseRichBolt { private final int branches; private OutputCollector collector; public BranchingBolt(int branches) { this.branches = branches; } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("num")); } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { IntStream.range(0, branches) .forEach(i -> collector.emit(input, new Values(i))); collector.ack(input); } } private static class AckBolt extends BaseRichBolt { private OutputCollector collector; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { collector.ack(input); } } @Test public void testAcking() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withTracked() .build()) { AckTrackingFeeder feeder1 = new AckTrackingFeeder("num"); AckTrackingFeeder feeder2 = new AckTrackingFeeder("num"); AckTrackingFeeder feeder3 = new AckTrackingFeeder("num"); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", feeder1.getSpout()); builder.setSpout("2", feeder2.getSpout()); builder.setSpout("3", feeder3.getSpout()); builder.setBolt("4", new BranchingBolt(2)).shuffleGrouping("1"); builder.setBolt("5", new BranchingBolt(4)).shuffleGrouping("2"); builder.setBolt("6", new BranchingBolt(1)).shuffleGrouping("3"); builder.setBolt("7", new AggBolt(3)).shuffleGrouping("4").shuffleGrouping("5").shuffleGrouping("6"); builder.setBolt("8", new BranchingBolt(2)).shuffleGrouping("7"); builder.setBolt("9", new AckBolt()).shuffleGrouping("8"); TrackedTopology tracked = new TrackedTopology(builder.createTopology(), cluster); cluster.submitTopology("acking-test1", Collections.emptyMap(), tracked); cluster.advanceClusterTime(11); feeder1.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder1.assertNumAcks(0); feeder2.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder1.assertNumAcks(1); feeder2.assertNumAcks(1); feeder1.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder1.assertNumAcks(0); feeder1.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder1.assertNumAcks(1); feeder3.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder1.assertNumAcks(0); feeder3.assertNumAcks(0); feeder2.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder1.feed(new Values(1)); feeder2.feed(new Values(1)); feeder3.feed(new Values(1)); } } @Test public void testAckBranching() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withTracked() .build()) { AckTrackingFeeder feeder = new AckTrackingFeeder("num"); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", feeder.getSpout()); builder.setBolt("2", new IdentityBolt()).shuffleGrouping("1"); builder.setBolt("3", new IdentityBolt()).shuffleGrouping("1"); builder.setBolt("4", new AggBolt(4)).shuffleGrouping("2").shuffleGrouping("3"); TrackedTopology tracked = new TrackedTopology(builder.createTopology(), cluster); cluster.submitTopology("test-acking2", Collections.emptyMap(), tracked); cluster.advanceClusterTime(11); feeder.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder.assertNumAcks(0); feeder.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder.assertNumAcks(2); } } private static class DupAnchorBolt extends BaseRichBolt { private OutputCollector collector; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("num")); } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { ArrayList<Tuple> anchors = new ArrayList<>(); anchors.add(input); anchors.add(input); collector.emit(anchors, new Values(1)); collector.ack(input); } } private static boolean boltPrepared = false; private static class PrepareTrackedBolt extends BaseRichBolt { private OutputCollector collector; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; } @Override public void execute(Tuple input) { boltPrepared = true; collector.ack(input); } } private static boolean spoutOpened = false; private static class OpenTrackedSpout extends BaseRichSpout { @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("val")); } @Override public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) { } @Override public void nextTuple() { spoutOpened = true; } } @Test public void testSubmitInactiveTopology() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withDaemonConf(Collections.singletonMap(Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS, true)) .build()) { FeederSpout feeder = new FeederSpout(new Fields("field1")); AckFailMapTracker tracker = new AckFailMapTracker(); feeder.setAckFailDelegate(tracker); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", feeder); builder.setSpout("2", new OpenTrackedSpout()); builder.setBolt("3", new PrepareTrackedBolt()).globalGrouping("1"); boltPrepared = false; spoutOpened = false; StormTopology topology = builder.createTopology(); cluster.submitTopologyWithOpts("test", Collections.singletonMap(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS, 10), topology, new SubmitOptions(TopologyInitialStatus.INACTIVE)); cluster.advanceClusterTime(11); feeder.feed(new Values("a"), 1); cluster.advanceClusterTime(9); assertThat(boltPrepared, is(false)); assertThat(spoutOpened, is(false)); cluster.getNimbus().activate("test"); cluster.advanceClusterTime(12); assertAcked(tracker, 1); assertThat(boltPrepared, is(true)); assertThat(spoutOpened, is(true)); } } @Test public void testAckingSelfAnchor() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withTracked() .build()) { AckTrackingFeeder feeder = new AckTrackingFeeder("num"); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", feeder.getSpout()); builder.setBolt("2", new DupAnchorBolt()).shuffleGrouping("1"); builder.setBolt("3", new AckBolt()).shuffleGrouping("2"); TrackedTopology tracked = new TrackedTopology(builder.createTopology(), cluster); cluster.submitTopology("test", Collections.emptyMap(), tracked); cluster.advanceClusterTime(11); feeder.feed(new Values(1)); Testing.trackedWait(tracked, 1); feeder.assertNumAcks(1); feeder.feed(new Values(1)); feeder.feed(new Values(1)); feeder.feed(new Values(1)); Testing.trackedWait(tracked, 3); feeder.assertNumAcks(3); } } private Map<Object, Object> listToMap(List<Object> list) { assertThat(list.size() % 2, is(0)); Map<Object, Object> res = new HashMap<>(); for (int i = 0; i < list.size(); i += 2) { res.put(list.get(i), list.get(i + 1)); } return res; } @Test public void testKryoDecoratorsConfig() throws Exception { Map<String, Object> daemonConf = new HashMap<>(); daemonConf.put(Config.TOPOLOGY_SKIP_MISSING_KRYO_REGISTRATIONS, true); daemonConf.put(Config.TOPOLOGY_KRYO_DECORATORS, "this-is-overridden"); try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withDaemonConf(daemonConf) .build()) { TopologyBuilder topologyBuilder = new TopologyBuilder(); topologyBuilder.setSpout("1", new TestPlannerSpout(new Fields("conf"))); topologyBuilder.setBolt("2", new TestConfBolt(Collections.singletonMap(Config.TOPOLOGY_KRYO_DECORATORS, Arrays.asList("one", "two")))) .shuffleGrouping("1"); List<FixedTuple> testTuples = Collections.singletonList(new Values(Config.TOPOLOGY_KRYO_DECORATORS)).stream() .map(FixedTuple::new) .collect(Collectors.toList()); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", testTuples)); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); completeTopologyParams.setMockedSources(mockedSources); completeTopologyParams.setStormConf(Collections.singletonMap(Config.TOPOLOGY_KRYO_DECORATORS, Arrays.asList("one", "three"))); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topologyBuilder.createTopology(), completeTopologyParams); List<Object> concatValues = Testing.readTuples(results, "2").stream() .flatMap(Collection::stream) .collect(Collectors.toList()); assertThat(concatValues.get(0), is(Config.TOPOLOGY_KRYO_DECORATORS)); assertThat(concatValues.get(1), is(Arrays.asList("one", "two", "three"))); } } @Test public void testComponentSpecificConfig() throws Exception { Map<String, Object> daemonConf = new HashMap<>(); daemonConf.put(Config.TOPOLOGY_SKIP_MISSING_KRYO_REGISTRATIONS, true); try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .withDaemonConf(daemonConf) .build()) { TopologyBuilder topologyBuilder = new TopologyBuilder(); topologyBuilder.setSpout("1", new TestPlannerSpout(new Fields("conf"))); Map<String, Object> componentConf = new HashMap<>(); componentConf.put("fake.config", 123); componentConf.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 20); componentConf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 30); componentConf.put(Config.TOPOLOGY_KRYO_REGISTER, Arrays.asList(Collections.singletonMap("fake.type", "bad.serializer"), Collections.singletonMap("fake.type2", "a.serializer"))); topologyBuilder.setBolt("2", new TestConfBolt(componentConf)) .shuffleGrouping("1") .setMaxTaskParallelism(2) .addConfiguration("fake.config2", 987); List<FixedTuple> testTuples = Stream.of("fake.config", Config.TOPOLOGY_MAX_TASK_PARALLELISM, Config.TOPOLOGY_MAX_SPOUT_PENDING, "fake.config2", Config.TOPOLOGY_KRYO_REGISTER) .map(value -> new FixedTuple(new Values(value))) .collect(Collectors.toList()); Map<String, String> kryoRegister = new HashMap<>(); kryoRegister.put("fake.type", "good.serializer"); kryoRegister.put("fake.type3", "a.serializer3"); Map<String, Object> stormConf = new HashMap<>(); stormConf.put(Config.TOPOLOGY_KRYO_REGISTER, Collections.singletonList(kryoRegister)); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", testTuples)); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); completeTopologyParams.setMockedSources(mockedSources); completeTopologyParams.setStormConf(stormConf); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topologyBuilder.createTopology(), completeTopologyParams); Map<String, Object> expectedValues = new HashMap<>(); expectedValues.put("fake.config", 123L); expectedValues.put("fake.config2", 987L); expectedValues.put(Config.TOPOLOGY_MAX_TASK_PARALLELISM, 2L); expectedValues.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 30L); Map<String, String> expectedKryoRegister = new HashMap<>(kryoRegister); expectedKryoRegister.put("fake.type2", "a.serializer"); expectedValues.put(Config.TOPOLOGY_KRYO_REGISTER, expectedKryoRegister); List<Object> concatValues = Testing.readTuples(results, "2").stream() .flatMap(Collection::stream) .collect(Collectors.toList()); assertThat(listToMap(concatValues), is(expectedValues)); } } private static class HooksBolt extends BaseRichBolt { private int acked = 0; private int failed = 0; private int executed = 0; private int emitted = 0; private OutputCollector collector; @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("emit", "ack", "fail", "executed")); } @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.collector = collector; context.addTaskHook(new BaseTaskHook() { @Override public void boltExecute(BoltExecuteInfo info) { executed++; } @Override public void boltFail(BoltFailInfo info) { failed++; } @Override public void boltAck(BoltAckInfo info) { acked++; } @Override public void emit(EmitInfo info) { emitted++; } }); } @Override public void execute(Tuple input) { collector.emit(new Values(emitted, acked, failed, executed)); if (acked - failed == 0) { collector.ack(input); } else { collector.fail(input); } } } @Test public void testHooks() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .build()) { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestPlannerSpout(new Fields("conf"))); builder.setBolt("2", new HooksBolt()).shuffleGrouping("1"); StormTopology topology = builder.createTopology(); List<FixedTuple> testTuples = Stream.of(1, 1, 1, 1) .map(value -> new FixedTuple(new Values(value))) .collect(Collectors.toList()); MockedSources mockedSources = new MockedSources(Collections.singletonMap("1", testTuples)); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); completeTopologyParams.setMockedSources(mockedSources); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topology, completeTopologyParams); List<List<Object>> expectedTuples = Arrays.asList( Arrays.asList(0, 0, 0, 0), Arrays.asList(2, 1, 0, 1), Arrays.asList(4, 1, 1, 2), Arrays.asList(6, 2, 1, 3)); assertThat(Testing.readTuples(results, "2"), is(expectedTuples)); } } private static class TestUserResource implements Serializable { String id; String name; TestUserResource(String id, String name) { this.id = id; this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TestUserResource that = (TestUserResource) o; return Objects.equals(id, that.id) && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(id, name); } } private static class ResourceInitializingWorkerHook extends BaseWorkerHook { private Map<String, String> resourceMap; public ResourceInitializingWorkerHook(Map<String, String> resourceMap) { this.resourceMap = resourceMap; } @Override public void start(Map<String, Object> topoConf, WorkerUserContext context) { resourceMap.forEach((resourceKey, resourceValue) -> context.setResource(resourceKey, new TestUserResource(resourceKey, resourceValue))); } } private static class ResourceForwardingBolt extends BaseTickTupleAwareRichBolt { private transient TopologyContext context; private transient OutputCollector collector; @Override public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) { this.context = context; this.collector = collector; } @Override public void process(Tuple input) { String key = input.getStringByField("key"); collector.emit(new Values(key, context.getResource(key))); collector.ack(input); } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("key", "val")); } } @Test public void testUserResourcesAreVisibleToTasks() throws Exception { try (LocalCluster cluster = new LocalCluster.Builder() .withSimulatedTime() .build()) { Map<String, String> resourceMap = new HashMap<>(1); resourceMap.put("resource-key1", "resource-value1"); List<FixedTuple> testTuples = resourceMap.keySet().stream() .map(value -> new FixedTuple(new Values(value))) .collect(Collectors.toList()); TopologyBuilder builder = new TopologyBuilder(); builder.addWorkerHook(new ResourceInitializingWorkerHook(resourceMap)); builder.setSpout("1", new FixedTupleSpout(testTuples, new Fields("key"))); builder.setBolt("2", new ResourceForwardingBolt()).shuffleGrouping("1"); StormTopology topology = builder.createTopology(); CompleteTopologyParam completeTopologyParams = new CompleteTopologyParam(); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, topology, completeTopologyParams); List<Object> expectedTuple = Arrays.asList("resource-key1", new TestUserResource("resource-key1", "resource-value1")); assertThat(Testing.readTuples(results, "2"), hasItem(expectedTuple)); } } }
googleapis/google-cloud-java
37,666
java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ListFlowsResponse.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/flow.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.cx.v3beta1; /** * * * <pre> * The response message for * [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse} */ public final class ListFlowsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse) ListFlowsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListFlowsResponse.newBuilder() to construct. private ListFlowsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListFlowsResponse() { flows_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListFlowsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.FlowProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListFlowsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.FlowProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListFlowsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.class, com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.Builder.class); } public static final int FLOWS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Flow> flows_; /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Flow> getFlowsList() { return flows_; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder> getFlowsOrBuilderList() { return flows_; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ @java.lang.Override public int getFlowsCount() { return flows_.size(); } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.Flow getFlows(int index) { return flows_.get(index); } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder getFlowsOrBuilder(int index) { return flows_.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 < flows_.size(); i++) { output.writeMessage(1, flows_.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 < flows_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, flows_.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.dialogflow.cx.v3beta1.ListFlowsResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse other = (com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse) obj; if (!getFlowsList().equals(other.getFlowsList())) 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 (getFlowsCount() > 0) { hash = (37 * hash) + FLOWS_FIELD_NUMBER; hash = (53 * hash) + getFlowsList().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.dialogflow.cx.v3beta1.ListFlowsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse 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.ListFlowsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse 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.ListFlowsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse 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.ListFlowsResponse 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.ListFlowsResponse 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.ListFlowsResponse 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.ListFlowsResponse 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.ListFlowsResponse 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.ListFlowsResponse 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.ListFlowsResponse 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 * [Flows.ListFlows][google.cloud.dialogflow.cx.v3beta1.Flows.ListFlows]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse) com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.FlowProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListFlowsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.FlowProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListFlowsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.class, com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (flowsBuilder_ == null) { flows_ = java.util.Collections.emptyList(); } else { flows_ = null; flowsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.cx.v3beta1.FlowProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListFlowsResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse build() { com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse buildPartial() { com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse result = new com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse result) { if (flowsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { flows_ = java.util.Collections.unmodifiableList(flows_); bitField0_ = (bitField0_ & ~0x00000001); } result.flows_ = flows_; } else { result.flows_ = flowsBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse 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.dialogflow.cx.v3beta1.ListFlowsResponse) { return mergeFrom((com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse other) { if (other == com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse.getDefaultInstance()) return this; if (flowsBuilder_ == null) { if (!other.flows_.isEmpty()) { if (flows_.isEmpty()) { flows_ = other.flows_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureFlowsIsMutable(); flows_.addAll(other.flows_); } onChanged(); } } else { if (!other.flows_.isEmpty()) { if (flowsBuilder_.isEmpty()) { flowsBuilder_.dispose(); flowsBuilder_ = null; flows_ = other.flows_; bitField0_ = (bitField0_ & ~0x00000001); flowsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getFlowsFieldBuilder() : null; } else { flowsBuilder_.addAllMessages(other.flows_); } } } 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.dialogflow.cx.v3beta1.Flow m = input.readMessage( com.google.cloud.dialogflow.cx.v3beta1.Flow.parser(), extensionRegistry); if (flowsBuilder_ == null) { ensureFlowsIsMutable(); flows_.add(m); } else { flowsBuilder_.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.dialogflow.cx.v3beta1.Flow> flows_ = java.util.Collections.emptyList(); private void ensureFlowsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { flows_ = new java.util.ArrayList<com.google.cloud.dialogflow.cx.v3beta1.Flow>(flows_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Flow, com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder, com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder> flowsBuilder_; /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Flow> getFlowsList() { if (flowsBuilder_ == null) { return java.util.Collections.unmodifiableList(flows_); } else { return flowsBuilder_.getMessageList(); } } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public int getFlowsCount() { if (flowsBuilder_ == null) { return flows_.size(); } else { return flowsBuilder_.getCount(); } } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Flow getFlows(int index) { if (flowsBuilder_ == null) { return flows_.get(index); } else { return flowsBuilder_.getMessage(index); } } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder setFlows(int index, com.google.cloud.dialogflow.cx.v3beta1.Flow value) { if (flowsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFlowsIsMutable(); flows_.set(index, value); onChanged(); } else { flowsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder setFlows( int index, com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder builderForValue) { if (flowsBuilder_ == null) { ensureFlowsIsMutable(); flows_.set(index, builderForValue.build()); onChanged(); } else { flowsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder addFlows(com.google.cloud.dialogflow.cx.v3beta1.Flow value) { if (flowsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFlowsIsMutable(); flows_.add(value); onChanged(); } else { flowsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder addFlows(int index, com.google.cloud.dialogflow.cx.v3beta1.Flow value) { if (flowsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureFlowsIsMutable(); flows_.add(index, value); onChanged(); } else { flowsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder addFlows(com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder builderForValue) { if (flowsBuilder_ == null) { ensureFlowsIsMutable(); flows_.add(builderForValue.build()); onChanged(); } else { flowsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder addFlows( int index, com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder builderForValue) { if (flowsBuilder_ == null) { ensureFlowsIsMutable(); flows_.add(index, builderForValue.build()); onChanged(); } else { flowsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder addAllFlows( java.lang.Iterable<? extends com.google.cloud.dialogflow.cx.v3beta1.Flow> values) { if (flowsBuilder_ == null) { ensureFlowsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, flows_); onChanged(); } else { flowsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder clearFlows() { if (flowsBuilder_ == null) { flows_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { flowsBuilder_.clear(); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public Builder removeFlows(int index) { if (flowsBuilder_ == null) { ensureFlowsIsMutable(); flows_.remove(index); onChanged(); } else { flowsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder getFlowsBuilder(int index) { return getFlowsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder getFlowsOrBuilder(int index) { if (flowsBuilder_ == null) { return flows_.get(index); } else { return flowsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder> getFlowsOrBuilderList() { if (flowsBuilder_ != null) { return flowsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(flows_); } } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder addFlowsBuilder() { return getFlowsFieldBuilder() .addBuilder(com.google.cloud.dialogflow.cx.v3beta1.Flow.getDefaultInstance()); } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder addFlowsBuilder(int index) { return getFlowsFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.cx.v3beta1.Flow.getDefaultInstance()); } /** * * * <pre> * The list of flows. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Flow flows = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder> getFlowsBuilderList() { return getFlowsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Flow, com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder, com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder> getFlowsFieldBuilder() { if (flowsBuilder_ == null) { flowsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Flow, com.google.cloud.dialogflow.cx.v3beta1.Flow.Builder, com.google.cloud.dialogflow.cx.v3beta1.FlowOrBuilder>( flows_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); flows_ = null; } return flowsBuilder_; } 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.dialogflow.cx.v3beta1.ListFlowsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse) private static final com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse(); } public static com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListFlowsResponse> PARSER = new com.google.protobuf.AbstractParser<ListFlowsResponse>() { @java.lang.Override public ListFlowsResponse 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<ListFlowsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListFlowsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListFlowsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,666
java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ListPagesResponse.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/page.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.cx.v3beta1; /** * * * <pre> * The response message for * [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListPagesResponse} */ public final class ListPagesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.ListPagesResponse) ListPagesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListPagesResponse.newBuilder() to construct. private ListPagesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListPagesResponse() { pages_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListPagesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.PageProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListPagesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.PageProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListPagesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.class, com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.Builder.class); } public static final int PAGES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Page> pages_; /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Page> getPagesList() { return pages_; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder> getPagesOrBuilderList() { return pages_; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ @java.lang.Override public int getPagesCount() { return pages_.size(); } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.Page getPages(int index) { return pages_.get(index); } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder getPagesOrBuilder(int index) { return pages_.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 < pages_.size(); i++) { output.writeMessage(1, pages_.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 < pages_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, pages_.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.dialogflow.cx.v3beta1.ListPagesResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse other = (com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse) obj; if (!getPagesList().equals(other.getPagesList())) 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 (getPagesCount() > 0) { hash = (37 * hash) + PAGES_FIELD_NUMBER; hash = (53 * hash) + getPagesList().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.dialogflow.cx.v3beta1.ListPagesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse 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.ListPagesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse 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.ListPagesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse 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.ListPagesResponse 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.ListPagesResponse 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.ListPagesResponse 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.ListPagesResponse 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.ListPagesResponse 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.ListPagesResponse 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.ListPagesResponse 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 * [Pages.ListPages][google.cloud.dialogflow.cx.v3beta1.Pages.ListPages]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListPagesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.ListPagesResponse) com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.PageProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListPagesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.PageProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListPagesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.class, com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (pagesBuilder_ == null) { pages_ = java.util.Collections.emptyList(); } else { pages_ = null; pagesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.cx.v3beta1.PageProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListPagesResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse build() { com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse buildPartial() { com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse result = new com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse result) { if (pagesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { pages_ = java.util.Collections.unmodifiableList(pages_); bitField0_ = (bitField0_ & ~0x00000001); } result.pages_ = pages_; } else { result.pages_ = pagesBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse 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.dialogflow.cx.v3beta1.ListPagesResponse) { return mergeFrom((com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse other) { if (other == com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse.getDefaultInstance()) return this; if (pagesBuilder_ == null) { if (!other.pages_.isEmpty()) { if (pages_.isEmpty()) { pages_ = other.pages_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensurePagesIsMutable(); pages_.addAll(other.pages_); } onChanged(); } } else { if (!other.pages_.isEmpty()) { if (pagesBuilder_.isEmpty()) { pagesBuilder_.dispose(); pagesBuilder_ = null; pages_ = other.pages_; bitField0_ = (bitField0_ & ~0x00000001); pagesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPagesFieldBuilder() : null; } else { pagesBuilder_.addAllMessages(other.pages_); } } } 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.dialogflow.cx.v3beta1.Page m = input.readMessage( com.google.cloud.dialogflow.cx.v3beta1.Page.parser(), extensionRegistry); if (pagesBuilder_ == null) { ensurePagesIsMutable(); pages_.add(m); } else { pagesBuilder_.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.dialogflow.cx.v3beta1.Page> pages_ = java.util.Collections.emptyList(); private void ensurePagesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { pages_ = new java.util.ArrayList<com.google.cloud.dialogflow.cx.v3beta1.Page>(pages_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Page, com.google.cloud.dialogflow.cx.v3beta1.Page.Builder, com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder> pagesBuilder_; /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Page> getPagesList() { if (pagesBuilder_ == null) { return java.util.Collections.unmodifiableList(pages_); } else { return pagesBuilder_.getMessageList(); } } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public int getPagesCount() { if (pagesBuilder_ == null) { return pages_.size(); } else { return pagesBuilder_.getCount(); } } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Page getPages(int index) { if (pagesBuilder_ == null) { return pages_.get(index); } else { return pagesBuilder_.getMessage(index); } } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder setPages(int index, com.google.cloud.dialogflow.cx.v3beta1.Page value) { if (pagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePagesIsMutable(); pages_.set(index, value); onChanged(); } else { pagesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder setPages( int index, com.google.cloud.dialogflow.cx.v3beta1.Page.Builder builderForValue) { if (pagesBuilder_ == null) { ensurePagesIsMutable(); pages_.set(index, builderForValue.build()); onChanged(); } else { pagesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder addPages(com.google.cloud.dialogflow.cx.v3beta1.Page value) { if (pagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePagesIsMutable(); pages_.add(value); onChanged(); } else { pagesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder addPages(int index, com.google.cloud.dialogflow.cx.v3beta1.Page value) { if (pagesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePagesIsMutable(); pages_.add(index, value); onChanged(); } else { pagesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder addPages(com.google.cloud.dialogflow.cx.v3beta1.Page.Builder builderForValue) { if (pagesBuilder_ == null) { ensurePagesIsMutable(); pages_.add(builderForValue.build()); onChanged(); } else { pagesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder addPages( int index, com.google.cloud.dialogflow.cx.v3beta1.Page.Builder builderForValue) { if (pagesBuilder_ == null) { ensurePagesIsMutable(); pages_.add(index, builderForValue.build()); onChanged(); } else { pagesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder addAllPages( java.lang.Iterable<? extends com.google.cloud.dialogflow.cx.v3beta1.Page> values) { if (pagesBuilder_ == null) { ensurePagesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, pages_); onChanged(); } else { pagesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder clearPages() { if (pagesBuilder_ == null) { pages_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { pagesBuilder_.clear(); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public Builder removePages(int index) { if (pagesBuilder_ == null) { ensurePagesIsMutable(); pages_.remove(index); onChanged(); } else { pagesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Page.Builder getPagesBuilder(int index) { return getPagesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder getPagesOrBuilder(int index) { if (pagesBuilder_ == null) { return pages_.get(index); } else { return pagesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder> getPagesOrBuilderList() { if (pagesBuilder_ != null) { return pagesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(pages_); } } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Page.Builder addPagesBuilder() { return getPagesFieldBuilder() .addBuilder(com.google.cloud.dialogflow.cx.v3beta1.Page.getDefaultInstance()); } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Page.Builder addPagesBuilder(int index) { return getPagesFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.cx.v3beta1.Page.getDefaultInstance()); } /** * * * <pre> * The list of pages. There will be a maximum number of items returned based * on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Page pages = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Page.Builder> getPagesBuilderList() { return getPagesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Page, com.google.cloud.dialogflow.cx.v3beta1.Page.Builder, com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder> getPagesFieldBuilder() { if (pagesBuilder_ == null) { pagesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Page, com.google.cloud.dialogflow.cx.v3beta1.Page.Builder, com.google.cloud.dialogflow.cx.v3beta1.PageOrBuilder>( pages_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); pages_ = null; } return pagesBuilder_; } 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.dialogflow.cx.v3beta1.ListPagesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.ListPagesResponse) private static final com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse(); } public static com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListPagesResponse> PARSER = new com.google.protobuf.AbstractParser<ListPagesResponse>() { @java.lang.Override public ListPagesResponse 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<ListPagesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListPagesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListPagesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,666
java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ListToolsResponse.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.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.cx.v3beta1; /** * * * <pre> * The response message for * [Tools.ListTools][google.cloud.dialogflow.cx.v3beta1.Tools.ListTools]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListToolsResponse} */ public final class ListToolsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.ListToolsResponse) ListToolsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListToolsResponse.newBuilder() to construct. private ListToolsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListToolsResponse() { tools_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListToolsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.ToolProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListToolsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.ToolProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListToolsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.class, com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.Builder.class); } public static final int TOOLS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Tool> tools_; /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Tool> getToolsList() { return tools_; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder> getToolsOrBuilderList() { return tools_; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ @java.lang.Override public int getToolsCount() { return tools_.size(); } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.Tool getTools(int index) { return tools_.get(index); } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder getToolsOrBuilder(int index) { return tools_.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 < tools_.size(); i++) { output.writeMessage(1, tools_.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 < tools_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, tools_.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.dialogflow.cx.v3beta1.ListToolsResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse other = (com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse) obj; if (!getToolsList().equals(other.getToolsList())) 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 (getToolsCount() > 0) { hash = (37 * hash) + TOOLS_FIELD_NUMBER; hash = (53 * hash) + getToolsList().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.dialogflow.cx.v3beta1.ListToolsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse 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.ListToolsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse 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.ListToolsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse 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.ListToolsResponse 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.ListToolsResponse 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.ListToolsResponse 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.ListToolsResponse 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.ListToolsResponse 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.ListToolsResponse 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.ListToolsResponse 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 * [Tools.ListTools][google.cloud.dialogflow.cx.v3beta1.Tools.ListTools]. * </pre> * * Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ListToolsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.ListToolsResponse) com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.cx.v3beta1.ToolProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListToolsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.cx.v3beta1.ToolProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListToolsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.class, com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (toolsBuilder_ == null) { tools_ = java.util.Collections.emptyList(); } else { tools_ = null; toolsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.cx.v3beta1.ToolProto .internal_static_google_cloud_dialogflow_cx_v3beta1_ListToolsResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse build() { com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse buildPartial() { com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse result = new com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse result) { if (toolsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { tools_ = java.util.Collections.unmodifiableList(tools_); bitField0_ = (bitField0_ & ~0x00000001); } result.tools_ = tools_; } else { result.tools_ = toolsBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse 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.dialogflow.cx.v3beta1.ListToolsResponse) { return mergeFrom((com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse other) { if (other == com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse.getDefaultInstance()) return this; if (toolsBuilder_ == null) { if (!other.tools_.isEmpty()) { if (tools_.isEmpty()) { tools_ = other.tools_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureToolsIsMutable(); tools_.addAll(other.tools_); } onChanged(); } } else { if (!other.tools_.isEmpty()) { if (toolsBuilder_.isEmpty()) { toolsBuilder_.dispose(); toolsBuilder_ = null; tools_ = other.tools_; bitField0_ = (bitField0_ & ~0x00000001); toolsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getToolsFieldBuilder() : null; } else { toolsBuilder_.addAllMessages(other.tools_); } } } 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.dialogflow.cx.v3beta1.Tool m = input.readMessage( com.google.cloud.dialogflow.cx.v3beta1.Tool.parser(), extensionRegistry); if (toolsBuilder_ == null) { ensureToolsIsMutable(); tools_.add(m); } else { toolsBuilder_.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.dialogflow.cx.v3beta1.Tool> tools_ = java.util.Collections.emptyList(); private void ensureToolsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { tools_ = new java.util.ArrayList<com.google.cloud.dialogflow.cx.v3beta1.Tool>(tools_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Tool, com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder, com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder> toolsBuilder_; /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Tool> getToolsList() { if (toolsBuilder_ == null) { return java.util.Collections.unmodifiableList(tools_); } else { return toolsBuilder_.getMessageList(); } } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public int getToolsCount() { if (toolsBuilder_ == null) { return tools_.size(); } else { return toolsBuilder_.getCount(); } } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Tool getTools(int index) { if (toolsBuilder_ == null) { return tools_.get(index); } else { return toolsBuilder_.getMessage(index); } } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder setTools(int index, com.google.cloud.dialogflow.cx.v3beta1.Tool value) { if (toolsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureToolsIsMutable(); tools_.set(index, value); onChanged(); } else { toolsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder setTools( int index, com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder builderForValue) { if (toolsBuilder_ == null) { ensureToolsIsMutable(); tools_.set(index, builderForValue.build()); onChanged(); } else { toolsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder addTools(com.google.cloud.dialogflow.cx.v3beta1.Tool value) { if (toolsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureToolsIsMutable(); tools_.add(value); onChanged(); } else { toolsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder addTools(int index, com.google.cloud.dialogflow.cx.v3beta1.Tool value) { if (toolsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureToolsIsMutable(); tools_.add(index, value); onChanged(); } else { toolsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder addTools(com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder builderForValue) { if (toolsBuilder_ == null) { ensureToolsIsMutable(); tools_.add(builderForValue.build()); onChanged(); } else { toolsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder addTools( int index, com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder builderForValue) { if (toolsBuilder_ == null) { ensureToolsIsMutable(); tools_.add(index, builderForValue.build()); onChanged(); } else { toolsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder addAllTools( java.lang.Iterable<? extends com.google.cloud.dialogflow.cx.v3beta1.Tool> values) { if (toolsBuilder_ == null) { ensureToolsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tools_); onChanged(); } else { toolsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder clearTools() { if (toolsBuilder_ == null) { tools_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { toolsBuilder_.clear(); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public Builder removeTools(int index) { if (toolsBuilder_ == null) { ensureToolsIsMutable(); tools_.remove(index); onChanged(); } else { toolsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder getToolsBuilder(int index) { return getToolsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder getToolsOrBuilder(int index) { if (toolsBuilder_ == null) { return tools_.get(index); } else { return toolsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder> getToolsOrBuilderList() { if (toolsBuilder_ != null) { return toolsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(tools_); } } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder addToolsBuilder() { return getToolsFieldBuilder() .addBuilder(com.google.cloud.dialogflow.cx.v3beta1.Tool.getDefaultInstance()); } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder addToolsBuilder(int index) { return getToolsFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.cx.v3beta1.Tool.getDefaultInstance()); } /** * * * <pre> * The list of Tools. There will be a maximum number of items returned * based on the page_size field in the request. * </pre> * * <code>repeated .google.cloud.dialogflow.cx.v3beta1.Tool tools = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder> getToolsBuilderList() { return getToolsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Tool, com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder, com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder> getToolsFieldBuilder() { if (toolsBuilder_ == null) { toolsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.cx.v3beta1.Tool, com.google.cloud.dialogflow.cx.v3beta1.Tool.Builder, com.google.cloud.dialogflow.cx.v3beta1.ToolOrBuilder>( tools_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); tools_ = null; } return toolsBuilder_; } 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.dialogflow.cx.v3beta1.ListToolsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.ListToolsResponse) private static final com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse(); } public static com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListToolsResponse> PARSER = new com.google.protobuf.AbstractParser<ListToolsResponse>() { @java.lang.Override public ListToolsResponse 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<ListToolsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListToolsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.cx.v3beta1.ListToolsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,685
java-speech/proto-google-cloud-speech-v2/src/main/java/com/google/cloud/speech/v2/UpdateCustomClassRequest.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/speech/v2/cloud_speech.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.speech.v2; /** * * * <pre> * Request message for the * [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] method. * </pre> * * Protobuf type {@code google.cloud.speech.v2.UpdateCustomClassRequest} */ public final class UpdateCustomClassRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v2.UpdateCustomClassRequest) UpdateCustomClassRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateCustomClassRequest.newBuilder() to construct. private UpdateCustomClassRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateCustomClassRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateCustomClassRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdateCustomClassRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdateCustomClassRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.UpdateCustomClassRequest.class, com.google.cloud.speech.v2.UpdateCustomClassRequest.Builder.class); } private int bitField0_; public static final int CUSTOM_CLASS_FIELD_NUMBER = 1; private com.google.cloud.speech.v2.CustomClass customClass_; /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the customClass field is set. */ @java.lang.Override public boolean hasCustomClass() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The customClass. */ @java.lang.Override public com.google.cloud.speech.v2.CustomClass getCustomClass() { return customClass_ == null ? com.google.cloud.speech.v2.CustomClass.getDefaultInstance() : customClass_; } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.speech.v2.CustomClassOrBuilder getCustomClassOrBuilder() { return customClass_ == null ? com.google.cloud.speech.v2.CustomClass.getDefaultInstance() : customClass_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_ = false; /** * * * <pre> * If set, validate the request and preview the updated CustomClass, but do * not actually update it. * </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 (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getCustomClass()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateMask()); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getCustomClass()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask()); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.speech.v2.UpdateCustomClassRequest)) { return super.equals(obj); } com.google.cloud.speech.v2.UpdateCustomClassRequest other = (com.google.cloud.speech.v2.UpdateCustomClassRequest) obj; if (hasCustomClass() != other.hasCustomClass()) return false; if (hasCustomClass()) { if (!getCustomClass().equals(other.getCustomClass())) return false; } if (hasUpdateMask() != other.hasUpdateMask()) return false; if (hasUpdateMask()) { if (!getUpdateMask().equals(other.getUpdateMask())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasCustomClass()) { hash = (37 * hash) + CUSTOM_CLASS_FIELD_NUMBER; hash = (53 * hash) + getCustomClass().hashCode(); } if (hasUpdateMask()) { hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER; hash = (53 * hash) + getUpdateMask().hashCode(); } hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v2.UpdateCustomClassRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest 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.speech.v2.UpdateCustomClassRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest 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.speech.v2.UpdateCustomClassRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest 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.speech.v2.UpdateCustomClassRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest 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.speech.v2.UpdateCustomClassRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest 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.speech.v2.UpdateCustomClassRequest 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 the * [UpdateCustomClass][google.cloud.speech.v2.Speech.UpdateCustomClass] method. * </pre> * * Protobuf type {@code google.cloud.speech.v2.UpdateCustomClassRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v2.UpdateCustomClassRequest) com.google.cloud.speech.v2.UpdateCustomClassRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdateCustomClassRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdateCustomClassRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.UpdateCustomClassRequest.class, com.google.cloud.speech.v2.UpdateCustomClassRequest.Builder.class); } // Construct using com.google.cloud.speech.v2.UpdateCustomClassRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCustomClassFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; customClass_ = null; if (customClassBuilder_ != null) { customClassBuilder_.dispose(); customClassBuilder_ = null; } updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_UpdateCustomClassRequest_descriptor; } @java.lang.Override public com.google.cloud.speech.v2.UpdateCustomClassRequest getDefaultInstanceForType() { return com.google.cloud.speech.v2.UpdateCustomClassRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v2.UpdateCustomClassRequest build() { com.google.cloud.speech.v2.UpdateCustomClassRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v2.UpdateCustomClassRequest buildPartial() { com.google.cloud.speech.v2.UpdateCustomClassRequest result = new com.google.cloud.speech.v2.UpdateCustomClassRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.speech.v2.UpdateCustomClassRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.customClass_ = customClassBuilder_ == null ? customClass_ : customClassBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.speech.v2.UpdateCustomClassRequest) { return mergeFrom((com.google.cloud.speech.v2.UpdateCustomClassRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v2.UpdateCustomClassRequest other) { if (other == com.google.cloud.speech.v2.UpdateCustomClassRequest.getDefaultInstance()) return this; if (other.hasCustomClass()) { mergeCustomClass(other.getCustomClass()); } if (other.hasUpdateMask()) { mergeUpdateMask(other.getUpdateMask()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getCustomClassFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 32: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.cloud.speech.v2.CustomClass customClass_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.speech.v2.CustomClass, com.google.cloud.speech.v2.CustomClass.Builder, com.google.cloud.speech.v2.CustomClassOrBuilder> customClassBuilder_; /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the customClass field is set. */ public boolean hasCustomClass() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The customClass. */ public com.google.cloud.speech.v2.CustomClass getCustomClass() { if (customClassBuilder_ == null) { return customClass_ == null ? com.google.cloud.speech.v2.CustomClass.getDefaultInstance() : customClass_; } else { return customClassBuilder_.getMessage(); } } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setCustomClass(com.google.cloud.speech.v2.CustomClass value) { if (customClassBuilder_ == null) { if (value == null) { throw new NullPointerException(); } customClass_ = value; } else { customClassBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setCustomClass(com.google.cloud.speech.v2.CustomClass.Builder builderForValue) { if (customClassBuilder_ == null) { customClass_ = builderForValue.build(); } else { customClassBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeCustomClass(com.google.cloud.speech.v2.CustomClass value) { if (customClassBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && customClass_ != null && customClass_ != com.google.cloud.speech.v2.CustomClass.getDefaultInstance()) { getCustomClassBuilder().mergeFrom(value); } else { customClass_ = value; } } else { customClassBuilder_.mergeFrom(value); } if (customClass_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearCustomClass() { bitField0_ = (bitField0_ & ~0x00000001); customClass_ = null; if (customClassBuilder_ != null) { customClassBuilder_.dispose(); customClassBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.speech.v2.CustomClass.Builder getCustomClassBuilder() { bitField0_ |= 0x00000001; onChanged(); return getCustomClassFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.speech.v2.CustomClassOrBuilder getCustomClassOrBuilder() { if (customClassBuilder_ != null) { return customClassBuilder_.getMessageOrBuilder(); } else { return customClass_ == null ? com.google.cloud.speech.v2.CustomClass.getDefaultInstance() : customClass_; } } /** * * * <pre> * Required. The CustomClass to update. * * The CustomClass's `name` field is used to identify the CustomClass to * update. Format: * `projects/{project}/locations/{location}/customClasses/{custom_class}`. * </pre> * * <code> * .google.cloud.speech.v2.CustomClass custom_class = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.speech.v2.CustomClass, com.google.cloud.speech.v2.CustomClass.Builder, com.google.cloud.speech.v2.CustomClassOrBuilder> getCustomClassFieldBuilder() { if (customClassBuilder_ == null) { customClassBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.speech.v2.CustomClass, com.google.cloud.speech.v2.CustomClass.Builder, com.google.cloud.speech.v2.CustomClassOrBuilder>( getCustomClass(), getParentForChildren(), isClean()); customClass_ = null; } return customClassBuilder_; } private com.google.protobuf.FieldMask updateMask_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_; /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * The list of fields to be updated. If empty, all fields are considered for * update. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } private boolean validateOnly_; /** * * * <pre> * If set, validate the request and preview the updated CustomClass, but do * not actually update it. * </pre> * * <code>bool validate_only = 4;</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * If set, validate the request and preview the updated CustomClass, but do * not actually update it. * </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_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * If set, validate the request and preview the updated CustomClass, but do * not actually update it. * </pre> * * <code>bool validate_only = 4;</code> * * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.speech.v2.UpdateCustomClassRequest) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v2.UpdateCustomClassRequest) private static final com.google.cloud.speech.v2.UpdateCustomClassRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v2.UpdateCustomClassRequest(); } public static com.google.cloud.speech.v2.UpdateCustomClassRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateCustomClassRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateCustomClassRequest>() { @java.lang.Override public UpdateCustomClassRequest 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<UpdateCustomClassRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateCustomClassRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v2.UpdateCustomClassRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,710
java-meet/proto-google-cloud-meet-v2/src/main/java/com/google/apps/meet/v2/ListConferenceRecordsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/meet/v2/service.proto // Protobuf Java Version: 3.25.8 package com.google.apps.meet.v2; /** * * * <pre> * Response of ListConferenceRecords method. * </pre> * * Protobuf type {@code google.apps.meet.v2.ListConferenceRecordsResponse} */ public final class ListConferenceRecordsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.meet.v2.ListConferenceRecordsResponse) ListConferenceRecordsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListConferenceRecordsResponse.newBuilder() to construct. private ListConferenceRecordsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListConferenceRecordsResponse() { conferenceRecords_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListConferenceRecordsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2.ServiceProto .internal_static_google_apps_meet_v2_ListConferenceRecordsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2.ServiceProto .internal_static_google_apps_meet_v2_ListConferenceRecordsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2.ListConferenceRecordsResponse.class, com.google.apps.meet.v2.ListConferenceRecordsResponse.Builder.class); } public static final int CONFERENCE_RECORDS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.apps.meet.v2.ConferenceRecord> conferenceRecords_; /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ @java.lang.Override public java.util.List<com.google.apps.meet.v2.ConferenceRecord> getConferenceRecordsList() { return conferenceRecords_; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.apps.meet.v2.ConferenceRecordOrBuilder> getConferenceRecordsOrBuilderList() { return conferenceRecords_; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ @java.lang.Override public int getConferenceRecordsCount() { return conferenceRecords_.size(); } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ @java.lang.Override public com.google.apps.meet.v2.ConferenceRecord getConferenceRecords(int index) { return conferenceRecords_.get(index); } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ @java.lang.Override public com.google.apps.meet.v2.ConferenceRecordOrBuilder getConferenceRecordsOrBuilder( int index) { return conferenceRecords_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < conferenceRecords_.size(); i++) { output.writeMessage(1, conferenceRecords_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < conferenceRecords_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, conferenceRecords_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.apps.meet.v2.ListConferenceRecordsResponse)) { return super.equals(obj); } com.google.apps.meet.v2.ListConferenceRecordsResponse other = (com.google.apps.meet.v2.ListConferenceRecordsResponse) obj; if (!getConferenceRecordsList().equals(other.getConferenceRecordsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getConferenceRecordsCount() > 0) { hash = (37 * hash) + CONFERENCE_RECORDS_FIELD_NUMBER; hash = (53 * hash) + getConferenceRecordsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.apps.meet.v2.ListConferenceRecordsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response of ListConferenceRecords method. * </pre> * * Protobuf type {@code google.apps.meet.v2.ListConferenceRecordsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.meet.v2.ListConferenceRecordsResponse) com.google.apps.meet.v2.ListConferenceRecordsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2.ServiceProto .internal_static_google_apps_meet_v2_ListConferenceRecordsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2.ServiceProto .internal_static_google_apps_meet_v2_ListConferenceRecordsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2.ListConferenceRecordsResponse.class, com.google.apps.meet.v2.ListConferenceRecordsResponse.Builder.class); } // Construct using com.google.apps.meet.v2.ListConferenceRecordsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (conferenceRecordsBuilder_ == null) { conferenceRecords_ = java.util.Collections.emptyList(); } else { conferenceRecords_ = null; conferenceRecordsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.meet.v2.ServiceProto .internal_static_google_apps_meet_v2_ListConferenceRecordsResponse_descriptor; } @java.lang.Override public com.google.apps.meet.v2.ListConferenceRecordsResponse getDefaultInstanceForType() { return com.google.apps.meet.v2.ListConferenceRecordsResponse.getDefaultInstance(); } @java.lang.Override public com.google.apps.meet.v2.ListConferenceRecordsResponse build() { com.google.apps.meet.v2.ListConferenceRecordsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.meet.v2.ListConferenceRecordsResponse buildPartial() { com.google.apps.meet.v2.ListConferenceRecordsResponse result = new com.google.apps.meet.v2.ListConferenceRecordsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.apps.meet.v2.ListConferenceRecordsResponse result) { if (conferenceRecordsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { conferenceRecords_ = java.util.Collections.unmodifiableList(conferenceRecords_); bitField0_ = (bitField0_ & ~0x00000001); } result.conferenceRecords_ = conferenceRecords_; } else { result.conferenceRecords_ = conferenceRecordsBuilder_.build(); } } private void buildPartial0(com.google.apps.meet.v2.ListConferenceRecordsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.apps.meet.v2.ListConferenceRecordsResponse) { return mergeFrom((com.google.apps.meet.v2.ListConferenceRecordsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.meet.v2.ListConferenceRecordsResponse other) { if (other == com.google.apps.meet.v2.ListConferenceRecordsResponse.getDefaultInstance()) return this; if (conferenceRecordsBuilder_ == null) { if (!other.conferenceRecords_.isEmpty()) { if (conferenceRecords_.isEmpty()) { conferenceRecords_ = other.conferenceRecords_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureConferenceRecordsIsMutable(); conferenceRecords_.addAll(other.conferenceRecords_); } onChanged(); } } else { if (!other.conferenceRecords_.isEmpty()) { if (conferenceRecordsBuilder_.isEmpty()) { conferenceRecordsBuilder_.dispose(); conferenceRecordsBuilder_ = null; conferenceRecords_ = other.conferenceRecords_; bitField0_ = (bitField0_ & ~0x00000001); conferenceRecordsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getConferenceRecordsFieldBuilder() : null; } else { conferenceRecordsBuilder_.addAllMessages(other.conferenceRecords_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.apps.meet.v2.ConferenceRecord m = input.readMessage( com.google.apps.meet.v2.ConferenceRecord.parser(), extensionRegistry); if (conferenceRecordsBuilder_ == null) { ensureConferenceRecordsIsMutable(); conferenceRecords_.add(m); } else { conferenceRecordsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.apps.meet.v2.ConferenceRecord> conferenceRecords_ = java.util.Collections.emptyList(); private void ensureConferenceRecordsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { conferenceRecords_ = new java.util.ArrayList<com.google.apps.meet.v2.ConferenceRecord>(conferenceRecords_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.apps.meet.v2.ConferenceRecord, com.google.apps.meet.v2.ConferenceRecord.Builder, com.google.apps.meet.v2.ConferenceRecordOrBuilder> conferenceRecordsBuilder_; /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public java.util.List<com.google.apps.meet.v2.ConferenceRecord> getConferenceRecordsList() { if (conferenceRecordsBuilder_ == null) { return java.util.Collections.unmodifiableList(conferenceRecords_); } else { return conferenceRecordsBuilder_.getMessageList(); } } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public int getConferenceRecordsCount() { if (conferenceRecordsBuilder_ == null) { return conferenceRecords_.size(); } else { return conferenceRecordsBuilder_.getCount(); } } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public com.google.apps.meet.v2.ConferenceRecord getConferenceRecords(int index) { if (conferenceRecordsBuilder_ == null) { return conferenceRecords_.get(index); } else { return conferenceRecordsBuilder_.getMessage(index); } } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder setConferenceRecords(int index, com.google.apps.meet.v2.ConferenceRecord value) { if (conferenceRecordsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConferenceRecordsIsMutable(); conferenceRecords_.set(index, value); onChanged(); } else { conferenceRecordsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder setConferenceRecords( int index, com.google.apps.meet.v2.ConferenceRecord.Builder builderForValue) { if (conferenceRecordsBuilder_ == null) { ensureConferenceRecordsIsMutable(); conferenceRecords_.set(index, builderForValue.build()); onChanged(); } else { conferenceRecordsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder addConferenceRecords(com.google.apps.meet.v2.ConferenceRecord value) { if (conferenceRecordsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConferenceRecordsIsMutable(); conferenceRecords_.add(value); onChanged(); } else { conferenceRecordsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder addConferenceRecords(int index, com.google.apps.meet.v2.ConferenceRecord value) { if (conferenceRecordsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureConferenceRecordsIsMutable(); conferenceRecords_.add(index, value); onChanged(); } else { conferenceRecordsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder addConferenceRecords( com.google.apps.meet.v2.ConferenceRecord.Builder builderForValue) { if (conferenceRecordsBuilder_ == null) { ensureConferenceRecordsIsMutable(); conferenceRecords_.add(builderForValue.build()); onChanged(); } else { conferenceRecordsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder addConferenceRecords( int index, com.google.apps.meet.v2.ConferenceRecord.Builder builderForValue) { if (conferenceRecordsBuilder_ == null) { ensureConferenceRecordsIsMutable(); conferenceRecords_.add(index, builderForValue.build()); onChanged(); } else { conferenceRecordsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder addAllConferenceRecords( java.lang.Iterable<? extends com.google.apps.meet.v2.ConferenceRecord> values) { if (conferenceRecordsBuilder_ == null) { ensureConferenceRecordsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, conferenceRecords_); onChanged(); } else { conferenceRecordsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder clearConferenceRecords() { if (conferenceRecordsBuilder_ == null) { conferenceRecords_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { conferenceRecordsBuilder_.clear(); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public Builder removeConferenceRecords(int index) { if (conferenceRecordsBuilder_ == null) { ensureConferenceRecordsIsMutable(); conferenceRecords_.remove(index); onChanged(); } else { conferenceRecordsBuilder_.remove(index); } return this; } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public com.google.apps.meet.v2.ConferenceRecord.Builder getConferenceRecordsBuilder(int index) { return getConferenceRecordsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public com.google.apps.meet.v2.ConferenceRecordOrBuilder getConferenceRecordsOrBuilder( int index) { if (conferenceRecordsBuilder_ == null) { return conferenceRecords_.get(index); } else { return conferenceRecordsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public java.util.List<? extends com.google.apps.meet.v2.ConferenceRecordOrBuilder> getConferenceRecordsOrBuilderList() { if (conferenceRecordsBuilder_ != null) { return conferenceRecordsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(conferenceRecords_); } } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public com.google.apps.meet.v2.ConferenceRecord.Builder addConferenceRecordsBuilder() { return getConferenceRecordsFieldBuilder() .addBuilder(com.google.apps.meet.v2.ConferenceRecord.getDefaultInstance()); } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public com.google.apps.meet.v2.ConferenceRecord.Builder addConferenceRecordsBuilder(int index) { return getConferenceRecordsFieldBuilder() .addBuilder(index, com.google.apps.meet.v2.ConferenceRecord.getDefaultInstance()); } /** * * * <pre> * List of conferences in one page. * </pre> * * <code>repeated .google.apps.meet.v2.ConferenceRecord conference_records = 1;</code> */ public java.util.List<com.google.apps.meet.v2.ConferenceRecord.Builder> getConferenceRecordsBuilderList() { return getConferenceRecordsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.apps.meet.v2.ConferenceRecord, com.google.apps.meet.v2.ConferenceRecord.Builder, com.google.apps.meet.v2.ConferenceRecordOrBuilder> getConferenceRecordsFieldBuilder() { if (conferenceRecordsBuilder_ == null) { conferenceRecordsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.apps.meet.v2.ConferenceRecord, com.google.apps.meet.v2.ConferenceRecord.Builder, com.google.apps.meet.v2.ConferenceRecordOrBuilder>( conferenceRecords_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); conferenceRecords_ = null; } return conferenceRecordsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Token to be circulated back for further List call if current List does NOT * include all the Conferences. Unset if all conferences have been returned. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.apps.meet.v2.ListConferenceRecordsResponse) } // @@protoc_insertion_point(class_scope:google.apps.meet.v2.ListConferenceRecordsResponse) private static final com.google.apps.meet.v2.ListConferenceRecordsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.meet.v2.ListConferenceRecordsResponse(); } public static com.google.apps.meet.v2.ListConferenceRecordsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListConferenceRecordsResponse> PARSER = new com.google.protobuf.AbstractParser<ListConferenceRecordsResponse>() { @java.lang.Override public ListConferenceRecordsResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<ListConferenceRecordsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListConferenceRecordsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.meet.v2.ListConferenceRecordsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,722
java-talent/proto-google-cloud-talent-v4beta1/src/main/java/com/google/cloud/talent/v4beta1/UpdateTenantRequest.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/talent/v4beta1/tenant_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.talent.v4beta1; /** * * * <pre> * Request for updating a specified tenant. * </pre> * * Protobuf type {@code google.cloud.talent.v4beta1.UpdateTenantRequest} */ public final class UpdateTenantRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.talent.v4beta1.UpdateTenantRequest) UpdateTenantRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateTenantRequest.newBuilder() to construct. private UpdateTenantRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateTenantRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateTenantRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.talent.v4beta1.TenantServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateTenantRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.talent.v4beta1.TenantServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateTenantRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.talent.v4beta1.UpdateTenantRequest.class, com.google.cloud.talent.v4beta1.UpdateTenantRequest.Builder.class); } private int bitField0_; public static final int TENANT_FIELD_NUMBER = 1; private com.google.cloud.talent.v4beta1.Tenant tenant_; /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code>.google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tenant field is set. */ @java.lang.Override public boolean hasTenant() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code>.google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tenant. */ @java.lang.Override public com.google.cloud.talent.v4beta1.Tenant getTenant() { return tenant_ == null ? com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance() : tenant_; } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code>.google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.talent.v4beta1.TenantOrBuilder getTenantOrBuilder() { return tenant_ == null ? com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance() : tenant_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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, getTenant()); } 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, getTenant()); } 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.talent.v4beta1.UpdateTenantRequest)) { return super.equals(obj); } com.google.cloud.talent.v4beta1.UpdateTenantRequest other = (com.google.cloud.talent.v4beta1.UpdateTenantRequest) obj; if (hasTenant() != other.hasTenant()) return false; if (hasTenant()) { if (!getTenant().equals(other.getTenant())) 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 (hasTenant()) { hash = (37 * hash) + TENANT_FIELD_NUMBER; hash = (53 * hash) + getTenant().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.talent.v4beta1.UpdateTenantRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest 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.talent.v4beta1.UpdateTenantRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest 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.talent.v4beta1.UpdateTenantRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest 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.talent.v4beta1.UpdateTenantRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest 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.talent.v4beta1.UpdateTenantRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest 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.talent.v4beta1.UpdateTenantRequest 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 updating a specified tenant. * </pre> * * Protobuf type {@code google.cloud.talent.v4beta1.UpdateTenantRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.talent.v4beta1.UpdateTenantRequest) com.google.cloud.talent.v4beta1.UpdateTenantRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.talent.v4beta1.TenantServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateTenantRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.talent.v4beta1.TenantServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateTenantRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.talent.v4beta1.UpdateTenantRequest.class, com.google.cloud.talent.v4beta1.UpdateTenantRequest.Builder.class); } // Construct using com.google.cloud.talent.v4beta1.UpdateTenantRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getTenantFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; tenant_ = null; if (tenantBuilder_ != null) { tenantBuilder_.dispose(); tenantBuilder_ = 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.talent.v4beta1.TenantServiceProto .internal_static_google_cloud_talent_v4beta1_UpdateTenantRequest_descriptor; } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateTenantRequest getDefaultInstanceForType() { return com.google.cloud.talent.v4beta1.UpdateTenantRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateTenantRequest build() { com.google.cloud.talent.v4beta1.UpdateTenantRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateTenantRequest buildPartial() { com.google.cloud.talent.v4beta1.UpdateTenantRequest result = new com.google.cloud.talent.v4beta1.UpdateTenantRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.talent.v4beta1.UpdateTenantRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.tenant_ = tenantBuilder_ == null ? tenant_ : tenantBuilder_.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.talent.v4beta1.UpdateTenantRequest) { return mergeFrom((com.google.cloud.talent.v4beta1.UpdateTenantRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.talent.v4beta1.UpdateTenantRequest other) { if (other == com.google.cloud.talent.v4beta1.UpdateTenantRequest.getDefaultInstance()) return this; if (other.hasTenant()) { mergeTenant(other.getTenant()); } 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(getTenantFieldBuilder().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.talent.v4beta1.Tenant tenant_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.talent.v4beta1.Tenant, com.google.cloud.talent.v4beta1.Tenant.Builder, com.google.cloud.talent.v4beta1.TenantOrBuilder> tenantBuilder_; /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the tenant field is set. */ public boolean hasTenant() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The tenant. */ public com.google.cloud.talent.v4beta1.Tenant getTenant() { if (tenantBuilder_ == null) { return tenant_ == null ? com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance() : tenant_; } else { return tenantBuilder_.getMessage(); } } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTenant(com.google.cloud.talent.v4beta1.Tenant value) { if (tenantBuilder_ == null) { if (value == null) { throw new NullPointerException(); } tenant_ = value; } else { tenantBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setTenant(com.google.cloud.talent.v4beta1.Tenant.Builder builderForValue) { if (tenantBuilder_ == null) { tenant_ = builderForValue.build(); } else { tenantBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeTenant(com.google.cloud.talent.v4beta1.Tenant value) { if (tenantBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && tenant_ != null && tenant_ != com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance()) { getTenantBuilder().mergeFrom(value); } else { tenant_ = value; } } else { tenantBuilder_.mergeFrom(value); } if (tenant_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearTenant() { bitField0_ = (bitField0_ & ~0x00000001); tenant_ = null; if (tenantBuilder_ != null) { tenantBuilder_.dispose(); tenantBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4beta1.Tenant.Builder getTenantBuilder() { bitField0_ |= 0x00000001; onChanged(); return getTenantFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.talent.v4beta1.TenantOrBuilder getTenantOrBuilder() { if (tenantBuilder_ != null) { return tenantBuilder_.getMessageOrBuilder(); } else { return tenant_ == null ? com.google.cloud.talent.v4beta1.Tenant.getDefaultInstance() : tenant_; } } /** * * * <pre> * Required. The tenant resource to replace the current resource in the * system. * </pre> * * <code> * .google.cloud.talent.v4beta1.Tenant tenant = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.talent.v4beta1.Tenant, com.google.cloud.talent.v4beta1.Tenant.Builder, com.google.cloud.talent.v4beta1.TenantOrBuilder> getTenantFieldBuilder() { if (tenantBuilder_ == null) { tenantBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.talent.v4beta1.Tenant, com.google.cloud.talent.v4beta1.Tenant.Builder, com.google.cloud.talent.v4beta1.TenantOrBuilder>( getTenant(), getParentForChildren(), isClean()); tenant_ = null; } return tenantBuilder_; } 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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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> * Strongly recommended for the best service experience. * * If * [update_mask][google.cloud.talent.v4beta1.UpdateTenantRequest.update_mask] * is provided, only the specified fields in * [tenant][google.cloud.talent.v4beta1.UpdateTenantRequest.tenant] are * updated. Otherwise all the fields are updated. * * A field mask to specify the tenant fields to be updated. Only * top level fields of [Tenant][google.cloud.talent.v4beta1.Tenant] are * supported. * </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.talent.v4beta1.UpdateTenantRequest) } // @@protoc_insertion_point(class_scope:google.cloud.talent.v4beta1.UpdateTenantRequest) private static final com.google.cloud.talent.v4beta1.UpdateTenantRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.talent.v4beta1.UpdateTenantRequest(); } public static com.google.cloud.talent.v4beta1.UpdateTenantRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateTenantRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateTenantRequest>() { @java.lang.Override public UpdateTenantRequest 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<UpdateTenantRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateTenantRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.talent.v4beta1.UpdateTenantRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,646
java-vertexai/proto-google-cloud-vertexai-v1/src/main/java/com/google/cloud/vertexai/api/Content.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/vertexai/v1/content.proto // Protobuf Java Version: 3.25.3 package com.google.cloud.vertexai.api; /** * * * <pre> * The base structured datatype containing multi-part content of a message. * * A `Content` includes a `role` field designating the producer of the `Content` * and a `parts` field containing multi-part data that contains the content of * the message turn. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.Content} */ public final class Content extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vertexai.v1.Content) ContentOrBuilder { private static final long serialVersionUID = 0L; // Use Content.newBuilder() to construct. private Content(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private Content() { role_ = ""; parts_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new Content(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.ContentProto .internal_static_google_cloud_vertexai_v1_Content_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.ContentProto .internal_static_google_cloud_vertexai_v1_Content_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.Content.class, com.google.cloud.vertexai.api.Content.Builder.class); } public static final int ROLE_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object role_ = ""; /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The role. */ @java.lang.Override public java.lang.String getRole() { java.lang.Object ref = role_; 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(); role_ = s; return s; } } /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for role. */ @java.lang.Override public com.google.protobuf.ByteString getRoleBytes() { java.lang.Object ref = role_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); role_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PARTS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.cloud.vertexai.api.Part> parts_; /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.vertexai.api.Part> getPartsList() { return parts_; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.vertexai.api.PartOrBuilder> getPartsOrBuilderList() { return parts_; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public int getPartsCount() { return parts_.size(); } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.vertexai.api.Part getParts(int index) { return parts_.get(index); } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.vertexai.api.PartOrBuilder getPartsOrBuilder(int index) { return parts_.get(index); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(role_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, role_); } for (int i = 0; i < parts_.size(); i++) { output.writeMessage(2, parts_.get(i)); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(role_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, role_); } for (int i = 0; i < parts_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, parts_.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.vertexai.api.Content)) { return super.equals(obj); } com.google.cloud.vertexai.api.Content other = (com.google.cloud.vertexai.api.Content) obj; if (!getRole().equals(other.getRole())) return false; if (!getPartsList().equals(other.getPartsList())) 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) + ROLE_FIELD_NUMBER; hash = (53 * hash) + getRole().hashCode(); if (getPartsCount() > 0) { hash = (37 * hash) + PARTS_FIELD_NUMBER; hash = (53 * hash) + getPartsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vertexai.api.Content parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.Content 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.vertexai.api.Content parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.Content 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.vertexai.api.Content parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.Content parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vertexai.api.Content parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.Content 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.vertexai.api.Content parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.Content 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.vertexai.api.Content parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.Content 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.vertexai.api.Content 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 base structured datatype containing multi-part content of a message. * * A `Content` includes a `role` field designating the producer of the `Content` * and a `parts` field containing multi-part data that contains the content of * the message turn. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.Content} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vertexai.v1.Content) com.google.cloud.vertexai.api.ContentOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.ContentProto .internal_static_google_cloud_vertexai_v1_Content_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.ContentProto .internal_static_google_cloud_vertexai_v1_Content_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.Content.class, com.google.cloud.vertexai.api.Content.Builder.class); } // Construct using com.google.cloud.vertexai.api.Content.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; role_ = ""; if (partsBuilder_ == null) { parts_ = java.util.Collections.emptyList(); } else { parts_ = null; partsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vertexai.api.ContentProto .internal_static_google_cloud_vertexai_v1_Content_descriptor; } @java.lang.Override public com.google.cloud.vertexai.api.Content getDefaultInstanceForType() { return com.google.cloud.vertexai.api.Content.getDefaultInstance(); } @java.lang.Override public com.google.cloud.vertexai.api.Content build() { com.google.cloud.vertexai.api.Content result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vertexai.api.Content buildPartial() { com.google.cloud.vertexai.api.Content result = new com.google.cloud.vertexai.api.Content(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.cloud.vertexai.api.Content result) { if (partsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { parts_ = java.util.Collections.unmodifiableList(parts_); bitField0_ = (bitField0_ & ~0x00000002); } result.parts_ = parts_; } else { result.parts_ = partsBuilder_.build(); } } private void buildPartial0(com.google.cloud.vertexai.api.Content result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.role_ = role_; } } @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.vertexai.api.Content) { return mergeFrom((com.google.cloud.vertexai.api.Content) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.vertexai.api.Content other) { if (other == com.google.cloud.vertexai.api.Content.getDefaultInstance()) return this; if (!other.getRole().isEmpty()) { role_ = other.role_; bitField0_ |= 0x00000001; onChanged(); } if (partsBuilder_ == null) { if (!other.parts_.isEmpty()) { if (parts_.isEmpty()) { parts_ = other.parts_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensurePartsIsMutable(); parts_.addAll(other.parts_); } onChanged(); } } else { if (!other.parts_.isEmpty()) { if (partsBuilder_.isEmpty()) { partsBuilder_.dispose(); partsBuilder_ = null; parts_ = other.parts_; bitField0_ = (bitField0_ & ~0x00000002); partsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getPartsFieldBuilder() : null; } else { partsBuilder_.addAllMessages(other.parts_); } } } 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: { role_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.cloud.vertexai.api.Part m = input.readMessage( com.google.cloud.vertexai.api.Part.parser(), extensionRegistry); if (partsBuilder_ == null) { ensurePartsIsMutable(); parts_.add(m); } else { partsBuilder_.addMessage(m); } break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object role_ = ""; /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The role. */ public java.lang.String getRole() { java.lang.Object ref = role_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); role_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for role. */ public com.google.protobuf.ByteString getRoleBytes() { java.lang.Object ref = role_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); role_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The role to set. * @return This builder for chaining. */ public Builder setRole(java.lang.String value) { if (value == null) { throw new NullPointerException(); } role_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearRole() { role_ = getDefaultInstance().getRole(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Optional. The producer of the content. Must be either 'user' or 'model'. * * Useful to set for multi-turn conversations, otherwise can be left blank * or unset. * </pre> * * <code>string role = 1 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for role to set. * @return This builder for chaining. */ public Builder setRoleBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); role_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List<com.google.cloud.vertexai.api.Part> parts_ = java.util.Collections.emptyList(); private void ensurePartsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { parts_ = new java.util.ArrayList<com.google.cloud.vertexai.api.Part>(parts_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vertexai.api.Part, com.google.cloud.vertexai.api.Part.Builder, com.google.cloud.vertexai.api.PartOrBuilder> partsBuilder_; /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.vertexai.api.Part> getPartsList() { if (partsBuilder_ == null) { return java.util.Collections.unmodifiableList(parts_); } else { return partsBuilder_.getMessageList(); } } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public int getPartsCount() { if (partsBuilder_ == null) { return parts_.size(); } else { return partsBuilder_.getCount(); } } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vertexai.api.Part getParts(int index) { if (partsBuilder_ == null) { return parts_.get(index); } else { return partsBuilder_.getMessage(index); } } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setParts(int index, com.google.cloud.vertexai.api.Part value) { if (partsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePartsIsMutable(); parts_.set(index, value); onChanged(); } else { partsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setParts(int index, com.google.cloud.vertexai.api.Part.Builder builderForValue) { if (partsBuilder_ == null) { ensurePartsIsMutable(); parts_.set(index, builderForValue.build()); onChanged(); } else { partsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addParts(com.google.cloud.vertexai.api.Part value) { if (partsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePartsIsMutable(); parts_.add(value); onChanged(); } else { partsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addParts(int index, com.google.cloud.vertexai.api.Part value) { if (partsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensurePartsIsMutable(); parts_.add(index, value); onChanged(); } else { partsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addParts(com.google.cloud.vertexai.api.Part.Builder builderForValue) { if (partsBuilder_ == null) { ensurePartsIsMutable(); parts_.add(builderForValue.build()); onChanged(); } else { partsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addParts(int index, com.google.cloud.vertexai.api.Part.Builder builderForValue) { if (partsBuilder_ == null) { ensurePartsIsMutable(); parts_.add(index, builderForValue.build()); onChanged(); } else { partsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder addAllParts( java.lang.Iterable<? extends com.google.cloud.vertexai.api.Part> values) { if (partsBuilder_ == null) { ensurePartsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, parts_); onChanged(); } else { partsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearParts() { if (partsBuilder_ == null) { parts_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { partsBuilder_.clear(); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder removeParts(int index) { if (partsBuilder_ == null) { ensurePartsIsMutable(); parts_.remove(index); onChanged(); } else { partsBuilder_.remove(index); } return this; } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vertexai.api.Part.Builder getPartsBuilder(int index) { return getPartsFieldBuilder().getBuilder(index); } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vertexai.api.PartOrBuilder getPartsOrBuilder(int index) { if (partsBuilder_ == null) { return parts_.get(index); } else { return partsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<? extends com.google.cloud.vertexai.api.PartOrBuilder> getPartsOrBuilderList() { if (partsBuilder_ != null) { return partsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(parts_); } } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vertexai.api.Part.Builder addPartsBuilder() { return getPartsFieldBuilder() .addBuilder(com.google.cloud.vertexai.api.Part.getDefaultInstance()); } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.vertexai.api.Part.Builder addPartsBuilder(int index) { return getPartsFieldBuilder() .addBuilder(index, com.google.cloud.vertexai.api.Part.getDefaultInstance()); } /** * * * <pre> * Required. Ordered `Parts` that constitute a single message. Parts may have * different IANA MIME types. * </pre> * * <code> * repeated .google.cloud.vertexai.v1.Part parts = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public java.util.List<com.google.cloud.vertexai.api.Part.Builder> getPartsBuilderList() { return getPartsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vertexai.api.Part, com.google.cloud.vertexai.api.Part.Builder, com.google.cloud.vertexai.api.PartOrBuilder> getPartsFieldBuilder() { if (partsBuilder_ == null) { partsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vertexai.api.Part, com.google.cloud.vertexai.api.Part.Builder, com.google.cloud.vertexai.api.PartOrBuilder>( parts_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); parts_ = null; } return partsBuilder_; } @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.vertexai.v1.Content) } // @@protoc_insertion_point(class_scope:google.cloud.vertexai.v1.Content) private static final com.google.cloud.vertexai.api.Content DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vertexai.api.Content(); } public static com.google.cloud.vertexai.api.Content getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<Content> PARSER = new com.google.protobuf.AbstractParser<Content>() { @java.lang.Override public Content 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<Content> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<Content> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vertexai.api.Content getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,690
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/FetchExamplesResponse.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> * Response message for * [ExampleStoreService.FetchExamples][google.cloud.aiplatform.v1beta1.ExampleStoreService.FetchExamples]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.FetchExamplesResponse} */ public final class FetchExamplesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.FetchExamplesResponse) FetchExamplesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use FetchExamplesResponse.newBuilder() to construct. private FetchExamplesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private FetchExamplesResponse() { examples_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new FetchExamplesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto .internal_static_google_cloud_aiplatform_v1beta1_FetchExamplesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto .internal_static_google_cloud_aiplatform_v1beta1_FetchExamplesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.class, com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.Builder.class); } public static final int EXAMPLES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.aiplatform.v1beta1.Example> examples_; /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.aiplatform.v1beta1.Example> getExamplesList() { return examples_; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ExampleOrBuilder> getExamplesOrBuilderList() { return examples_; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ @java.lang.Override public int getExamplesCount() { return examples_.size(); } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.Example getExamples(int index) { return examples_.get(index); } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ @java.lang.Override public com.google.cloud.aiplatform.v1beta1.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, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates 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 < 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.aiplatform.v1beta1.FetchExamplesResponse)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse other = (com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse) 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.aiplatform.v1beta1.FetchExamplesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse 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.FetchExamplesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse 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.FetchExamplesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse 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.FetchExamplesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse 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.FetchExamplesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse 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.FetchExamplesResponse 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.FetchExamplesResponse 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.FetchExamplesResponse 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 * [ExampleStoreService.FetchExamples][google.cloud.aiplatform.v1beta1.ExampleStoreService.FetchExamples]. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1beta1.FetchExamplesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.FetchExamplesResponse) com.google.cloud.aiplatform.v1beta1.FetchExamplesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto .internal_static_google_cloud_aiplatform_v1beta1_FetchExamplesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto .internal_static_google_cloud_aiplatform_v1beta1_FetchExamplesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.class, com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.Builder.class); } // Construct using com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.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.aiplatform.v1beta1.ExampleStoreServiceProto .internal_static_google_cloud_aiplatform_v1beta1_FetchExamplesResponse_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse build() { com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse buildPartial() { com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse result = new com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse 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.aiplatform.v1beta1.FetchExamplesResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse) { return mergeFrom((com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse other) { if (other == com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse.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.aiplatform.v1beta1.Example m = input.readMessage( com.google.cloud.aiplatform.v1beta1.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.aiplatform.v1beta1.Example> examples_ = java.util.Collections.emptyList(); private void ensureExamplesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { examples_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Example>(examples_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Example, com.google.cloud.aiplatform.v1beta1.Example.Builder, com.google.cloud.aiplatform.v1beta1.ExampleOrBuilder> examplesBuilder_; /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.Example> getExamplesList() { if (examplesBuilder_ == null) { return java.util.Collections.unmodifiableList(examples_); } else { return examplesBuilder_.getMessageList(); } } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public int getExamplesCount() { if (examplesBuilder_ == null) { return examples_.size(); } else { return examplesBuilder_.getCount(); } } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Example getExamples(int index) { if (examplesBuilder_ == null) { return examples_.get(index); } else { return examplesBuilder_.getMessage(index); } } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder setExamples(int index, com.google.cloud.aiplatform.v1beta1.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 examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder setExamples( int index, com.google.cloud.aiplatform.v1beta1.Example.Builder builderForValue) { if (examplesBuilder_ == null) { ensureExamplesIsMutable(); examples_.set(index, builderForValue.build()); onChanged(); } else { examplesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder addExamples(com.google.cloud.aiplatform.v1beta1.Example value) { if (examplesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExamplesIsMutable(); examples_.add(value); onChanged(); } else { examplesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder addExamples(int index, com.google.cloud.aiplatform.v1beta1.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 examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder addExamples( com.google.cloud.aiplatform.v1beta1.Example.Builder builderForValue) { if (examplesBuilder_ == null) { ensureExamplesIsMutable(); examples_.add(builderForValue.build()); onChanged(); } else { examplesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder addExamples( int index, com.google.cloud.aiplatform.v1beta1.Example.Builder builderForValue) { if (examplesBuilder_ == null) { ensureExamplesIsMutable(); examples_.add(index, builderForValue.build()); onChanged(); } else { examplesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public Builder addAllExamples( java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Example> values) { if (examplesBuilder_ == null) { ensureExamplesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, examples_); onChanged(); } else { examplesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.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 examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.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 examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Example.Builder getExamplesBuilder(int index) { return getExamplesFieldBuilder().getBuilder(index); } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.ExampleOrBuilder getExamplesOrBuilder(int index) { if (examplesBuilder_ == null) { return examples_.get(index); } else { return examplesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ExampleOrBuilder> getExamplesOrBuilderList() { if (examplesBuilder_ != null) { return examplesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(examples_); } } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Example.Builder addExamplesBuilder() { return getExamplesFieldBuilder() .addBuilder(com.google.cloud.aiplatform.v1beta1.Example.getDefaultInstance()); } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public com.google.cloud.aiplatform.v1beta1.Example.Builder addExamplesBuilder(int index) { return getExamplesFieldBuilder() .addBuilder(index, com.google.cloud.aiplatform.v1beta1.Example.getDefaultInstance()); } /** * * * <pre> * The examples in the Example Store that satisfy the metadata filters. * </pre> * * <code>repeated .google.cloud.aiplatform.v1beta1.Example examples = 1;</code> */ public java.util.List<com.google.cloud.aiplatform.v1beta1.Example.Builder> getExamplesBuilderList() { return getExamplesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Example, com.google.cloud.aiplatform.v1beta1.Example.Builder, com.google.cloud.aiplatform.v1beta1.ExampleOrBuilder> getExamplesFieldBuilder() { if (examplesBuilder_ == null) { examplesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.aiplatform.v1beta1.Example, com.google.cloud.aiplatform.v1beta1.Example.Builder, com.google.cloud.aiplatform.v1beta1.ExampleOrBuilder>( examples_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); examples_ = null; } return examplesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as [FetchExamplesRequest.page_token][] to * retrieve the next page. Absence of this field indicates there are no * subsequent pages. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.FetchExamplesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.FetchExamplesResponse) private static final com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse(); } public static com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<FetchExamplesResponse> PARSER = new com.google.protobuf.AbstractParser<FetchExamplesResponse>() { @java.lang.Override public FetchExamplesResponse 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<FetchExamplesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<FetchExamplesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.FetchExamplesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/conscrypt
37,809
android/src/main/java/org/conscrypt/Platform.java
/* * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.conscrypt; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.os.Binder; import android.os.Build; import android.os.SystemClock; import android.system.Os; import android.util.Log; import dalvik.system.BlockGuard; import dalvik.system.CloseGuard; import org.conscrypt.NativeCrypto; import org.conscrypt.ct.CertificateTransparency; import org.conscrypt.metrics.CertificateTransparencyVerificationReason; import org.conscrypt.metrics.NoopStatsLog; import org.conscrypt.metrics.Source; import org.conscrypt.metrics.StatsLog; import org.conscrypt.metrics.StatsLogImpl; import java.io.FileDescriptor; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketImpl; import java.security.AlgorithmParameters; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Security; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.InvalidParameterSpecException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.net.ssl.SNIHostName; import javax.net.ssl.SNIMatcher; import javax.net.ssl.SNIServerName; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.StandardConstants; import javax.net.ssl.X509TrustManager; /** * Platform-specific methods for unbundled Android. */ @Internal final public class Platform { private static final String TAG = "Conscrypt"; static boolean DEPRECATED_TLS_V1 = true; static boolean ENABLED_TLS_V1 = false; private static boolean FILTERED_TLS_V1 = true; private static Method m_getCurveName; static { NativeCrypto.setTlsV1DeprecationStatus(DEPRECATED_TLS_V1, ENABLED_TLS_V1); try { m_getCurveName = ECParameterSpec.class.getDeclaredMethod("getCurveName"); m_getCurveName.setAccessible(true); } catch (Exception ignored) { //Ignored } } private Platform() {} public static void setup(boolean deprecatedTlsV1, boolean enabledTlsV1) { DEPRECATED_TLS_V1 = deprecatedTlsV1; ENABLED_TLS_V1 = enabledTlsV1; FILTERED_TLS_V1 = !enabledTlsV1; NativeCrypto.setTlsV1DeprecationStatus(DEPRECATED_TLS_V1, ENABLED_TLS_V1); } /** * Default name used in the {@link java.security.Security JCE system} by {@code OpenSSLProvider} * if the default constructor is used. */ public static String getDefaultProviderName() { return "Conscrypt"; } static boolean provideTrustManagerByDefault() { return false; } public static FileDescriptor getFileDescriptor(Socket s) { try { Field f_impl = Socket.class.getDeclaredField("impl"); f_impl.setAccessible(true); Object socketImpl = f_impl.get(s); Field f_fd = SocketImpl.class.getDeclaredField("fd"); f_fd.setAccessible(true); return (FileDescriptor) f_fd.get(socketImpl); } catch (Exception e) { throw new RuntimeException("Can't get FileDescriptor from socket", e); } } public static FileDescriptor getFileDescriptorFromSSLSocket(AbstractConscryptSocket socket) { return getFileDescriptor(socket); } public static String getCurveName(ECParameterSpec spec) { if (m_getCurveName == null) { return null; } try { return (String) m_getCurveName.invoke(spec); } catch (Exception e) { return null; } } public static void setCurveName(ECParameterSpec spec, String curveName) { try { Method setCurveName = spec.getClass().getDeclaredMethod("setCurveName", String.class); setCurveName.invoke(spec, curveName); } catch (Exception ignored) { //Ignored } } /** * Call Os.setsockoptTimeval via reflection. */ public static void setSocketWriteTimeout(Socket s, long timeoutMillis) throws SocketException { try { FileDescriptor fd = getFileDescriptor(s); if (fd == null || !fd.valid()) { // Mirror the behavior of platform sockets when calling methods with bad fds throw new SocketException("Socket closed"); } Class<?> c_structTimeval = getClass("android.system.StructTimeval", "libcore.io.StructTimeval"); if (c_structTimeval == null) { Log.w(TAG, "StructTimeval == null; not setting socket write timeout"); return; } Method m_fromMillis = c_structTimeval.getDeclaredMethod("fromMillis", long.class); if (m_fromMillis == null) { Log.w(TAG, "fromMillis == null; not setting socket write timeout"); return; } Object timeval = m_fromMillis.invoke(null, timeoutMillis); Class<?> c_Libcore = Class.forName("libcore.io.Libcore"); if (c_Libcore == null) { Log.w(TAG, "Libcore == null; not setting socket write timeout"); return; } Field f_os = c_Libcore.getField("os"); if (f_os == null) { Log.w(TAG, "os == null; not setting socket write timeout"); return; } Object instance_os = f_os.get(null); if (instance_os == null) { Log.w(TAG, "instance_os == null; not setting socket write timeout"); return; } Class<?> c_osConstants = getClass("android.system.OsConstants", "libcore.io.OsConstants"); if (c_osConstants == null) { Log.w(TAG, "OsConstants == null; not setting socket write timeout"); return; } Field f_SOL_SOCKET = c_osConstants.getField("SOL_SOCKET"); if (f_SOL_SOCKET == null) { Log.w(TAG, "SOL_SOCKET == null; not setting socket write timeout"); return; } Field f_SO_SNDTIMEO = c_osConstants.getField("SO_SNDTIMEO"); if (f_SO_SNDTIMEO == null) { Log.w(TAG, "SO_SNDTIMEO == null; not setting socket write timeout"); return; } Method m_setsockoptTimeval = instance_os.getClass().getMethod("setsockoptTimeval", FileDescriptor.class, int.class, int.class, c_structTimeval); if (m_setsockoptTimeval == null) { Log.w(TAG, "setsockoptTimeval == null; not setting socket write timeout"); return; } m_setsockoptTimeval.invoke(instance_os, fd, f_SOL_SOCKET.get(null), f_SO_SNDTIMEO.get(null), timeval); } catch (Exception e) { // We don't want to spam the logcat since this isn't a fatal error, but we want to know // why this might be happening. logStackTraceSnippet("Could not set socket write timeout: " + e, e); Throwable cause = e.getCause(); while (cause != null) { logStackTraceSnippet("Caused by: " + cause, cause); cause = cause.getCause(); } } } /** * Logs an abbreviated stacktrace (summary and a couple of StackTraceElements). */ private static void logStackTraceSnippet(String summary, Throwable throwable) { Log.w(TAG, summary); StackTraceElement[] elements = throwable.getStackTrace(); for (int i = 0; i < 2 && i < elements.length; i++) { Log.w(TAG, "\tat " + elements[i].toString()); } } private static void setSSLParametersOnImpl(SSLParameters params, SSLParametersImpl impl) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method m_getEndpointIdentificationAlgorithm = params.getClass().getMethod("getEndpointIdentificationAlgorithm"); impl.setEndpointIdentificationAlgorithm( (String) m_getEndpointIdentificationAlgorithm.invoke(params)); Method m_getUseCipherSuitesOrder = params.getClass().getMethod("getUseCipherSuitesOrder"); impl.setUseCipherSuitesOrder((boolean) m_getUseCipherSuitesOrder.invoke(params)); } public static void setSSLParameters( SSLParameters params, SSLParametersImpl impl, AbstractConscryptSocket socket) { try { setSSLParametersOnImpl(params, impl); if (Build.VERSION.SDK_INT >= 24) { String sniHostname = getSniHostnameFromParams(params); if (sniHostname != null) { socket.setHostname(sniHostname); } } } catch (NoSuchMethodException ignored) { //Ignored } catch (IllegalAccessException ignored) { //Ignored } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } public static void setSSLParameters( SSLParameters params, SSLParametersImpl impl, ConscryptEngine engine) { try { setSSLParametersOnImpl(params, impl); if (Build.VERSION.SDK_INT >= 24) { String sniHostname = getSniHostnameFromParams(params); if (sniHostname != null) { engine.setHostname(sniHostname); } } } catch (NoSuchMethodException ignored) { //Ignored } catch (IllegalAccessException ignored) { //Ignored } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } @TargetApi(24) private static String getSniHostnameFromParams(SSLParameters params) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method m_getServerNames = params.getClass().getMethod("getServerNames"); @SuppressWarnings("unchecked") List<SNIServerName> serverNames = (List<SNIServerName>) m_getServerNames.invoke(params); if (serverNames != null) { for (SNIServerName serverName : serverNames) { if (serverName.getType() == StandardConstants.SNI_HOST_NAME) { return ((SNIHostName) serverName).getAsciiName(); } } } return null; } private static void getSSLParametersFromImpl(SSLParameters params, SSLParametersImpl impl) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method m_setEndpointIdentificationAlgorithm = params.getClass().getMethod("setEndpointIdentificationAlgorithm", String.class); m_setEndpointIdentificationAlgorithm.invoke( params, impl.getEndpointIdentificationAlgorithm()); Method m_setUseCipherSuitesOrder = params.getClass().getMethod("setUseCipherSuitesOrder", boolean.class); m_setUseCipherSuitesOrder.invoke(params, impl.getUseCipherSuitesOrder()); } public static void getSSLParameters( SSLParameters params, SSLParametersImpl impl, AbstractConscryptSocket socket) { try { getSSLParametersFromImpl(params, impl); if (Build.VERSION.SDK_INT >= 24) { setParametersSniHostname(params, impl, socket); } } catch (NoSuchMethodException ignored) { //Ignored } catch (IllegalAccessException ignored) { //Ignored } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } @TargetApi(24) private static void setParametersSniHostname( SSLParameters params, SSLParametersImpl impl, AbstractConscryptSocket socket) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (impl.getUseSni() && AddressUtils.isValidSniHostname(socket.getHostname())) { Method m_setServerNames = params.getClass().getMethod("setServerNames", List.class); m_setServerNames.invoke(params, Collections.<SNIServerName>singletonList( new SNIHostName(socket.getHostname()))); } } public static void getSSLParameters( SSLParameters params, SSLParametersImpl impl, ConscryptEngine engine) { try { getSSLParametersFromImpl(params, impl); if (Build.VERSION.SDK_INT >= 24) { setParametersSniHostname(params, impl, engine); } } catch (NoSuchMethodException ignored) { //Ignored } catch (IllegalAccessException ignored) { //Ignored } catch (InvocationTargetException e) { throw new RuntimeException(e.getCause()); } } @TargetApi(24) private static void setParametersSniHostname( SSLParameters params, SSLParametersImpl impl, ConscryptEngine engine) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (impl.getUseSni() && AddressUtils.isValidSniHostname(engine.getHostname())) { Method m_setServerNames = params.getClass().getMethod("setServerNames", List.class); m_setServerNames.invoke(params, Collections.<SNIServerName>singletonList( new SNIHostName(engine.getHostname()))); } } /** * Tries to return a Class reference of one of the supplied class names. */ private static Class<?> getClass(String... klasses) { for (String klass : klasses) { try { return Class.forName(klass); } catch (Exception ignored) { //Ignored } } return null; } public static void setEndpointIdentificationAlgorithm( SSLParameters params, String endpointIdentificationAlgorithm) { // TODO: implement this for unbundled } public static String getEndpointIdentificationAlgorithm(SSLParameters params) { // TODO: implement this for unbundled return null; } /** * Helper function to unify calls to the different names used for each function taking a * Socket, SSLEngine, or String (legacy Android). */ private static boolean checkTrusted(String methodName, X509TrustManager tm, X509Certificate[] chain, String authType, Class<?> argumentClass, Object argumentInstance) throws CertificateException { // Use duck-typing to try and call the hostname-aware method if available. try { Method method = tm.getClass().getMethod( methodName, X509Certificate[].class, String.class, argumentClass); method.invoke(tm, chain, authType, argumentInstance); return true; } catch (NoSuchMethodException ignored) { //Ignored } catch (IllegalAccessException ignored) { //Ignored } catch (InvocationTargetException e) { if (e.getCause() instanceof CertificateException) { throw(CertificateException) e.getCause(); } throw new RuntimeException(e.getCause()); } return false; } @SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession() public static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain, String authType, AbstractConscryptSocket socket) throws CertificateException { if (!checkTrusted("checkClientTrusted", tm, chain, authType, Socket.class, socket) && !checkTrusted("checkClientTrusted", tm, chain, authType, String.class, socket.getHandshakeSession().getPeerHost())) { tm.checkClientTrusted(chain, authType); } } @SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession() public static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain, String authType, AbstractConscryptSocket socket) throws CertificateException { if (!checkTrusted("checkServerTrusted", tm, chain, authType, Socket.class, socket) && !checkTrusted("checkServerTrusted", tm, chain, authType, String.class, socket.getHandshakeSession().getPeerHost())) { tm.checkServerTrusted(chain, authType); } } @SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession() public static void checkClientTrusted(X509TrustManager tm, X509Certificate[] chain, String authType, ConscryptEngine engine) throws CertificateException { if (!checkTrusted("checkClientTrusted", tm, chain, authType, SSLEngine.class, engine) && !checkTrusted("checkClientTrusted", tm, chain, authType, String.class, engine.getHandshakeSession().getPeerHost())) { tm.checkClientTrusted(chain, authType); } } @SuppressLint("NewApi") // AbstractConscryptSocket defines getHandshakeSession() public static void checkServerTrusted(X509TrustManager tm, X509Certificate[] chain, String authType, ConscryptEngine engine) throws CertificateException { if (!checkTrusted("checkServerTrusted", tm, chain, authType, SSLEngine.class, engine) && !checkTrusted("checkServerTrusted", tm, chain, authType, String.class, engine.getHandshakeSession().getPeerHost())) { tm.checkServerTrusted(chain, authType); } } static SSLEngine wrapEngine(ConscryptEngine engine) { // For now, don't wrap on Android. return engine; } static SSLEngine unwrapEngine(SSLEngine engine) { // For now, don't wrap on Android. return engine; } static ConscryptEngineSocket createEngineSocket(SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8EngineSocket(sslParameters); } return new ConscryptEngineSocket(sslParameters); } static ConscryptEngineSocket createEngineSocket(String hostname, int port, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8EngineSocket(hostname, port, sslParameters); } return new ConscryptEngineSocket(hostname, port, sslParameters); } static ConscryptEngineSocket createEngineSocket(InetAddress address, int port, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8EngineSocket(address, port, sslParameters); } return new ConscryptEngineSocket(address, port, sslParameters); } static ConscryptEngineSocket createEngineSocket(String hostname, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8EngineSocket(hostname, port, clientAddress, clientPort, sslParameters); } return new ConscryptEngineSocket(hostname, port, clientAddress, clientPort, sslParameters); } static ConscryptEngineSocket createEngineSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8EngineSocket(address, port, clientAddress, clientPort, sslParameters); } return new ConscryptEngineSocket(address, port, clientAddress, clientPort, sslParameters); } static ConscryptEngineSocket createEngineSocket(Socket socket, String hostname, int port, boolean autoClose, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8EngineSocket(socket, hostname, port, autoClose, sslParameters); } return new ConscryptEngineSocket(socket, hostname, port, autoClose, sslParameters); } static ConscryptFileDescriptorSocket createFileDescriptorSocket(SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8FileDescriptorSocket(sslParameters); } return new ConscryptFileDescriptorSocket(sslParameters); } static ConscryptFileDescriptorSocket createFileDescriptorSocket(String hostname, int port, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8FileDescriptorSocket(hostname, port, sslParameters); } return new ConscryptFileDescriptorSocket(hostname, port, sslParameters); } static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress address, int port, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8FileDescriptorSocket(address, port, sslParameters); } return new ConscryptFileDescriptorSocket(address, port, sslParameters); } static ConscryptFileDescriptorSocket createFileDescriptorSocket(String hostname, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8FileDescriptorSocket( hostname, port, clientAddress, clientPort, sslParameters); } return new ConscryptFileDescriptorSocket( hostname, port, clientAddress, clientPort, sslParameters); } static ConscryptFileDescriptorSocket createFileDescriptorSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8FileDescriptorSocket( address, port, clientAddress, clientPort, sslParameters); } return new ConscryptFileDescriptorSocket( address, port, clientAddress, clientPort, sslParameters); } static ConscryptFileDescriptorSocket createFileDescriptorSocket(Socket socket, String hostname, int port, boolean autoClose, SSLParametersImpl sslParameters) throws IOException { if (Build.VERSION.SDK_INT >= 24) { return new Java8FileDescriptorSocket(socket, hostname, port, autoClose, sslParameters); } return new ConscryptFileDescriptorSocket(socket, hostname, port, autoClose, sslParameters); } /** * Wrap the SocketFactory with the platform wrapper if needed for compatability. */ public static SSLSocketFactory wrapSocketFactoryIfNeeded(OpenSSLSocketFactoryImpl factory) { if (Build.VERSION.SDK_INT < 22) { return new KitKatPlatformOpenSSLSocketAdapterFactory(factory); } return factory; } /** * Convert from platform's GCMParameterSpec to our internal version. */ @SuppressWarnings("LiteralClassName") public static GCMParameters fromGCMParameterSpec(AlgorithmParameterSpec params) { Class<?> gcmSpecClass; try { gcmSpecClass = Class.forName("javax.crypto.spec.GCMParameterSpec"); } catch (ClassNotFoundException e) { gcmSpecClass = null; } if (gcmSpecClass != null && gcmSpecClass.isAssignableFrom(params.getClass())) { try { int tLen; byte[] iv; Method getTLenMethod = gcmSpecClass.getMethod("getTLen"); Method getIVMethod = gcmSpecClass.getMethod("getIV"); tLen = (int) getTLenMethod.invoke(params); iv = (byte[]) getIVMethod.invoke(params); return new GCMParameters(tLen, iv); } catch (NoSuchMethodException e) { throw new RuntimeException("GCMParameterSpec lacks expected methods", e); } catch (IllegalAccessException e) { throw new RuntimeException("GCMParameterSpec lacks expected methods", e); } catch (InvocationTargetException e) { throw new RuntimeException( "Could not fetch GCM parameters", e.getTargetException()); } } return null; } /** * Convert from an opaque AlgorithmParameters to the platform's GCMParameterSpec. */ @SuppressWarnings({"LiteralClassName", "unchecked"}) static AlgorithmParameterSpec fromGCMParameters(AlgorithmParameters params) { Class<?> gcmSpecClass; try { gcmSpecClass = Class.forName("javax.crypto.spec.GCMParameterSpec"); } catch (ClassNotFoundException e) { gcmSpecClass = null; } if (gcmSpecClass != null) { try { return params.getParameterSpec((Class) gcmSpecClass); } catch (InvalidParameterSpecException e) { return null; } } return null; } /** * Creates a platform version of {@code GCMParameterSpec}. */ @SuppressWarnings("LiteralClassName") public static AlgorithmParameterSpec toGCMParameterSpec(int tagLenInBits, byte[] iv) { Class<?> gcmSpecClass; try { gcmSpecClass = Class.forName("javax.crypto.spec.GCMParameterSpec"); } catch (ClassNotFoundException e) { gcmSpecClass = null; } if (gcmSpecClass != null) { try { Constructor<?> constructor = gcmSpecClass.getConstructor(int.class, byte[].class); return (AlgorithmParameterSpec) constructor.newInstance(tagLenInBits, iv); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { logStackTraceSnippet("Can't find GCMParameterSpec class", e); } catch (InvocationTargetException e) { logStackTraceSnippet("Can't find GCMParameterSpec class", e.getCause()); } } return null; } /* * CloseGuard functions. */ public static CloseGuard closeGuardGet() { return CloseGuard.get(); } public static void closeGuardOpen(Object guardObj, String message) { CloseGuard guard = (CloseGuard) guardObj; guard.open(message); } public static void closeGuardClose(Object guardObj) { CloseGuard guard = (CloseGuard) guardObj; guard.close(); } public static void closeGuardWarnIfOpen(Object guardObj) { CloseGuard guard = (CloseGuard) guardObj; guard.warnIfOpen(); } /* * BlockGuard functions. */ public static void blockGuardOnNetwork() { BlockGuard.getThreadPolicy().onNetwork(); } /** * OID to Algorithm Name mapping. */ @SuppressWarnings("LiteralClassName") public static String oidToAlgorithmName(String oid) { // Old Harmony style try { Class<?> algNameMapperClass = Class.forName("org.apache.harmony.security.utils.AlgNameMapper"); Method map2AlgNameMethod = algNameMapperClass.getDeclaredMethod("map2AlgName", String.class); map2AlgNameMethod.setAccessible(true); return (String) map2AlgNameMethod.invoke(null, oid); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw(RuntimeException) cause; } else if (cause instanceof Error) { throw(Error) cause; } throw new RuntimeException(e); } catch (Exception ignored) { //Ignored } // Newer OpenJDK style try { Class<?> algorithmIdClass = Class.forName("sun.security.x509.AlgorithmId"); Method getMethod = algorithmIdClass.getDeclaredMethod("get", String.class); getMethod.setAccessible(true); Method getNameMethod = algorithmIdClass.getDeclaredMethod("getName"); getNameMethod.setAccessible(true); Object algIdObj = getMethod.invoke(null, oid); return (String) getNameMethod.invoke(algIdObj); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw(RuntimeException) cause; } else if (cause instanceof Error) { throw(Error) cause; } throw new RuntimeException(e); } catch (Exception ignored) { //Ignored } return oid; } /** * Provides extended capabilities for the session if supported by the platform. */ public static SSLSession wrapSSLSession(ExternalSession sslSession) { if (Build.VERSION.SDK_INT >= 24) { return new Java8ExtendedSSLSession(sslSession); } return sslSession; } public static String getOriginalHostNameFromInetAddress(InetAddress addr) { if (Build.VERSION.SDK_INT > 27) { try { Method getHolder = InetAddress.class.getDeclaredMethod("holder"); getHolder.setAccessible(true); Method getOriginalHostName = Class.forName("java.net.InetAddress$InetAddressHolder") .getDeclaredMethod("getOriginalHostName"); getOriginalHostName.setAccessible(true); String originalHostName = (String) getOriginalHostName.invoke(getHolder.invoke(addr)); if (originalHostName == null) { return addr.getHostAddress(); } return originalHostName; } catch (InvocationTargetException e) { throw new RuntimeException("Failed to get originalHostName", e); } catch (ClassNotFoundException ignore) { // passthrough and return addr.getHostAddress() } catch (IllegalAccessException ignore) { //Ignored } catch (NoSuchMethodException ignore) { //Ignored } } return addr.getHostAddress(); } /* * Pre-Java-7 backward compatibility. */ public static String getHostStringFromInetSocketAddress(InetSocketAddress addr) { if (Build.VERSION.SDK_INT > 23) { try { Method m_getHostString = InetSocketAddress.class.getDeclaredMethod("getHostString"); return (String) m_getHostString.invoke(addr); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (Exception ignored) { //Ignored } } return null; } // X509ExtendedTrustManager was added in API 24 static boolean supportsX509ExtendedTrustManager() { return Build.VERSION.SDK_INT > 23; } /** * Check if SCT verification is required for a given hostname. * * SCT Verification is enabled using {@code Security} properties. * The "conscrypt.ct.enable" property must be true, as well as a per domain property. * The reverse notation of the domain name, prefixed with "conscrypt.ct.enforce." * is used as the property name. * Basic globbing is also supported. * * For example, for the domain foo.bar.com, the following properties will be * looked up, in order of precedence. * - conscrypt.ct.enforce.com.bar.foo * - conscrypt.ct.enforce.com.bar.* * - conscrypt.ct.enforce.com.* * - conscrypt.ct.enforce.* */ public static boolean isCTVerificationRequired(String hostname) { if (hostname == null) { return false; } // TODO: Use the platform version on platforms that support it String property = Security.getProperty("conscrypt.ct.enable"); if (property == null || !Boolean.parseBoolean(property)) { return false; } List<String> parts = Arrays.asList(hostname.split("\\.")); Collections.reverse(parts); boolean enable = false; String propertyName = "conscrypt.ct.enforce"; // The loop keeps going on even once we've found a match // This allows for finer grained settings on subdomains for (String part : parts) { property = Security.getProperty(propertyName + ".*"); if (property != null) { enable = Boolean.parseBoolean(property); } propertyName = propertyName + "." + part; } property = Security.getProperty(propertyName); if (property != null) { enable = Boolean.parseBoolean(property); } return enable; } public static CertificateTransparencyVerificationReason reasonCTVerificationRequired( String hostname) { return CertificateTransparencyVerificationReason.UNKNOWN; } static boolean supportsConscryptCertStore() { return false; } static KeyStore getDefaultCertKeyStore() throws KeyStoreException { KeyStore keyStore = KeyStore.getInstance("AndroidCAStore"); try { keyStore.load(null, null); } catch (IOException e) { throw new KeyStoreException(e); } catch (CertificateException e) { throw new KeyStoreException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreException(e); } return keyStore; } static ConscryptCertStore newDefaultCertStore() { return null; } static CertBlocklist newDefaultBlocklist() { return null; } static CertificateTransparency newDefaultCertificateTransparency() { return null; } static boolean serverNamePermitted(SSLParametersImpl parameters, String serverName) { if (Build.VERSION.SDK_INT >= 24) { return serverNamePermittedInternal(parameters, serverName); } return true; } @TargetApi(24) private static boolean serverNamePermittedInternal( SSLParametersImpl parameters, String serverName) { Collection<SNIMatcher> sniMatchers = parameters.getSNIMatchers(); if (sniMatchers == null || sniMatchers.isEmpty()) { return true; } for (SNIMatcher m : sniMatchers) { boolean match = m.matches(new SNIHostName(serverName)); if (match) { return true; } } return false; } public static ConscryptHostnameVerifier getDefaultHostnameVerifier() { return OkHostnameVerifier.strictInstance(); } /** * Returns milliseconds elapsed since boot, including time spent in sleep. * @return long number of milliseconds elapsed since boot */ static long getMillisSinceBoot() { return SystemClock.elapsedRealtime(); } public static StatsLog getStatsLog() { if (Build.VERSION.SDK_INT >= 30) { return StatsLogImpl.getInstance(); } return NoopStatsLog.getInstance(); } public static Source getStatsSource() { return Source.SOURCE_GMS; } // Only called from StatsLogImpl, so protected by build version check above. @TargetApi(30) public static int[] getUids() { return new int[] {Os.getuid(), Binder.getCallingUid()}; } public static boolean isJavaxCertificateSupported() { return true; } public static boolean isTlsV1Deprecated() { return DEPRECATED_TLS_V1; } public static boolean isTlsV1Filtered() { return FILTERED_TLS_V1; } public static boolean isTlsV1Supported() { return ENABLED_TLS_V1; } public static boolean isPakeSupported() { return false; } public static boolean isSdkGreater(int sdk) { return Build.VERSION.SDK_INT > sdk; } }
googleapis/google-cloud-java
37,738
java-retail/proto-google-cloud-retail-v2/src/main/java/com/google/cloud/retail/v2/UpdateCatalogRequest.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/catalog_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.retail.v2; /** * * * <pre> * Request for * [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] * method. * </pre> * * Protobuf type {@code google.cloud.retail.v2.UpdateCatalogRequest} */ public final class UpdateCatalogRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.retail.v2.UpdateCatalogRequest) UpdateCatalogRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateCatalogRequest.newBuilder() to construct. private UpdateCatalogRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateCatalogRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateCatalogRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2.CatalogServiceProto .internal_static_google_cloud_retail_v2_UpdateCatalogRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2.CatalogServiceProto .internal_static_google_cloud_retail_v2_UpdateCatalogRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2.UpdateCatalogRequest.class, com.google.cloud.retail.v2.UpdateCatalogRequest.Builder.class); } private int bitField0_; public static final int CATALOG_FIELD_NUMBER = 1; private com.google.cloud.retail.v2.Catalog catalog_; /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the catalog field is set. */ @java.lang.Override public boolean hasCatalog() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The catalog. */ @java.lang.Override public com.google.cloud.retail.v2.Catalog getCatalog() { return catalog_ == null ? com.google.cloud.retail.v2.Catalog.getDefaultInstance() : catalog_; } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.retail.v2.CatalogOrBuilder getCatalogOrBuilder() { return catalog_ == null ? com.google.cloud.retail.v2.Catalog.getDefaultInstance() : catalog_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Indicates which fields in the provided * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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, getCatalog()); } 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, getCatalog()); } 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.UpdateCatalogRequest)) { return super.equals(obj); } com.google.cloud.retail.v2.UpdateCatalogRequest other = (com.google.cloud.retail.v2.UpdateCatalogRequest) obj; if (hasCatalog() != other.hasCatalog()) return false; if (hasCatalog()) { if (!getCatalog().equals(other.getCatalog())) 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 (hasCatalog()) { hash = (37 * hash) + CATALOG_FIELD_NUMBER; hash = (53 * hash) + getCatalog().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.UpdateCatalogRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2.UpdateCatalogRequest 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.UpdateCatalogRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2.UpdateCatalogRequest 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.UpdateCatalogRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.retail.v2.UpdateCatalogRequest 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.UpdateCatalogRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.retail.v2.UpdateCatalogRequest 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.UpdateCatalogRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.retail.v2.UpdateCatalogRequest 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.UpdateCatalogRequest 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.UpdateCatalogRequest 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.UpdateCatalogRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request for * [CatalogService.UpdateCatalog][google.cloud.retail.v2.CatalogService.UpdateCatalog] * method. * </pre> * * Protobuf type {@code google.cloud.retail.v2.UpdateCatalogRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.retail.v2.UpdateCatalogRequest) com.google.cloud.retail.v2.UpdateCatalogRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.retail.v2.CatalogServiceProto .internal_static_google_cloud_retail_v2_UpdateCatalogRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.retail.v2.CatalogServiceProto .internal_static_google_cloud_retail_v2_UpdateCatalogRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.retail.v2.UpdateCatalogRequest.class, com.google.cloud.retail.v2.UpdateCatalogRequest.Builder.class); } // Construct using com.google.cloud.retail.v2.UpdateCatalogRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCatalogFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; catalog_ = null; if (catalogBuilder_ != null) { catalogBuilder_.dispose(); catalogBuilder_ = 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.CatalogServiceProto .internal_static_google_cloud_retail_v2_UpdateCatalogRequest_descriptor; } @java.lang.Override public com.google.cloud.retail.v2.UpdateCatalogRequest getDefaultInstanceForType() { return com.google.cloud.retail.v2.UpdateCatalogRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.retail.v2.UpdateCatalogRequest build() { com.google.cloud.retail.v2.UpdateCatalogRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.retail.v2.UpdateCatalogRequest buildPartial() { com.google.cloud.retail.v2.UpdateCatalogRequest result = new com.google.cloud.retail.v2.UpdateCatalogRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.retail.v2.UpdateCatalogRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.catalog_ = catalogBuilder_ == null ? catalog_ : catalogBuilder_.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.UpdateCatalogRequest) { return mergeFrom((com.google.cloud.retail.v2.UpdateCatalogRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.retail.v2.UpdateCatalogRequest other) { if (other == com.google.cloud.retail.v2.UpdateCatalogRequest.getDefaultInstance()) return this; if (other.hasCatalog()) { mergeCatalog(other.getCatalog()); } 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(getCatalogFieldBuilder().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.Catalog catalog_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.retail.v2.Catalog, com.google.cloud.retail.v2.Catalog.Builder, com.google.cloud.retail.v2.CatalogOrBuilder> catalogBuilder_; /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the catalog field is set. */ public boolean hasCatalog() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The catalog. */ public com.google.cloud.retail.v2.Catalog getCatalog() { if (catalogBuilder_ == null) { return catalog_ == null ? com.google.cloud.retail.v2.Catalog.getDefaultInstance() : catalog_; } else { return catalogBuilder_.getMessage(); } } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setCatalog(com.google.cloud.retail.v2.Catalog value) { if (catalogBuilder_ == null) { if (value == null) { throw new NullPointerException(); } catalog_ = value; } else { catalogBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setCatalog(com.google.cloud.retail.v2.Catalog.Builder builderForValue) { if (catalogBuilder_ == null) { catalog_ = builderForValue.build(); } else { catalogBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeCatalog(com.google.cloud.retail.v2.Catalog value) { if (catalogBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && catalog_ != null && catalog_ != com.google.cloud.retail.v2.Catalog.getDefaultInstance()) { getCatalogBuilder().mergeFrom(value); } else { catalog_ = value; } } else { catalogBuilder_.mergeFrom(value); } if (catalog_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearCatalog() { bitField0_ = (bitField0_ & ~0x00000001); catalog_ = null; if (catalogBuilder_ != null) { catalogBuilder_.dispose(); catalogBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.retail.v2.Catalog.Builder getCatalogBuilder() { bitField0_ |= 0x00000001; onChanged(); return getCatalogFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.retail.v2.CatalogOrBuilder getCatalogOrBuilder() { if (catalogBuilder_ != null) { return catalogBuilder_.getMessageOrBuilder(); } else { return catalog_ == null ? com.google.cloud.retail.v2.Catalog.getDefaultInstance() : catalog_; } } /** * * * <pre> * Required. The [Catalog][google.cloud.retail.v2.Catalog] to update. * * If the caller does not have permission to update the * [Catalog][google.cloud.retail.v2.Catalog], regardless of whether or not it * exists, a PERMISSION_DENIED error is returned. * * If the [Catalog][google.cloud.retail.v2.Catalog] to update does not exist, * a NOT_FOUND error is returned. * </pre> * * <code>.google.cloud.retail.v2.Catalog catalog = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.retail.v2.Catalog, com.google.cloud.retail.v2.Catalog.Builder, com.google.cloud.retail.v2.CatalogOrBuilder> getCatalogFieldBuilder() { if (catalogBuilder_ == null) { catalogBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.retail.v2.Catalog, com.google.cloud.retail.v2.Catalog.Builder, com.google.cloud.retail.v2.CatalogOrBuilder>( getCatalog(), getParentForChildren(), isClean()); catalog_ = null; } return catalogBuilder_; } 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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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 * [Catalog][google.cloud.retail.v2.Catalog] to update. * * If an unsupported or unknown field is provided, an INVALID_ARGUMENT error * is returned. * </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.UpdateCatalogRequest) } // @@protoc_insertion_point(class_scope:google.cloud.retail.v2.UpdateCatalogRequest) private static final com.google.cloud.retail.v2.UpdateCatalogRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.retail.v2.UpdateCatalogRequest(); } public static com.google.cloud.retail.v2.UpdateCatalogRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateCatalogRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateCatalogRequest>() { @java.lang.Override public UpdateCatalogRequest 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<UpdateCatalogRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateCatalogRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.retail.v2.UpdateCatalogRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/closure-compiler
37,411
test/com/google/javascript/rhino/NodeTest.java
/* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Nick Santos * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino; import static com.google.common.truth.Truth.assertThat; import static com.google.javascript.rhino.testing.NodeSubject.assertNode; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.javascript.jscomp.colors.StandardColors; import com.google.javascript.jscomp.serialization.NodeProperty; import com.google.javascript.rhino.Node.SideEffectFlags; import com.google.javascript.rhino.jstype.JSTypeNative; import com.google.javascript.rhino.jstype.JSTypeRegistry; import com.google.javascript.rhino.testing.TestErrorReporter; import java.math.BigInteger; import java.util.function.Consumer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class NodeTest { @Test public void testValidatePropertiesForRoot() { final Node n = IR.root(); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); // ROOT nodes shouldn't have properties, not even a source file n.setSourceFileForTesting("file.js"); assertThat(getMessagesFromValidateProperties(n)).containsExactly("ROOT has properties"); } private ImmutableList<String> getMessagesFromValidateProperties(Node n) { final ImmutableList.Builder<String> listBuilder = ImmutableList.builder(); Consumer<String> violationMessageConsumer = listBuilder::add; n.validateProperties(violationMessageConsumer); return listBuilder.build(); } @Test public void testSideEffectFlagsSerialization() { // Test each individual flag checkSideEffectFlagsRoundTrip(SideEffectFlags.MUTATES_GLOBAL_STATE); checkSideEffectFlagsRoundTrip(SideEffectFlags.MUTATES_THIS); checkSideEffectFlagsRoundTrip(SideEffectFlags.MUTATES_ARGUMENTS); checkSideEffectFlagsRoundTrip(SideEffectFlags.THROWS); // Test an arbitrary combination of 2 flags checkSideEffectFlagsRoundTrip(SideEffectFlags.THROWS | SideEffectFlags.MUTATES_THIS); } public void checkSideEffectFlagsRoundTrip(int testFlags) { final Node original = IR.call(IR.name("f")); // serialization only works for nodes that actually have a source file, // because in actual execution they always must have that. original.setSourceFileForTesting("sourcefile"); // Simulate the situation where we've deserialized the node itself, but not its non-source-file // properties yet, by cloning the orignal node before adding the side effect flags to it. final Node restored = original.cloneNode(); original.setSideEffectFlags(testFlags); final long serializedProperties = original.serializeProperties(); restored.deserializeProperties(serializedProperties); assertThat(restored.getSideEffectFlags()).isEqualTo(testFlags); } @Test public void testValidatePropertiesForIsParenthesized() { Node n = IR.string(""); n.setSourceFileForTesting("file.js"); // avoid error about missing source file n.setIsParenthesized(true); n.setToken(Token.STRING_KEY); assertThat(getMessagesFromValidateProperties(n)) .containsExactly("non-expression is parenthesized"); } @Test public void testValidatePropertiesForFunctionProperties() { Node n = IR.empty(); n.setSourceFileForTesting("file.js"); // avoid error about missing source file // Change the Node type so we won't get thrown errors when we try to set the function-only // properties. n.setToken(Token.FUNCTION); n.setIsArrowFunction(true); n.setIsAsyncFunction(true); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.EMPTY); assertThat(getMessagesFromValidateProperties(n)) .containsExactly("invalid ARROW_FN prop", "invalid ASYNC_FN prop"); } @Test public void testValidatePropertiesForSyntheticProperty() { Node n = IR.block(); n.setSourceFileForTesting("file.js"); // avoid error about missing source file n.setIsSyntheticBlock(true); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.EMPTY); assertThat(getMessagesFromValidateProperties(n)).containsExactly("invalid SYNTHETIC prop"); } @Test public void testValidatePropertiesForColorFromCast() { Node n = IR.name("a"); n.setSourceFileForTesting("file.js"); // avoid error about missing source file n.setColor(StandardColors.NUMBER); n.setColorFromTypeCast(); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setColor(null); assertThat(getMessagesFromValidateProperties(n)) .containsExactly("COLOR_FROM_CAST with no Color"); } @Test public void testValidatePropertiesForOptChain() { Node n = IR.empty(); n.setSourceFileForTesting("file.js"); // avoid error about missing source file n.setToken(Token.OPTCHAIN_CALL); n.setIsOptionalChainStart(true); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.OPTCHAIN_GETELEM); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.OPTCHAIN_GETELEM); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.EMPTY); assertThat(getMessagesFromValidateProperties(n)) .containsExactly("START_OF_OPT_CHAIN on non-optional Node"); } @Test public void testValidatePropertiesForConstVarFlags() { Node n = IR.name("a"); n.setSourceFileForTesting("file.js"); // avoid error about missing source file n.setDeclaredConstantVar(true); n.setInferredConstantVar(true); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.IMPORT_STAR); assertThat(getMessagesFromValidateProperties(n)).isEmpty(); n.setToken(Token.STRINGLIT); assertThat(getMessagesFromValidateProperties(n)).containsExactly("invalid CONST_VAR_FLAGS"); } @Test public void testLinenoCharnoNormal() { assertLinenoCharno(5, 6, 5, 6); assertLinenoCharno(456, 3423, 456, 3423); assertLinenoCharno(0, 0, 0, 0); } @Test public void testLinenoCharnoErroneous() { assertLinenoCharno(-5, 90, -1, -1); assertLinenoCharno(90, -1, -1, -1); } @Test public void testMergeOverflowGraciously() { assertLinenoCharno(89, 4096, 89, 4095); } private void assertLinenoCharno(int linenoIn, int charnoIn, int linenoOut, int charnoOut) { Node test = IR.block(); test.setLinenoCharno(linenoIn, charnoIn); assertThat(test.getLineno()).isEqualTo(linenoOut); assertThat(test.getCharno()).isEqualTo(charnoOut); } @Test public void isEquivalentToConsidersStartOfOptionalChainProperty() { // `a?.b.c` Node singleSegmentOptChain = IR.continueOptChainGetprop(IR.startOptChainGetprop(IR.name("a"), "b"), "c"); assertNode(singleSegmentOptChain).isEquivalentTo(singleSegmentOptChain.cloneTree()); Node twoSegmentOptChain = singleSegmentOptChain.cloneTree(); twoSegmentOptChain.setIsOptionalChainStart(true); assertNode(singleSegmentOptChain).isNotEquivalentTo(twoSegmentOptChain); } @Test public void isEquivalentToForFunctionsConsidersKindOfFunction() { Node normalFunction = IR.function(IR.name(""), IR.paramList(), IR.block()); assertNode(normalFunction).isEquivalentTo(normalFunction.cloneTree()); // normal vs async function Node asyncFunction = normalFunction.cloneTree(); asyncFunction.setIsAsyncFunction(true); assertNode(asyncFunction) .isEquivalentTo(asyncFunction.cloneTree()) .isNotEquivalentTo(normalFunction); // normal vs arrow function Node arrowFunction = normalFunction.cloneTree(); arrowFunction.setIsArrowFunction(true); assertNode(arrowFunction) .isEquivalentTo(arrowFunction.cloneTree()) .isNotEquivalentTo(normalFunction); // async arrow function vs async only vs arrow only Node asyncArrowFunction = arrowFunction.cloneTree(); asyncArrowFunction.setIsAsyncFunction(true); assertNode(asyncArrowFunction) .isEquivalentTo(asyncArrowFunction.cloneTree()) .isNotEquivalentTo(arrowFunction) .isNotEquivalentTo(asyncFunction); // normal vs generator function Node generatorFunction = normalFunction.cloneTree(); generatorFunction.setIsGeneratorFunction(true); assertNode(generatorFunction) .isEquivalentTo(generatorFunction.cloneTree()) .isNotEquivalentTo(normalFunction); // async generator function vs only async vs only generator Node asyncGeneratorFunction = generatorFunction.cloneTree(); asyncGeneratorFunction.setIsAsyncFunction(true); assertNode(asyncGeneratorFunction) .isEquivalentTo(asyncGeneratorFunction.cloneTree()) .isNotEquivalentTo(asyncFunction) .isNotEquivalentTo(generatorFunction); } @Test public void testIsEquivalentTo_withBoolean_isSame() { Node node1 = new Node(Token.LET); assertThat(node1.isEquivalentTo(node1)).isTrue(); } @Test public void testIsEquivalentTo_withBoolean_isDifferent() { Node node1 = new Node(Token.LET); Node node2 = new Node(Token.VAR); assertThat(node1.isEquivalentTo(node2)).isFalse(); } @Test public void testIsEquivalentTo_considersDifferentEsModuleExports() { Node exportAllFrom = new Node(Token.EXPORT); // export * from './other/module' exportAllFrom.putBooleanProp(Node.EXPORT_ALL_FROM, true); Node exportDefault = new Node(Token.EXPORT); // export default function foo() { exportDefault.putBooleanProp(Node.EXPORT_DEFAULT, true); Node simpleExport = new Node(Token.EXPORT); // export {x} or export const x = 0; assertThat(exportAllFrom.isEquivalentTo(exportDefault)).isFalse(); assertThat(exportAllFrom.isEquivalentTo(simpleExport)).isFalse(); assertThat(exportDefault.isEquivalentTo(simpleExport)).isFalse(); } @Test public void testIsEquivalentToNumber() { assertThat(Node.newNumber(1).isEquivalentTo(Node.newNumber(1))).isTrue(); assertThat(Node.newNumber(1).isEquivalentTo(Node.newNumber(2))).isFalse(); } @Test public void testNumberRejects_isNaN() { assertNumberNodeRejects(Double.NaN); assertNumberNodeRejects(-Double.NaN); } @Test public void testNumberRejects_negativeValues() { assertNumberNodeRejects(-1394793.114); assertNumberNodeRejects(-1.0); assertNumberNodeRejects(-0.0); assertNumberNodeRejects(Double.NEGATIVE_INFINITY); } private void assertNumberNodeRejects(double d) { assertThrows(Exception.class, () -> Node.newNumber(d)); assertThrows(Exception.class, () -> Node.newNumber(0.0).setDouble(d)); } @Test public void testBigintRejects_negativeValues() { assertBigIntNodeRejects(new BigInteger("-1394793")); assertBigIntNodeRejects(new BigInteger("-1")); assertThat(Node.newBigInt(new BigInteger("-0"))).isNotNull(); } private void assertBigIntNodeRejects(BigInteger x) { assertThrows(Exception.class, () -> Node.newBigInt(x)); assertThrows(Exception.class, () -> Node.newBigInt(BigInteger.ZERO).setBigInt(x)); } @Test public void testIsEquivalentToBigInt() { assertThat(Node.newBigInt(BigInteger.ONE).isEquivalentTo(Node.newBigInt(BigInteger.ONE))) .isTrue(); assertThat(Node.newBigInt(BigInteger.ONE).isEquivalentTo(Node.newBigInt(BigInteger.TEN))) .isFalse(); } @Test public void testIsEquivalentToString() { assertThat(Node.newString("1").isEquivalentTo(Node.newString("1"))).isTrue(); assertThat(Node.newString("1").isEquivalentTo(Node.newString("2"))).isFalse(); } @Test public void testCheckTreeTypeAwareEqualsSame() { TestErrorReporter testErrorReporter = new TestErrorReporter(); JSTypeRegistry registry = new JSTypeRegistry(testErrorReporter); Node node1 = Node.newString(Token.NAME, "f"); node1.setJSType(registry.getNativeType(JSTypeNative.NUMBER_TYPE)); Node node2 = Node.newString(Token.NAME, "f"); node2.setJSType(registry.getNativeType(JSTypeNative.NUMBER_TYPE)); assertThat(node1.isEquivalentToTyped(node2)).isTrue(); testErrorReporter.verifyHasEncounteredAllWarningsAndErrors(); } @Test public void testCheckTreeTypeAwareEqualsSameNull() { Node node1 = Node.newString(Token.NAME, "f"); Node node2 = Node.newString(Token.NAME, "f"); assertThat(node1.isEquivalentToTyped(node2)).isTrue(); } @Test public void testCheckTreeTypeAwareEqualsDifferent() { TestErrorReporter testErrorReporter = new TestErrorReporter(); JSTypeRegistry registry = new JSTypeRegistry(testErrorReporter); Node node1 = Node.newString(Token.NAME, "f"); node1.setJSType(registry.getNativeType(JSTypeNative.NUMBER_TYPE)); Node node2 = Node.newString(Token.NAME, "f"); node2.setJSType(registry.getNativeType(JSTypeNative.STRING_TYPE)); assertThat(node1.isEquivalentToTyped(node2)).isFalse(); testErrorReporter.verifyHasEncounteredAllWarningsAndErrors(); } @Test public void testCheckTreeTypeAwareEqualsDifferentNull() { TestErrorReporter testErrorReporter = new TestErrorReporter(); JSTypeRegistry registry = new JSTypeRegistry(testErrorReporter); Node node1 = Node.newString(Token.NAME, "f"); node1.setJSType(registry.getNativeType(JSTypeNative.NUMBER_TYPE)); Node node2 = Node.newString(Token.NAME, "f"); assertThat(node1.isEquivalentToTyped(node2)).isFalse(); testErrorReporter.verifyHasEncounteredAllWarningsAndErrors(); } @Test public void testCheckTreeTypeAwareEqualsColorsSame() { Node node1 = Node.newString(Token.NAME, "f"); node1.setColor(StandardColors.NUMBER); Node node2 = Node.newString(Token.NAME, "f"); node2.setColor(StandardColors.NUMBER); assertThat(node1.isEquivalentToTyped(node2)).isTrue(); } @Test public void testCheckTreeTypeAwareEqualsColorsSameNull() { Node node1 = Node.newString(Token.NAME, "f"); Node node2 = Node.newString(Token.NAME, "f"); assertThat(node1.isEquivalentToTyped(node2)).isTrue(); } @Test public void testCheckTreeTypeAwareEqualsColorsDifferent() { Node node1 = Node.newString(Token.NAME, "f"); node1.setColor(StandardColors.NUMBER); Node node2 = Node.newString(Token.NAME, "f"); node2.setColor(StandardColors.STRING); assertThat(node1.isEquivalentToTyped(node2)).isFalse(); } @Test public void testCheckTreeTypeAwareEqualsColorsDifferentNull() { Node node1 = Node.newString(Token.NAME, "f"); node1.setColor(StandardColors.NUMBER); Node node2 = Node.newString(Token.NAME, "f"); assertThat(node1.isEquivalentToTyped(node2)).isFalse(); } @Test public void testIsQualifiedName() { assertThat(IR.name("a").isQualifiedName()).isTrue(); assertThat(IR.name("$").isQualifiedName()).isTrue(); assertThat(IR.name("_").isQualifiedName()).isTrue(); assertThat(IR.getprop(IR.name("a"), "b").isQualifiedName()).isTrue(); assertThat(IR.getprop(IR.thisNode(), "b").isQualifiedName()).isTrue(); assertThat(IR.number(0).isQualifiedName()).isFalse(); assertThat(IR.arraylit().isQualifiedName()).isFalse(); assertThat(IR.objectlit().isQualifiedName()).isFalse(); assertThat(IR.string("").isQualifiedName()).isFalse(); assertThat(IR.getelem(IR.name("a"), IR.string("b")).isQualifiedName()).isFalse(); assertThat( // a[b].c IR.getprop(IR.getelem(IR.name("a"), IR.string("b")), "c").isQualifiedName()) .isFalse(); assertThat( // a.b[c] IR.getelem(IR.getprop(IR.name("a"), "b"), IR.string("c")).isQualifiedName()) .isFalse(); assertThat(IR.call(IR.name("a")).isQualifiedName()).isFalse(); assertThat( // a().b IR.getprop(IR.call(IR.name("a")), "b").isQualifiedName()) .isFalse(); assertThat( // (a.b)() IR.call(IR.getprop(IR.name("a"), "b")).isQualifiedName()) .isFalse(); assertThat(IR.string("a").isQualifiedName()).isFalse(); assertThat(IR.regexp(IR.string("x")).isQualifiedName()).isFalse(); assertThat(new Node(Token.INC, IR.name("x")).isQualifiedName()).isFalse(); } @Test public void testMatchesQualifiedName1() { assertThat(IR.name("a").matchesQualifiedName("a")).isTrue(); assertThat(IR.name("a").matchesQualifiedName("ab")).isFalse(); assertThat(IR.name("a").matchesQualifiedName("a.b")).isFalse(); assertThat(IR.name("a").matchesQualifiedName(".b")).isFalse(); assertThat(IR.name("a").matchesQualifiedName("a.")).isFalse(); assertThat(qname("a.b").matchesQualifiedName("a")).isFalse(); assertThat(qname("a.b").matchesQualifiedName("a.b")).isTrue(); assertThat(qname("a.b").matchesQualifiedName("a.bc")).isFalse(); assertThat(qname("a.b").matchesQualifiedName(".b")).isFalse(); assertThat(qname("a.b").matchesQualifiedName("this.b")).isFalse(); assertThat(qname("this").matchesQualifiedName("this")).isTrue(); assertThat(qname("this").matchesQualifiedName("thisx")).isFalse(); assertThat(qname("this.b").matchesQualifiedName("a")).isFalse(); assertThat(qname("this.b").matchesQualifiedName("a.b")).isFalse(); assertThat(qname("this.b").matchesQualifiedName(".b")).isFalse(); assertThat(qname("this.b").matchesQualifiedName("a.")).isFalse(); assertThat(qname("this.b").matchesQualifiedName("super.b")).isFalse(); assertThat(qname("this.b").matchesQualifiedName("this.b")).isTrue(); assertThat(qname("super").matchesQualifiedName("super")).isTrue(); assertThat(qname("super").matchesQualifiedName("superx")).isFalse(); assertThat(qname("super.b").matchesQualifiedName("a")).isFalse(); assertThat(qname("super.b").matchesQualifiedName("a.b")).isFalse(); assertThat(qname("super.b").matchesQualifiedName(".b")).isFalse(); assertThat(qname("super.b").matchesQualifiedName("a.")).isFalse(); assertThat(qname("super.b").matchesQualifiedName("this.b")).isFalse(); assertThat(qname("super.b").matchesQualifiedName("super.b")).isTrue(); assertThat(qname("a.b.c").matchesQualifiedName("a.b.c")).isTrue(); assertThat(qname("a.b.c").matchesQualifiedName("a.b.c")).isTrue(); assertThat(IR.importStar("a").matchesQualifiedName("a")).isTrue(); assertThat(IR.importStar("a").matchesQualifiedName("b")).isFalse(); assertThat(IR.number(0).matchesQualifiedName("a.b")).isFalse(); assertThat(IR.arraylit().matchesQualifiedName("a.b")).isFalse(); assertThat(IR.objectlit().matchesQualifiedName("a.b")).isFalse(); assertThat(IR.string("").matchesQualifiedName("a.b")).isFalse(); assertThat(IR.getelem(IR.name("a"), IR.string("b")).matchesQualifiedName("a.b")).isFalse(); assertThat( // a[b].c IR.getprop(IR.getelem(IR.name("a"), IR.string("b")), "c").matchesQualifiedName("a.b.c")) .isFalse(); assertThat( // a.b[c] IR.getelem(IR.getprop(IR.name("a"), "b"), IR.string("c")).matchesQualifiedName("a.b.c")) .isFalse(); assertThat(IR.call(IR.name("a")).matchesQualifiedName("a")).isFalse(); assertThat( // a().b IR.getprop(IR.call(IR.name("a")), "b").matchesQualifiedName("a.b")) .isFalse(); assertThat( // (a.b)() IR.call(IR.getprop(IR.name("a"), "b")).matchesQualifiedName("a.b")) .isFalse(); assertThat(IR.string("a").matchesQualifiedName("a")).isFalse(); assertThat(IR.regexp(IR.string("x")).matchesQualifiedName("x")).isFalse(); assertThat(new Node(Token.INC, IR.name("x")).matchesQualifiedName("x")).isFalse(); } @Test public void testMatchesQualifiedName2() { assertThat(IR.name("a").matchesQualifiedName(qname("a"))).isTrue(); assertThat(IR.name("a").matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(qname("a.b").matchesQualifiedName(qname("a"))).isFalse(); assertThat(qname("a.b").matchesQualifiedName(qname("a.b"))).isTrue(); assertThat(qname("a.b").matchesQualifiedName(qname(".b"))).isFalse(); assertThat(qname("a.b").matchesQualifiedName(qname("this.b"))).isFalse(); assertThat(qname("this.b").matchesQualifiedName(qname("a"))).isFalse(); assertThat(qname("this.b").matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(qname("this.b").matchesQualifiedName(qname("super.b"))).isFalse(); assertThat(qname("this.b").matchesQualifiedName(qname("this.b"))).isTrue(); assertThat(qname("super.b").matchesQualifiedName(qname("a"))).isFalse(); assertThat(qname("super.b").matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(qname("super.b").matchesQualifiedName(qname("this.b"))).isFalse(); assertThat(qname("super.b").matchesQualifiedName(qname("super.b"))).isTrue(); assertThat(qname("a.b.c").matchesQualifiedName(qname("a.b.c"))).isTrue(); assertThat(qname("a.b.c").matchesQualifiedName(qname("a.b.c"))).isTrue(); assertThat(IR.number(0).matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(IR.arraylit().matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(IR.objectlit().matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(IR.string("").matchesQualifiedName(qname("a.b"))).isFalse(); assertThat(IR.getelem(IR.name("a"), IR.string("b")).matchesQualifiedName(qname("a.b"))) .isFalse(); assertThat( // a[b].c IR.getprop(IR.getelem(IR.name("a"), IR.string("b")), "c") .matchesQualifiedName(qname("a.b.c"))) .isFalse(); assertThat( // a.b[c] IR.getelem(IR.getprop(IR.name("a"), "b"), IR.string("c")).matchesQualifiedName("a.b.c")) .isFalse(); assertThat(IR.call(IR.name("a")).matchesQualifiedName(qname("a"))).isFalse(); assertThat( // a().b IR.getprop(IR.call(IR.name("a")), "b").matchesQualifiedName(qname("a.b"))) .isFalse(); assertThat( // (a.b)() IR.call(IR.getprop(IR.name("a"), "b")).matchesQualifiedName(qname("a.b"))) .isFalse(); assertThat(IR.string("a").matchesQualifiedName(qname("a"))).isFalse(); assertThat(IR.regexp(IR.string("x")).matchesQualifiedName(qname("x"))).isFalse(); assertThat(new Node(Token.INC, IR.name("x")).matchesQualifiedName(qname("x"))).isFalse(); } @Test public void testMatchesName() { // Empty string are treat as unique. assertThat(IR.name("").matchesName("")).isFalse(); assertThat(IR.name("a").matchesName("a")).isTrue(); assertThat(IR.name("a").matchesName("a.b")).isFalse(); assertThat(IR.name("a").matchesName("")).isFalse(); assertThat(IR.thisNode().matchesName("this")).isFalse(); assertThat(IR.superNode().matchesName("super")).isFalse(); } @Test public void testMatchesNameNodes() { assertThat(IR.name("a").matchesName(qname("a"))).isTrue(); assertThat(IR.name("a").matchesName(qname("a.b"))).isFalse(); assertThat(IR.thisNode().matchesName(qname("this"))).isFalse(); assertThat(IR.superNode().matchesName(qname("super"))).isFalse(); } public static Node qname(String name) { int endPos = name.indexOf('.'); if (endPos == -1) { return IR.name(name); } Node node; String nodeName = name.substring(0, endPos); if ("this".equals(nodeName)) { node = IR.thisNode(); } else if ("super".equals(nodeName)) { node = IR.superNode(); } else { node = IR.name(nodeName); } int startPos; do { startPos = endPos + 1; endPos = name.indexOf('.', startPos); String part = (endPos == -1 ? name.substring(startPos) : name.substring(startPos, endPos)); node = IR.getprop(node, part); } while (endPos != -1); return node; } @Test public void testCloneAnnontations() { Node n = getVarRef("a"); n.setLength(1); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isFalse(); n.putBooleanProp(Node.IS_CONSTANT_NAME, true); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); Node nodeClone = n.cloneNode(); assertThat(nodeClone.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); assertThat(nodeClone.getLength()).isEqualTo(1); } @Test public void testCloneValues() { Node number = Node.newNumber(100.0); assertThat(number.cloneNode().getDouble()).isEqualTo(100.0); Node string = Node.newString(new String("a")); assertThat(string.cloneNode().getString()).isSameInstanceAs(string.getString()); Node template = Node.newTemplateLitString(new String("a"), new String("b")); assertThat(template.cloneNode().getCookedString()).isSameInstanceAs(template.getCookedString()); assertThat(template.cloneNode().getRawString()).isSameInstanceAs(template.getRawString()); Node bigint = Node.newBigInt(new BigInteger("100")); assertThat(bigint.cloneNode().getBigInt()).isSameInstanceAs(bigint.getBigInt()); } @Test public void testSharedProps1() { Node n = getCall("A"); n.setSideEffectFlags(5); Node m = new Node(Token.TRUE); m.clonePropsFrom(n); assertThat(n.getPropListHeadForTesting()).isEqualTo(m.getPropListHeadForTesting()); assertThat(n.getSideEffectFlags()).isEqualTo(5); assertThat(m.getSideEffectFlags()).isEqualTo(5); } @Test public void testSharedProps2() { Node n = getCall("A"); n.setSideEffectFlags(5); Node m = getCall("B"); m.clonePropsFrom(n); n.setSideEffectFlags(6); assertThat(n.getSideEffectFlags()).isEqualTo(6); assertThat(m.getSideEffectFlags()).isEqualTo(5); assertThat(m.getPropListHeadForTesting() == n.getPropListHeadForTesting()).isFalse(); m.setSideEffectFlags(7); assertThat(n.getSideEffectFlags()).isEqualTo(6); assertThat(m.getSideEffectFlags()).isEqualTo(7); } @Test public void testSharedProps3() { Node n = getCall("A"); n.setSideEffectFlags(2); n.putBooleanProp(Node.INCRDECR_PROP, true); Node m = new Node(Token.TRUE); m.clonePropsFrom(n); n.setSideEffectFlags(4); assertThat(n.getSideEffectFlags()).isEqualTo(4); assertThat(m.getSideEffectFlags()).isEqualTo(2); } @Test public void testBooleanProp() { Node n = getVarRef("a"); n.putBooleanProp(Node.IS_CONSTANT_NAME, false); assertThat(n.lookupProperty(Node.IS_CONSTANT_NAME)).isNull(); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isFalse(); n.putBooleanProp(Node.IS_CONSTANT_NAME, true); assertThat(n.lookupProperty(Node.IS_CONSTANT_NAME)).isNotNull(); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); n.putBooleanProp(Node.IS_CONSTANT_NAME, false); assertThat(n.lookupProperty(Node.IS_CONSTANT_NAME)).isNull(); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isFalse(); } // Verify that annotations on cloned nodes are properly handled. @Test public void testCloneAnnontations2() { Node n = getVarRef("a"); n.putBooleanProp(Node.IS_CONSTANT_NAME, true); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); Node nodeClone = n.cloneNode(); assertThat(nodeClone.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); assertThat(n.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); assertThat(nodeClone.getBooleanProp(Node.IS_CONSTANT_NAME)).isTrue(); } private long bitsetFromNodeProperties(ImmutableSet<NodeProperty> props) { long bitset = 0; for (NodeProperty prop : props) { bitset = Node.setNodePropertyBit(bitset, prop); } return bitset; } @Test public void testSerializeProperties() { Node node = IR.function(IR.name(""), IR.paramList(), IR.block()); node.setIsAsyncFunction(true); node.setIsGeneratorFunction(true); long result = node.serializeProperties(); assertThat(result) .isEqualTo( bitsetFromNodeProperties( ImmutableSet.of(NodeProperty.GENERATOR_FN, NodeProperty.ASYNC_FN))); } @Test public void testSerializeProperties_isDeclaredConstant() { Node node = new Node(Token.NAME); node.setDeclaredConstantVar(true); long result = node.serializeProperties(); assertThat(result) .isEqualTo(bitsetFromNodeProperties(ImmutableSet.of(NodeProperty.IS_DECLARED_CONSTANT))); } @Test public void testSerializeProperties_isInferredConstant() { Node node = new Node(Token.NAME); node.setInferredConstantVar(true); long result = node.serializeProperties(); assertThat(result) .isEqualTo(bitsetFromNodeProperties(ImmutableSet.of(NodeProperty.IS_INFERRED_CONSTANT))); } @Test public void testSerializeProperties_untranslatableRhinoProp() { Node node = getCall("A"); node.setUseStrict(true); long result = node.serializeProperties(); // Rhino node prop USE_STRICT does not have a corresponding NodeProperty assertThat(node.isUseStrict()).isTrue(); assertThat(result).isEqualTo(0); } @Test public void testSerializeProperties_typeBeforeCast() { TestErrorReporter testErrorReporter = new TestErrorReporter(); JSTypeRegistry registry = new JSTypeRegistry(testErrorReporter); Node node = Node.newString(Token.NAME, "f"); node.setJSTypeBeforeCast(registry.getNativeType(JSTypeNative.NUMBER_TYPE)); long result = node.serializeProperties(); // Special case: Rhino node prop TYPE_BEFORE_CAST is converted to NodeProperty.COLOR_FROM_CAST assertThat(result) .isEqualTo(bitsetFromNodeProperties(ImmutableSet.of(NodeProperty.COLOR_FROM_CAST))); } @Test public void testGetIndexOfChild() { Node assign = getAssignExpr("b", "c"); assertThat(assign.getChildCount()).isEqualTo(2); Node firstChild = assign.getFirstChild(); Node secondChild = firstChild.getNext(); assertThat(secondChild).isNotNull(); assertThat(assign.getIndexOfChild(firstChild)).isEqualTo(0); assertThat(assign.getIndexOfChild(secondChild)).isEqualTo(1); assertThat(assign.getIndexOfChild(assign)).isEqualTo(-1); } @Test public void testSrcrefIfMissing() { Node assign = getAssignExpr("b", "c"); assign.setLinenoCharno(99, 0); assign.setSourceFileForTesting("foo.js"); Node lhs = assign.getFirstChild(); lhs.srcrefIfMissing(assign); assertNode(lhs).hasLineno(99); assertThat(lhs.getSourceFileName()).isEqualTo("foo.js"); assign.setLinenoCharno(101, 0); assign.setSourceFileForTesting("bar.js"); lhs.srcrefIfMissing(assign); assertNode(lhs).hasLineno(99); assertThat(lhs.getSourceFileName()).isEqualTo("foo.js"); } @Test public void testSrcref() { Node assign = getAssignExpr("b", "c"); assign.setLinenoCharno(99, 0); assign.setSourceFileForTesting("foo.js"); Node lhs = assign.getFirstChild(); lhs.srcref(assign); assertNode(lhs).hasLineno(99); assertThat(lhs.getSourceFileName()).isEqualTo("foo.js"); assign.setLinenoCharno(101, 0); assign.setSourceFileForTesting("bar.js"); lhs.srcref(assign); assertNode(lhs).hasLineno(101); assertThat(lhs.getSourceFileName()).isEqualTo("bar.js"); } @Test public void testInvalidSourceOffset() { Node string = Node.newString("a"); string.setLinenoCharno(-1, -1); assertThat(string.getSourceOffset()).isLessThan(0); string.setSourceFileForTesting("foo.js"); assertThat(string.getSourceOffset()).isLessThan(0); } @Test public void testQualifiedName() { assertThat(IR.name("").getQualifiedName()).isNull(); assertThat(IR.name("a").getQualifiedName()).isEqualTo("a"); assertThat(IR.thisNode().getQualifiedName()).isEqualTo("this"); assertThat(IR.superNode().getQualifiedName()).isEqualTo("super"); assertThat(IR.getprop(IR.name("a"), "b").getQualifiedName()).isEqualTo("a.b"); assertThat(IR.getprop(IR.thisNode(), "b").getQualifiedName()).isEqualTo("this.b"); assertThat(IR.getprop(IR.superNode(), "b").getQualifiedName()).isEqualTo("super.b"); assertThat(IR.getprop(IR.call(IR.name("a")), "b").getQualifiedName()).isNull(); } @Test public void testJSDocInfoClone() { Node original = IR.var(IR.name("varName")); JSDocInfo.Builder builder = JSDocInfo.builder(); builder.recordType(new JSTypeExpression(IR.name("TypeName"), "blah")); JSDocInfo info = builder.build(); original.getFirstChild().setJSDocInfo(info); // By default the JSDocInfo and JSTypeExpression objects are not cloned Node clone = original.cloneTree(); assertThat(clone.getFirstChild().getJSDocInfo()) .isSameInstanceAs(original.getFirstChild().getJSDocInfo()); assertThat(clone.getFirstChild().getJSDocInfo().getType()) .isSameInstanceAs(original.getFirstChild().getJSDocInfo().getType()); assertThat(clone.getFirstChild().getJSDocInfo().getType().getRoot()) .isSameInstanceAs(original.getFirstChild().getJSDocInfo().getType().getRoot()); // If requested the JSDocInfo and JSTypeExpression objects are cloned. // This is required because compiler classes are modifying the type expressions in place clone = original.cloneTree(true); assertThat(clone.getFirstChild().getJSDocInfo()) .isNotSameInstanceAs(original.getFirstChild().getJSDocInfo()); assertThat(clone.getFirstChild().getJSDocInfo().getType()) .isNotSameInstanceAs(original.getFirstChild().getJSDocInfo().getType()); assertThat(clone.getFirstChild().getJSDocInfo().getType().getRoot()) .isNotSameInstanceAs(original.getFirstChild().getJSDocInfo().getType().getRoot()); } @Test public void testAddChildToFrontWithSingleNode() { Node root = new Node(Token.SCRIPT); Node nodeToAdd = new Node(Token.SCRIPT); root.addChildToFront(nodeToAdd); assertThat(nodeToAdd.getParent()).isEqualTo(root); assertThat(nodeToAdd).isEqualTo(root.getFirstChild()); assertThat(nodeToAdd).isEqualTo(root.getLastChild()); assertThat(nodeToAdd.getNext()).isNull(); } @Test public void testAddChildToFrontWithLargerTree() { Node left = Node.newString("left"); Node mid = Node.newString("mid"); Node right = Node.newString("right"); Node root = new Node(Token.SCRIPT, left, mid, right); Node nodeToAdd = new Node(Token.SCRIPT); root.addChildToFront(nodeToAdd); assertThat(nodeToAdd.getParent()).isEqualTo(root); assertThat(nodeToAdd).isEqualTo(root.getFirstChild()); assertThat(nodeToAdd.getPrevious()).isNull(); assertThat(nodeToAdd.getNext()).isEqualTo(left); assertThat(left.getPrevious()).isEqualTo(nodeToAdd); } @Test public void testDetach1() { Node left = Node.newString("left"); Node mid = Node.newString("mid"); Node right = Node.newString("right"); Node root = new Node(Token.SCRIPT, left, mid, right); assertThat(mid.getParent()).isEqualTo(root); assertThat(mid.getPrevious()).isEqualTo(left); assertThat(mid.getNext()).isEqualTo(right); mid.detach(); assertThat(mid.getParent()).isNull(); assertThat(mid.getNext()).isNull(); assertThat(right.getPrevious()).isEqualTo(left); assertThat(left.getNext()).isEqualTo(right); } @Test public void testGetAncestors() { Node grandparent = new Node(Token.ROOT); Node parent = new Node(Token.PLACEHOLDER1); Node node = new Node(Token.PLACEHOLDER2); grandparent.addChildToFront(parent); parent.addChildToFront(node); assertThat(node.getAncestors()).containsExactly(parent, grandparent); } @Test public void testGetAncestors_empty() { Node node = new Node(Token.ROOT); assertThat(node.getAncestors()).isEmpty(); } @Test public void testTrailingComma() { Node list = new Node(Token.ARRAYLIT); list.setTrailingComma(true); assertNode(list).hasTrailingComma(); } private static Node getVarRef(String name) { return Node.newString(Token.NAME, name); } private static Node getAssignExpr(String name1, String name2) { return new Node(Token.ASSIGN, getVarRef(name1), getVarRef(name2)); } private static Node getCall(String name1) { return new Node(Token.CALL, getVarRef(name1)); } }
googleads/google-ads-java
37,834
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/resources/CustomerAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/resources/customer_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.resources; /** * <pre> * CustomerAssetSet is the linkage between a customer and an asset set. * Adding a CustomerAssetSet links an asset set with a customer. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.CustomerAssetSet} */ public final class CustomerAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.resources.CustomerAssetSet) CustomerAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerAssetSet.newBuilder() to construct. private CustomerAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerAssetSet() { resourceName_ = ""; assetSet_ = ""; customer_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v19_resources_CustomerAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v19_resources_CustomerAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.CustomerAssetSet.class, com.google.ads.googleads.v19.resources.CustomerAssetSet.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; 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(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; 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(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CUSTOMER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object customer_ = ""; /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The customer. */ @java.lang.Override public java.lang.String getCustomer() { java.lang.Object ref = customer_; 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(); customer_ = s; return s; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for customer. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerBytes() { java.lang.Object ref = customer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.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(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, assetSet_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customer_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, customer_); } if (status_ != com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } 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(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, assetSet_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customer_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, customer_); } if (status_ != com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } 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.resources.CustomerAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v19.resources.CustomerAssetSet other = (com.google.ads.googleads.v19.resources.CustomerAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (!getCustomer() .equals(other.getCustomer())) return false; if (status_ != other.status_) 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_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + CUSTOMER_FIELD_NUMBER; hash = (53 * hash) + getCustomer().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.resources.CustomerAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v19.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v19.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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> * CustomerAssetSet is the linkage between a customer and an asset set. * Adding a CustomerAssetSet links an asset set with a customer. * </pre> * * Protobuf type {@code google.ads.googleads.v19.resources.CustomerAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.resources.CustomerAssetSet) com.google.ads.googleads.v19.resources.CustomerAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v19_resources_CustomerAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v19_resources_CustomerAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.resources.CustomerAssetSet.class, com.google.ads.googleads.v19.resources.CustomerAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v19.resources.CustomerAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; assetSet_ = ""; customer_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v19_resources_CustomerAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v19.resources.CustomerAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerAssetSet build() { com.google.ads.googleads.v19.resources.CustomerAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerAssetSet buildPartial() { com.google.ads.googleads.v19.resources.CustomerAssetSet result = new com.google.ads.googleads.v19.resources.CustomerAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.resources.CustomerAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.customer_ = customer_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @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.resources.CustomerAssetSet) { return mergeFrom((com.google.ads.googleads.v19.resources.CustomerAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.resources.CustomerAssetSet other) { if (other == com.google.ads.googleads.v19.resources.CustomerAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getCustomer().isEmpty()) { customer_ = other.customer_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } 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: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { customer_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = 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 resourceName_ = ""; /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object customer_ = ""; /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The customer. */ public java.lang.String getCustomer() { java.lang.Object ref = customer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for customer. */ public com.google.protobuf.ByteString getCustomerBytes() { java.lang.Object ref = customer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The customer to set. * @return This builder for chaining. */ public Builder setCustomer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customer_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearCustomer() { customer_ = getDefaultInstance().getCustomer(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for customer to set. * @return This builder for chaining. */ public Builder setCustomerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customer_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v19.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 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.ads.googleads.v19.resources.CustomerAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.resources.CustomerAssetSet) private static final com.google.ads.googleads.v19.resources.CustomerAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.resources.CustomerAssetSet(); } public static com.google.ads.googleads.v19.resources.CustomerAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerAssetSet> PARSER = new com.google.protobuf.AbstractParser<CustomerAssetSet>() { @java.lang.Override public CustomerAssetSet 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<CustomerAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.resources.CustomerAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,834
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/resources/CustomerAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/resources/customer_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.resources; /** * <pre> * CustomerAssetSet is the linkage between a customer and an asset set. * Adding a CustomerAssetSet links an asset set with a customer. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.CustomerAssetSet} */ public final class CustomerAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.resources.CustomerAssetSet) CustomerAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerAssetSet.newBuilder() to construct. private CustomerAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerAssetSet() { resourceName_ = ""; assetSet_ = ""; customer_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v20_resources_CustomerAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v20_resources_CustomerAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.CustomerAssetSet.class, com.google.ads.googleads.v20.resources.CustomerAssetSet.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; 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(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; 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(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CUSTOMER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object customer_ = ""; /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The customer. */ @java.lang.Override public java.lang.String getCustomer() { java.lang.Object ref = customer_; 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(); customer_ = s; return s; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for customer. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerBytes() { java.lang.Object ref = customer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.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(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, assetSet_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customer_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, customer_); } if (status_ != com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } 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(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, assetSet_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customer_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, customer_); } if (status_ != com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } 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.resources.CustomerAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v20.resources.CustomerAssetSet other = (com.google.ads.googleads.v20.resources.CustomerAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (!getCustomer() .equals(other.getCustomer())) return false; if (status_ != other.status_) 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_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + CUSTOMER_FIELD_NUMBER; hash = (53 * hash) + getCustomer().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.resources.CustomerAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v20.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v20.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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> * CustomerAssetSet is the linkage between a customer and an asset set. * Adding a CustomerAssetSet links an asset set with a customer. * </pre> * * Protobuf type {@code google.ads.googleads.v20.resources.CustomerAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.resources.CustomerAssetSet) com.google.ads.googleads.v20.resources.CustomerAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v20_resources_CustomerAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v20_resources_CustomerAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.resources.CustomerAssetSet.class, com.google.ads.googleads.v20.resources.CustomerAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v20.resources.CustomerAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; assetSet_ = ""; customer_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v20_resources_CustomerAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v20.resources.CustomerAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerAssetSet build() { com.google.ads.googleads.v20.resources.CustomerAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerAssetSet buildPartial() { com.google.ads.googleads.v20.resources.CustomerAssetSet result = new com.google.ads.googleads.v20.resources.CustomerAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.resources.CustomerAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.customer_ = customer_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @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.resources.CustomerAssetSet) { return mergeFrom((com.google.ads.googleads.v20.resources.CustomerAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.resources.CustomerAssetSet other) { if (other == com.google.ads.googleads.v20.resources.CustomerAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getCustomer().isEmpty()) { customer_ = other.customer_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } 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: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { customer_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = 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 resourceName_ = ""; /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object customer_ = ""; /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The customer. */ public java.lang.String getCustomer() { java.lang.Object ref = customer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for customer. */ public com.google.protobuf.ByteString getCustomerBytes() { java.lang.Object ref = customer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The customer to set. * @return This builder for chaining. */ public Builder setCustomer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customer_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearCustomer() { customer_ = getDefaultInstance().getCustomer(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for customer to set. * @return This builder for chaining. */ public Builder setCustomerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customer_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v20.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 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.ads.googleads.v20.resources.CustomerAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.resources.CustomerAssetSet) private static final com.google.ads.googleads.v20.resources.CustomerAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.resources.CustomerAssetSet(); } public static com.google.ads.googleads.v20.resources.CustomerAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerAssetSet> PARSER = new com.google.protobuf.AbstractParser<CustomerAssetSet>() { @java.lang.Override public CustomerAssetSet 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<CustomerAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.resources.CustomerAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,834
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/resources/CustomerAssetSet.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/resources/customer_asset_set.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.resources; /** * <pre> * CustomerAssetSet is the linkage between a customer and an asset set. * Adding a CustomerAssetSet links an asset set with a customer. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.CustomerAssetSet} */ public final class CustomerAssetSet extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.resources.CustomerAssetSet) CustomerAssetSetOrBuilder { private static final long serialVersionUID = 0L; // Use CustomerAssetSet.newBuilder() to construct. private CustomerAssetSet(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CustomerAssetSet() { resourceName_ = ""; assetSet_ = ""; customer_ = ""; status_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new CustomerAssetSet(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v21_resources_CustomerAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v21_resources_CustomerAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.CustomerAssetSet.class, com.google.ads.googleads.v21.resources.CustomerAssetSet.Builder.class); } public static final int RESOURCE_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object resourceName_ = ""; /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ @java.lang.Override public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; 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(); resourceName_ = s; return s; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ @java.lang.Override public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ASSET_SET_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ @java.lang.Override public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; 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(); assetSet_ = s; return s; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ @java.lang.Override public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CUSTOMER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object customer_ = ""; /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The customer. */ @java.lang.Override public java.lang.String getCustomer() { java.lang.Object ref = customer_; 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(); customer_ = s; return s; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for customer. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerBytes() { java.lang.Object ref = customer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATUS_FIELD_NUMBER = 4; private int status_ = 0; /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.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(resourceName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, assetSet_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customer_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, customer_); } if (status_ != com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { output.writeEnum(4, status_); } 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(resourceName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resourceName_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(assetSet_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, assetSet_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customer_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, customer_); } if (status_ != com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNSPECIFIED.getNumber()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(4, status_); } 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.resources.CustomerAssetSet)) { return super.equals(obj); } com.google.ads.googleads.v21.resources.CustomerAssetSet other = (com.google.ads.googleads.v21.resources.CustomerAssetSet) obj; if (!getResourceName() .equals(other.getResourceName())) return false; if (!getAssetSet() .equals(other.getAssetSet())) return false; if (!getCustomer() .equals(other.getCustomer())) return false; if (status_ != other.status_) 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_NAME_FIELD_NUMBER; hash = (53 * hash) + getResourceName().hashCode(); hash = (37 * hash) + ASSET_SET_FIELD_NUMBER; hash = (53 * hash) + getAssetSet().hashCode(); hash = (37 * hash) + CUSTOMER_FIELD_NUMBER; hash = (53 * hash) + getCustomer().hashCode(); hash = (37 * hash) + STATUS_FIELD_NUMBER; hash = (53 * hash) + status_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.resources.CustomerAssetSet parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v21.resources.CustomerAssetSet 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.resources.CustomerAssetSet parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v21.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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.resources.CustomerAssetSet 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> * CustomerAssetSet is the linkage between a customer and an asset set. * Adding a CustomerAssetSet links an asset set with a customer. * </pre> * * Protobuf type {@code google.ads.googleads.v21.resources.CustomerAssetSet} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.resources.CustomerAssetSet) com.google.ads.googleads.v21.resources.CustomerAssetSetOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v21_resources_CustomerAssetSet_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v21_resources_CustomerAssetSet_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.resources.CustomerAssetSet.class, com.google.ads.googleads.v21.resources.CustomerAssetSet.Builder.class); } // Construct using com.google.ads.googleads.v21.resources.CustomerAssetSet.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; resourceName_ = ""; assetSet_ = ""; customer_ = ""; status_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.resources.CustomerAssetSetProto.internal_static_google_ads_googleads_v21_resources_CustomerAssetSet_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerAssetSet getDefaultInstanceForType() { return com.google.ads.googleads.v21.resources.CustomerAssetSet.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerAssetSet build() { com.google.ads.googleads.v21.resources.CustomerAssetSet result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerAssetSet buildPartial() { com.google.ads.googleads.v21.resources.CustomerAssetSet result = new com.google.ads.googleads.v21.resources.CustomerAssetSet(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.resources.CustomerAssetSet result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.resourceName_ = resourceName_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.assetSet_ = assetSet_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.customer_ = customer_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.status_ = status_; } } @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.resources.CustomerAssetSet) { return mergeFrom((com.google.ads.googleads.v21.resources.CustomerAssetSet)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.resources.CustomerAssetSet other) { if (other == com.google.ads.googleads.v21.resources.CustomerAssetSet.getDefaultInstance()) return this; if (!other.getResourceName().isEmpty()) { resourceName_ = other.resourceName_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getAssetSet().isEmpty()) { assetSet_ = other.assetSet_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getCustomer().isEmpty()) { customer_ = other.customer_; bitField0_ |= 0x00000004; onChanged(); } if (other.status_ != 0) { setStatusValue(other.getStatusValue()); } 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: { resourceName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { assetSet_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { customer_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { status_ = 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 resourceName_ = ""; /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The resourceName. */ public java.lang.String getResourceName() { java.lang.Object ref = resourceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for resourceName. */ public com.google.protobuf.ByteString getResourceNameBytes() { java.lang.Object ref = resourceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); resourceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The resourceName to set. * @return This builder for chaining. */ public Builder setResourceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearResourceName() { resourceName_ = getDefaultInstance().getResourceName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Immutable. The resource name of the customer asset set. * Asset set asset resource names have the form: * * `customers/{customer_id}/customerAssetSets/{asset_set_id}` * </pre> * * <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for resourceName to set. * @return This builder for chaining. */ public Builder setResourceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object assetSet_ = ""; /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The assetSet. */ public java.lang.String getAssetSet() { java.lang.Object ref = assetSet_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); assetSet_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for assetSet. */ public com.google.protobuf.ByteString getAssetSetBytes() { java.lang.Object ref = assetSet_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); assetSet_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The assetSet to set. * @return This builder for chaining. */ public Builder setAssetSet( java.lang.String value) { if (value == null) { throw new NullPointerException(); } assetSet_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearAssetSet() { assetSet_ = getDefaultInstance().getAssetSet(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Immutable. The asset set which is linked to the customer. * </pre> * * <code>string asset_set = 2 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for assetSet to set. * @return This builder for chaining. */ public Builder setAssetSetBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); assetSet_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object customer_ = ""; /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The customer. */ public java.lang.String getCustomer() { java.lang.Object ref = customer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customer_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return The bytes for customer. */ public com.google.protobuf.ByteString getCustomerBytes() { java.lang.Object ref = customer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The customer to set. * @return This builder for chaining. */ public Builder setCustomer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customer_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @return This builder for chaining. */ public Builder clearCustomer() { customer_ = getDefaultInstance().getCustomer(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Immutable. The customer to which this asset set is linked. * </pre> * * <code>string customer = 3 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code> * @param value The bytes for customer to set. * @return This builder for chaining. */ public Builder setCustomerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customer_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private int status_ = 0; /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The enum numeric value on the wire for status. */ @java.lang.Override public int getStatusValue() { return status_; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The enum numeric value on the wire for status to set. * @return This builder for chaining. */ public Builder setStatusValue(int value) { status_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The status. */ @java.lang.Override public com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus getStatus() { com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus result = com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.forNumber(status_); return result == null ? com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus.UNRECOGNIZED : result; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @param value The status to set. * @return This builder for chaining. */ public Builder setStatus(com.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000008; status_ = value.getNumber(); onChanged(); return this; } /** * <pre> * Output only. The status of the customer asset set asset. Read-only. * </pre> * * <code>.google.ads.googleads.v21.enums.AssetSetLinkStatusEnum.AssetSetLinkStatus status = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return This builder for chaining. */ public Builder clearStatus() { bitField0_ = (bitField0_ & ~0x00000008); status_ = 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.ads.googleads.v21.resources.CustomerAssetSet) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.resources.CustomerAssetSet) private static final com.google.ads.googleads.v21.resources.CustomerAssetSet DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.resources.CustomerAssetSet(); } public static com.google.ads.googleads.v21.resources.CustomerAssetSet getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CustomerAssetSet> PARSER = new com.google.protobuf.AbstractParser<CustomerAssetSet>() { @java.lang.Override public CustomerAssetSet 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<CustomerAssetSet> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CustomerAssetSet> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.resources.CustomerAssetSet getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hbase
38,052
hbase-endpoint/src/main/java/org/apache/hadoop/hbase/client/coprocessor/AggregationClient.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.hbase.client.coprocessor; import static org.apache.hadoop.hbase.client.coprocessor.AggregationHelper.getParsedGenericInstance; import static org.apache.hadoop.hbase.client.coprocessor.AggregationHelper.validateArgAndGetPB; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.coprocessor.ColumnInterpreter; import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Pair; import org.apache.yetus.audience.InterfaceAudience; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hbase.thirdparty.com.google.protobuf.ByteString; import org.apache.hbase.thirdparty.com.google.protobuf.Message; import org.apache.hbase.thirdparty.com.google.protobuf.RpcCallback; import org.apache.hbase.thirdparty.com.google.protobuf.RpcController; import org.apache.hadoop.hbase.shaded.protobuf.generated.AggregateProtos.AggregateRequest; import org.apache.hadoop.hbase.shaded.protobuf.generated.AggregateProtos.AggregateResponse; import org.apache.hadoop.hbase.shaded.protobuf.generated.AggregateProtos.AggregateService; /** * This client class is for invoking the aggregate functions deployed on the Region Server side via * the AggregateService. This class will implement the supporting functionality for * summing/processing the individual results obtained from the AggregateService for each region. * <p> * This will serve as the client side handler for invoking the aggregate functions. For all * aggregate functions, * <ul> * <li>start row &lt; end row is an essential condition (if they are not * {@link HConstants#EMPTY_BYTE_ARRAY}) * <li>Column family can't be null. In case where multiple families are provided, an IOException * will be thrown. An optional column qualifier can also be defined.</li> * <li>For methods to find maximum, minimum, sum, rowcount, it returns the parameter type. For * average and std, it returns a double value. For row count, it returns a long value.</li> * </ul> * <p> * Call {@link #close()} when done. */ @InterfaceAudience.Public public class AggregationClient implements Closeable { // TODO: This class is not used. Move to examples? private static final Logger log = LoggerFactory.getLogger(AggregationClient.class); private final Connection connection; private final boolean manageConnection; /** * An RpcController implementation for use here in this endpoint. */ static class AggregationClientRpcController implements RpcController { private String errorText; private boolean cancelled = false; private boolean failed = false; @Override public String errorText() { return this.errorText; } @Override public boolean failed() { return this.failed; } @Override public boolean isCanceled() { return this.cancelled; } @Override public void notifyOnCancel(RpcCallback<Object> arg0) { throw new UnsupportedOperationException(); } @Override public void reset() { this.errorText = null; this.cancelled = false; this.failed = false; } @Override public void setFailed(String errorText) { this.failed = true; this.errorText = errorText; } @Override public void startCancel() { this.cancelled = true; } } /** * Creates AggregationClient with no underlying Connection. Users of this constructor should limit * themselves to methods here which take a {@link Table} argument, such as * {@link #rowCount(Table, ColumnInterpreter, Scan)}. Use of methods which instead take a * TableName, such as {@link #rowCount(TableName, ColumnInterpreter, Scan)}, will throw an * IOException. */ public AggregationClient() { this(null, false); } /** * Creates AggregationClient using the passed in Connection, which will be used by methods taking * a {@link TableName} to create the necessary {@link Table} for the call. The Connection is * externally managed by the caller and will not be closed if {@link #close()} is called. There is * no need to call {@link #close()} for AggregationClients created this way. * @param connection the connection to use */ public AggregationClient(Connection connection) { this(connection, false); } /** * Creates AggregationClient with internally managed Connection, which will be used by methods * taking a {@link TableName} to create the necessary {@link Table} for the call. The Connection * will immediately be created will be closed when {@link #close()} is called. It's important to * call {@link #close()} when done with this AggregationClient and to otherwise treat it as a * shared Singleton. * @param cfg Configuration to use to create connection */ public AggregationClient(Configuration cfg) { // Create a connection on construction. Will use it making each of the calls below. this(createConnection(cfg), true); } private static Connection createConnection(Configuration cfg) { try { return ConnectionFactory.createConnection(cfg); } catch (IOException e) { throw new RuntimeException(e); } } private AggregationClient(Connection connection, boolean manageConnection) { this.connection = connection; this.manageConnection = manageConnection; } @Override public void close() throws IOException { if (manageConnection && this.connection != null && !this.connection.isClosed()) { this.connection.close(); } } // visible for tests boolean isClosed() { return manageConnection && this.connection != null && this.connection.isClosed(); } private Connection getConnection() throws IOException { if (connection == null) { throw new IOException( "Connection not initialized. Use the correct constructor, or use the methods taking a Table"); } return connection; } /** * It gives the maximum value of a column for a given column family for the given range. In case * qualifier is null, a max of all values for the given family is returned. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return max val &lt;R&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> R max(final TableName tableName, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return max(table, ci, scan); } } /** * It gives the maximum value of a column for a given column family for the given range. In case * qualifier is null, a max of all values for the given family is returned. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return max val &lt;&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> R max(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false, false); class MaxCallBack implements Batch.Callback<R> { R max = null; R getMax() { return max; } @Override public synchronized void update(byte[] region, byte[] row, R result) { max = (max == null || (result != null && ci.compare(max, result) < 0)) ? result : max; } } MaxCallBack aMaxCallBack = new MaxCallBack(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, R>() { @Override public R call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getMax(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } if (response.getFirstPartCount() > 0) { ByteString b = response.getFirstPart(0); Q q = getParsedGenericInstance(ci.getClass(), 3, b); return ci.getCellValueFromProto(q); } return null; } }, aMaxCallBack); return aMaxCallBack.getMax(); } /** * It gives the minimum value of a column for a given column family for the given range. In case * qualifier is null, a min of all values for the given family is returned. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return min val &lt;R&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> R min(final TableName tableName, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return min(table, ci, scan); } } /** * It gives the minimum value of a column for a given column family for the given range. In case * qualifier is null, a min of all values for the given family is returned. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return min val &lt;R&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> R min(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false, false); class MinCallBack implements Batch.Callback<R> { private R min = null; public R getMinimum() { return min; } @Override public synchronized void update(byte[] region, byte[] row, R result) { min = (min == null || (result != null && ci.compare(result, min) < 0)) ? result : min; } } MinCallBack minCallBack = new MinCallBack(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, R>() { @Override public R call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getMin(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } if (response.getFirstPartCount() > 0) { ByteString b = response.getFirstPart(0); Q q = getParsedGenericInstance(ci.getClass(), 3, b); return ci.getCellValueFromProto(q); } return null; } }, minCallBack); log.debug("Min fom all regions is: " + minCallBack.getMinimum()); return minCallBack.getMinimum(); } /** * It gives the row count, by summing up the individual results obtained from regions. In case the * qualifier is null, FirstKeyValueFilter is used to optimised the operation. In case qualifier is * provided, I can't use the filter as it may set the flag to skip to next row, but the value read * is not of the given filter: in this case, this particular row will not be counted ==&gt; an * error. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return &lt;R, S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> long rowCount(final TableName tableName, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return rowCount(table, ci, scan); } } /** * It gives the row count, by summing up the individual results obtained from regions. In case the * qualifier is null, FirstKeyValueFilter is used to optimised the operation. In case qualifier is * provided, I can't use the filter as it may set the flag to skip to next row, but the value read * is not of the given filter: in this case, this particular row will not be counted ==&gt; an * error. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return &lt;R, S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> long rowCount(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, true, false); class RowNumCallback implements Batch.Callback<Long> { private final AtomicLong rowCountL = new AtomicLong(0); public long getRowNumCount() { return rowCountL.get(); } @Override public void update(byte[] region, byte[] row, Long result) { rowCountL.addAndGet(result.longValue()); } } RowNumCallback rowNum = new RowNumCallback(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, Long>() { @Override public Long call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getRowNum(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } byte[] bytes = getBytesFromResponse(response.getFirstPart(0)); ByteBuffer bb = ByteBuffer.allocate(8).put(bytes); bb.rewind(); return bb.getLong(); } }, rowNum); return rowNum.getRowNumCount(); } /** * It sums up the value returned from various regions. In case qualifier is null, summation of all * the column qualifiers in the given family is done. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return sum &lt;S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> S sum(final TableName tableName, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return sum(table, ci, scan); } } /** * It sums up the value returned from various regions. In case qualifier is null, summation of all * the column qualifiers in the given family is done. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return sum &lt;S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> S sum(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false, false); class SumCallBack implements Batch.Callback<S> { S sumVal = null; public S getSumResult() { return sumVal; } @Override public synchronized void update(byte[] region, byte[] row, S result) { sumVal = ci.add(sumVal, result); } } SumCallBack sumCallBack = new SumCallBack(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, S>() { @Override public S call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); // Not sure what is going on here why I have to do these casts. TODO. CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getSum(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } if (response.getFirstPartCount() == 0) { return null; } ByteString b = response.getFirstPart(0); T t = getParsedGenericInstance(ci.getClass(), 4, b); S s = ci.getPromotedValueFromProto(t); return s; } }, sumCallBack); return sumCallBack.getSumResult(); } /** * It computes average while fetching sum and row count from all the corresponding regions. * Approach is to compute a global sum of region level sum and rowcount and then compute the * average. * @param tableName the name of the table to scan * @param scan the HBase scan object to use to read data from HBase * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ private <R, S, P extends Message, Q extends Message, T extends Message> Pair<S, Long> getAvgArgs( final TableName tableName, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return getAvgArgs(table, ci, scan); } } /** * It computes average while fetching sum and row count from all the corresponding regions. * Approach is to compute a global sum of region level sum and rowcount and then compute the * average. * @param table table to scan. * @param scan the HBase scan object to use to read data from HBase * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ private <R, S, P extends Message, Q extends Message, T extends Message> Pair<S, Long> getAvgArgs(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false, false); class AvgCallBack implements Batch.Callback<Pair<S, Long>> { S sum = null; Long rowCount = 0L; public synchronized Pair<S, Long> getAvgArgs() { return new Pair<>(sum, rowCount); } @Override public synchronized void update(byte[] region, byte[] row, Pair<S, Long> result) { sum = ci.add(sum, result.getFirst()); rowCount += result.getSecond(); } } AvgCallBack avgCallBack = new AvgCallBack(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, Pair<S, Long>>() { @Override public Pair<S, Long> call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getAvg(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } Pair<S, Long> pair = new Pair<>(null, 0L); if (response.getFirstPartCount() == 0) { return pair; } ByteString b = response.getFirstPart(0); T t = getParsedGenericInstance(ci.getClass(), 4, b); S s = ci.getPromotedValueFromProto(t); pair.setFirst(s); ByteBuffer bb = ByteBuffer.allocate(8).put(getBytesFromResponse(response.getSecondPart())); bb.rewind(); pair.setSecond(bb.getLong()); return pair; } }, avgCallBack); return avgCallBack.getAvgArgs(); } /** * This is the client side interface/handle for calling the average method for a given cf-cq * combination. It was necessary to add one more call stack as its return type should be a decimal * value, irrespective of what columninterpreter says. So, this methods collects the necessary * parameters to compute the average and returs the double value. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return &lt;R, S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> double avg(final TableName tableName, final ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { Pair<S, Long> p = getAvgArgs(tableName, ci, scan); return ci.divideForAvg(p.getFirst(), p.getSecond()); } /** * This is the client side interface/handle for calling the average method for a given cf-cq * combination. It was necessary to add one more call stack as its return type should be a decimal * value, irrespective of what columninterpreter says. So, this methods collects the necessary * parameters to compute the average and returs the double value. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return &lt;R, S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> double avg(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { Pair<S, Long> p = getAvgArgs(table, ci, scan); return ci.divideForAvg(p.getFirst(), p.getSecond()); } /** * It computes a global standard deviation for a given column and its value. Standard deviation is * square root of (average of squares - average*average). From individual regions, it obtains sum, * square sum and number of rows. With these, the above values are computed to get the global std. * @param table table to scan. * @param scan the HBase scan object to use to read data from HBase * @return standard deviations * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ private <R, S, P extends Message, Q extends Message, T extends Message> Pair<List<S>, Long> getStdArgs(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false, false); class StdCallback implements Batch.Callback<Pair<List<S>, Long>> { long rowCountVal = 0L; S sumVal = null, sumSqVal = null; public synchronized Pair<List<S>, Long> getStdParams() { List<S> l = new ArrayList<>(2); l.add(sumVal); l.add(sumSqVal); Pair<List<S>, Long> p = new Pair<>(l, rowCountVal); return p; } @Override public synchronized void update(byte[] region, byte[] row, Pair<List<S>, Long> result) { if (result.getFirst().size() > 0) { sumVal = ci.add(sumVal, result.getFirst().get(0)); sumSqVal = ci.add(sumSqVal, result.getFirst().get(1)); rowCountVal += result.getSecond(); } } } StdCallback stdCallback = new StdCallback(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, Pair<List<S>, Long>>() { @Override public Pair<List<S>, Long> call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getStd(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } Pair<List<S>, Long> pair = new Pair<>(new ArrayList<>(), 0L); if (response.getFirstPartCount() == 0) { return pair; } List<S> list = new ArrayList<>(); for (int i = 0; i < response.getFirstPartCount(); i++) { ByteString b = response.getFirstPart(i); T t = getParsedGenericInstance(ci.getClass(), 4, b); S s = ci.getPromotedValueFromProto(t); list.add(s); } pair.setFirst(list); ByteBuffer bb = ByteBuffer.allocate(8).put(getBytesFromResponse(response.getSecondPart())); bb.rewind(); pair.setSecond(bb.getLong()); return pair; } }, stdCallback); return stdCallback.getStdParams(); } /** * This is the client side interface/handle for calling the std method for a given cf-cq * combination. It was necessary to add one more call stack as its return type should be a decimal * value, irrespective of what columninterpreter says. So, this methods collects the necessary * parameters to compute the std and returns the double value. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return &lt;R, S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> double std( final TableName tableName, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return std(table, ci, scan); } } /** * This is the client side interface/handle for calling the std method for a given cf-cq * combination. It was necessary to add one more call stack as its return type should be a decimal * value, irrespective of what columninterpreter says. So, this methods collects the necessary * parameters to compute the std and returns the double value. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return &lt;R, S&gt; * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> double std(final Table table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { Pair<List<S>, Long> p = getStdArgs(table, ci, scan); double avg = ci.divideForAvg(p.getFirst().get(0), p.getSecond()); double avgOfSumSq = ci.divideForAvg(p.getFirst().get(1), p.getSecond()); double res = avgOfSumSq - avg * avg; // variance res = Math.pow(res, 0.5); return res; } /** * It helps locate the region with median for a given column whose weight is specified in an * optional column. From individual regions, it obtains sum of values and sum of weights. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return pair whose first element is a map between start row of the region and (sum of values, * sum of weights) for the region, the second element is (sum of values, sum of weights) * for all the regions chosen * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ private <R, S, P extends Message, Q extends Message, T extends Message> Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianArgs(final Table table, final ColumnInterpreter<R, S, P, Q, T> ci, final Scan scan) throws Throwable { final AggregateRequest requestArg = validateArgAndGetPB(scan, ci, false, false); final NavigableMap<byte[], List<S>> map = new TreeMap<>(Bytes.BYTES_COMPARATOR); class StdCallback implements Batch.Callback<List<S>> { S sumVal = null, sumWeights = null; public synchronized Pair<NavigableMap<byte[], List<S>>, List<S>> getMedianParams() { List<S> l = new ArrayList<>(2); l.add(sumVal); l.add(sumWeights); Pair<NavigableMap<byte[], List<S>>, List<S>> p = new Pair<>(map, l); return p; } @Override public synchronized void update(byte[] region, byte[] row, List<S> result) { map.put(row, result); sumVal = ci.add(sumVal, result.get(0)); sumWeights = ci.add(sumWeights, result.get(1)); } } StdCallback stdCallback = new StdCallback(); table.coprocessorService(AggregateService.class, scan.getStartRow(), scan.getStopRow(), new Batch.Call<AggregateService, List<S>>() { @Override public List<S> call(AggregateService instance) throws IOException { RpcController controller = new AggregationClientRpcController(); CoprocessorRpcUtils.BlockingRpcCallback<AggregateResponse> rpcCallback = new CoprocessorRpcUtils.BlockingRpcCallback<>(); instance.getMedian(controller, requestArg, rpcCallback); AggregateResponse response = rpcCallback.get(); if (controller.failed()) { throw new IOException(controller.errorText()); } List<S> list = new ArrayList<>(); for (int i = 0; i < response.getFirstPartCount(); i++) { ByteString b = response.getFirstPart(i); T t = getParsedGenericInstance(ci.getClass(), 4, b); S s = ci.getPromotedValueFromProto(t); list.add(s); } return list; } }, stdCallback); return stdCallback.getMedianParams(); } /** * This is the client side interface/handler for calling the median method for a given cf-cq * combination. This method collects the necessary parameters to compute the median and returns * the median. * @param tableName the name of the table to scan * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return R the median * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> R median( final TableName tableName, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { try (Table table = getConnection().getTable(tableName)) { return median(table, ci, scan); } } /** * This is the client side interface/handler for calling the median method for a given cf-cq * combination. This method collects the necessary parameters to compute the median and returns * the median. * @param table table to scan. * @param ci the user's ColumnInterpreter implementation * @param scan the HBase scan object to use to read data from HBase * @return R the median * @throws Throwable The caller is supposed to handle the exception as they are thrown &amp; * propagated to it. */ public <R, S, P extends Message, Q extends Message, T extends Message> R median(final Table table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable { Pair<NavigableMap<byte[], List<S>>, List<S>> p = getMedianArgs(table, ci, scan); byte[] startRow = null; byte[] colFamily = scan.getFamilies()[0]; NavigableSet<byte[]> quals = scan.getFamilyMap().get(colFamily); NavigableMap<byte[], List<S>> map = p.getFirst(); S sumVal = p.getSecond().get(0); S sumWeights = p.getSecond().get(1); double halfSumVal = ci.divideForAvg(sumVal, 2L); double movingSumVal = 0; boolean weighted = false; if (quals.size() > 1) { weighted = true; halfSumVal = ci.divideForAvg(sumWeights, 2L); } for (Map.Entry<byte[], List<S>> entry : map.entrySet()) { S s = weighted ? entry.getValue().get(1) : entry.getValue().get(0); double newSumVal = movingSumVal + ci.divideForAvg(s, 1L); if (newSumVal > halfSumVal) { // we found the region with the median break; } movingSumVal = newSumVal; startRow = entry.getKey(); } // scan the region with median and find it Scan scan2 = new Scan(scan); // inherit stop row from method parameter if (startRow != null) { scan2.withStartRow(startRow); } ResultScanner scanner = null; try { int cacheSize = scan2.getCaching(); if (!scan2.getCacheBlocks() || scan2.getCaching() < 2) { scan2.setCacheBlocks(true); cacheSize = 5; scan2.setCaching(cacheSize); } scanner = table.getScanner(scan2); Result[] results = null; byte[] qualifier = quals.pollFirst(); // qualifier for the weight column byte[] weightQualifier = weighted ? quals.pollLast() : qualifier; R value = null; do { results = scanner.next(cacheSize); if (results != null && results.length > 0) { for (int i = 0; i < results.length; i++) { Result r = results[i]; // retrieve weight Cell kv = r.getColumnLatestCell(colFamily, weightQualifier); R newValue = ci.getValue(colFamily, weightQualifier, kv); S s = ci.castToReturnType(newValue); double newSumVal = movingSumVal + ci.divideForAvg(s, 1L); // see if we have moved past the median if (newSumVal > halfSumVal) { return value; } movingSumVal = newSumVal; kv = r.getColumnLatestCell(colFamily, qualifier); value = ci.getValue(colFamily, qualifier, kv); } } } while (results != null && results.length > 0); } finally { if (scanner != null) { scanner.close(); } } return null; } byte[] getBytesFromResponse(ByteString response) { return response.toByteArray(); } }
apache/hive
37,766
ql/src/test/org/apache/hadoop/hive/ql/exec/vector/expressions/TestVectorBetweenIn.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.hive.ql.exec.vector.expressions; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.apache.hadoop.hive.common.type.DataTypePhysicalVariation; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluator; import org.apache.hadoop.hive.ql.exec.ExprNodeEvaluatorFactory; import org.apache.hadoop.hive.ql.exec.FunctionInfo; import org.apache.hadoop.hive.ql.exec.FunctionRegistry; import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor; import org.apache.hadoop.hive.ql.exec.vector.VectorExtractRow; import org.apache.hadoop.hive.ql.exec.vector.VectorRandomBatchSource; import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource; import org.apache.hadoop.hive.ql.exec.vector.VectorizationContext; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatchCtx; import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource.GenerationSpec; import org.apache.hadoop.hive.ql.exec.vector.VectorRandomRowSource.SupportedTypes; import org.apache.hadoop.hive.ql.exec.vector.expressions.IdentityExpression; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression; import org.apache.hadoop.hive.ql.exec.vector.expressions.TestVectorArithmetic.ColumnScalarMode; import org.apache.hadoop.hive.ql.exec.vector.udf.VectorUDFAdaptor; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.metadata.VirtualColumn; import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBetween; import org.apache.hadoop.hive.ql.udf.generic.GenericUDFIn; import org.apache.hadoop.hive.serde2.io.DoubleWritable; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable; import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils.ObjectInspectorCopyOption; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; import org.apache.hadoop.hive.serde2.objectinspector.StandardStructObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo; import org.apache.hadoop.io.BooleanWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.io.WritableComparable; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class TestVectorBetweenIn { @Test public void testTinyInt() throws Exception { Random random = new Random(5371); doBetweenIn(random, "tinyint"); } @Test public void testSmallInt() throws Exception { Random random = new Random(2772); doBetweenIn(random, "smallint"); } @Test public void testInt() throws Exception { Random random = new Random(12882); doBetweenIn(random, "int"); } @Test public void testBigInt() throws Exception { Random random = new Random(12882); doBetweenIn(random, "bigint"); } @Test public void testString() throws Exception { Random random = new Random(12882); doBetweenIn(random, "string"); } @Test public void testTimestamp() throws Exception { Random random = new Random(12882); doBetweenIn(random, "timestamp"); } @Test public void testDate() throws Exception { Random random = new Random(12882); doBetweenIn(random, "date"); } @Test public void testFloat() throws Exception { Random random = new Random(7322); doBetweenIn(random, "float"); } @Test public void testDouble() throws Exception { Random random = new Random(12882); doBetweenIn(random, "double"); } @Test public void testChar() throws Exception { Random random = new Random(12882); doBetweenIn(random, "char(10)"); } @Test public void testVarchar() throws Exception { Random random = new Random(12882); doBetweenIn(random, "varchar(15)"); } @Test public void testDecimal() throws Exception { Random random = new Random(9300); doDecimalTests(random, /* tryDecimal64 */ false); } @Test public void testDecimal64() throws Exception { Random random = new Random(9300); doDecimalTests(random, /* tryDecimal64 */ true); } @Test public void testStruct() throws Exception { Random random = new Random(9300); doStructTests(random); } public enum BetweenInTestMode { ROW_MODE, ADAPTOR, VECTOR_EXPRESSION; static final int count = values().length; } public enum BetweenInVariation { FILTER_BETWEEN, FILTER_NOT_BETWEEN, PROJECTION_BETWEEN, PROJECTION_NOT_BETWEEN, FILTER_IN, PROJECTION_IN; static final int count = values().length; final boolean isFilter; BetweenInVariation() { isFilter = name().startsWith("FILTER"); } } private static TypeInfo[] decimalTypeInfos = new TypeInfo[] { new DecimalTypeInfo(38, 18), new DecimalTypeInfo(25, 2), new DecimalTypeInfo(19, 4), new DecimalTypeInfo(18, 10), new DecimalTypeInfo(17, 3), new DecimalTypeInfo(12, 2), new DecimalTypeInfo(7, 1) }; private void doDecimalTests(Random random, boolean tryDecimal64) throws Exception { for (TypeInfo typeInfo : decimalTypeInfos) { doBetweenIn( random, typeInfo.getTypeName(), tryDecimal64); } } private void doBetweenIn(Random random, String typeName) throws Exception { doBetweenIn(random, typeName, /* tryDecimal64 */ false); } private static final BetweenInVariation[] structInVarations = new BetweenInVariation[] { BetweenInVariation.FILTER_IN, BetweenInVariation.PROJECTION_IN }; private void doStructTests(Random random) throws Exception { String typeName = "struct"; // These are the only type supported for STRUCT IN by the VectorizationContext class. Set<String> allowedTypeNameSet = new HashSet<String>(); allowedTypeNameSet.add("int"); allowedTypeNameSet.add("bigint"); allowedTypeNameSet.add("double"); allowedTypeNameSet.add("string"); // Only STRUCT type IN currently supported. for (BetweenInVariation betweenInVariation : structInVarations) { for (int i = 0; i < 4; i++) { typeName = VectorRandomRowSource.getDecoratedTypeName( random, typeName, SupportedTypes.ALL, allowedTypeNameSet, /* depth */ 0, /* maxDepth */ 1); doBetweenStructInVariation( random, typeName, betweenInVariation); } } } private void doBetweenIn(Random random, String typeName, boolean tryDecimal64) throws Exception { int subVariation; for (BetweenInVariation betweenInVariation : BetweenInVariation.values()) { subVariation = 0; while (true) { if (!doBetweenInVariation( random, typeName, tryDecimal64, betweenInVariation, subVariation)) { break; } subVariation++; } } } private boolean checkDecimal64(boolean tryDecimal64, TypeInfo typeInfo) { if (!tryDecimal64 || !(typeInfo instanceof DecimalTypeInfo)) { return false; } DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo; boolean result = HiveDecimalWritable.isPrecisionDecimal64(decimalTypeInfo.getPrecision()); return result; } private void removeValue(List<Object> valueList, Object value) { valueList.remove(value); } private boolean needsValidDataTypeData(TypeInfo typeInfo) { if (!(typeInfo instanceof PrimitiveTypeInfo)) { return false; } PrimitiveCategory primitiveCategory = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory(); if (primitiveCategory == PrimitiveCategory.STRING || primitiveCategory == PrimitiveCategory.CHAR || primitiveCategory == PrimitiveCategory.VARCHAR || primitiveCategory == PrimitiveCategory.BINARY) { return false; } return true; } private boolean doBetweenInVariation(Random random, String typeName, boolean tryDecimal64, BetweenInVariation betweenInVariation, int subVariation) throws Exception { TypeInfo typeInfo = TypeInfoUtils.getTypeInfoFromTypeString(typeName); boolean isDecimal64 = checkDecimal64(tryDecimal64, typeInfo); DataTypePhysicalVariation dataTypePhysicalVariation = (isDecimal64 ? DataTypePhysicalVariation.DECIMAL_64 : DataTypePhysicalVariation.NONE); final int decimal64Scale = (isDecimal64 ? ((DecimalTypeInfo) typeInfo).getScale() : 0); //---------------------------------------------------------------------------------------------- ObjectInspector objectInspector = TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo( typeInfo); final int valueCount = 10 + random.nextInt(10); List<Object> valueList = new ArrayList<Object>(valueCount); for (int i = 0; i < valueCount; i++) { valueList.add( VectorRandomRowSource.randomWritable( random, typeInfo, objectInspector, dataTypePhysicalVariation, /* allowNull */ false)); } final boolean isBetween = (betweenInVariation == BetweenInVariation.FILTER_BETWEEN || betweenInVariation == BetweenInVariation.FILTER_NOT_BETWEEN || betweenInVariation == BetweenInVariation.PROJECTION_BETWEEN || betweenInVariation == BetweenInVariation.PROJECTION_NOT_BETWEEN); List<Object> compareList = new ArrayList<Object>(); List<Object> sortedList = new ArrayList<Object>(valueCount); sortedList.addAll(valueList); Object exampleObject = valueList.get(0); WritableComparator writableComparator = WritableComparator.get((Class<? extends WritableComparable>) exampleObject.getClass()); sortedList.sort(writableComparator); final boolean isInvert; if (isBetween) { // FILTER_BETWEEN // FILTER_NOT_BETWEEN // PROJECTION_BETWEEN // PROJECTION_NOT_BETWEEN isInvert = (betweenInVariation == BetweenInVariation.FILTER_NOT_BETWEEN || betweenInVariation == BetweenInVariation.PROJECTION_NOT_BETWEEN); switch (subVariation) { case 0: // Range covers all values exactly. compareList.add(sortedList.get(0)); compareList.add(sortedList.get(valueCount - 1)); break; case 1: // Exclude the first and last sorted. compareList.add(sortedList.get(1)); compareList.add(sortedList.get(valueCount - 2)); break; case 2: // Only last 2 sorted. compareList.add(sortedList.get(valueCount - 2)); compareList.add(sortedList.get(valueCount - 1)); break; case 3: case 4: case 5: case 6: { // Choose 2 adjacent in the middle. Object min = sortedList.get(5); Object max = sortedList.get(6); compareList.add(min); compareList.add(max); if (subVariation == 4) { removeValue(valueList, min); } else if (subVariation == 5) { removeValue(valueList, max); } else if (subVariation == 6) { removeValue(valueList, min); removeValue(valueList, max); } } break; default: return false; } } else { // FILTER_IN. // PROJECTION_IN. isInvert = false; switch (subVariation) { case 0: // All values. compareList.addAll(valueList); break; case 1: // Don't include the first and last sorted. for (int i = 1; i < valueCount - 1; i++) { compareList.add(valueList.get(i)); } break; case 2: // The even ones. for (int i = 2; i < valueCount; i += 2) { compareList.add(valueList.get(i)); } break; case 3: { // Choose 2 adjacent in the middle. Object min = sortedList.get(5); Object max = sortedList.get(6); compareList.add(min); compareList.add(max); if (subVariation == 4) { removeValue(valueList, min); } else if (subVariation == 5) { removeValue(valueList, max); } else if (subVariation == 6) { removeValue(valueList, min); removeValue(valueList, max); } } break; default: return false; } } //---------------------------------------------------------------------------------------------- GenerationSpec generationSpec = GenerationSpec.createValueList(typeInfo, valueList); List<GenerationSpec> generationSpecList = new ArrayList<GenerationSpec>(); List<DataTypePhysicalVariation> explicitDataTypePhysicalVariationList = new ArrayList<DataTypePhysicalVariation>(); generationSpecList.add(generationSpec); explicitDataTypePhysicalVariationList.add(dataTypePhysicalVariation); VectorRandomRowSource rowSource = new VectorRandomRowSource(); rowSource.initGenerationSpecSchema( random, generationSpecList, /* maxComplexDepth */ 0, /* allowNull */ true, /* isUnicodeOk */ true, explicitDataTypePhysicalVariationList); List<String> columns = new ArrayList<String>(); String col1Name = rowSource.columnNames().get(0); columns.add(col1Name); final ExprNodeDesc col1Expr = new ExprNodeColumnDesc(typeInfo, col1Name, "table", false); List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>(); if (isBetween) { children.add(new ExprNodeConstantDesc(Boolean.valueOf(isInvert))); } children.add(col1Expr); for (Object compareObject : compareList) { ExprNodeConstantDesc constDesc = new ExprNodeConstantDesc( typeInfo, VectorRandomRowSource.getNonWritableObject( compareObject, typeInfo, objectInspector)); children.add(constDesc); } String[] columnNames = columns.toArray(new String[0]); Object[][] randomRows = rowSource.randomRows(100000); VectorRandomBatchSource batchSource = VectorRandomBatchSource.createInterestingBatches( random, rowSource, randomRows, null); final GenericUDF udf; final ObjectInspector outputObjectInspector; if (isBetween) { udf = new GenericUDFBetween(); // First argument is boolean invert. Arguments 1..3 are inspectors for range limits... ObjectInspector[] argumentOIs = new ObjectInspector[4]; argumentOIs[0] = PrimitiveObjectInspectorFactory.writableBooleanObjectInspector; argumentOIs[1] = objectInspector; argumentOIs[2] = objectInspector; argumentOIs[3] = objectInspector; outputObjectInspector = udf.initialize(argumentOIs); } else { final int compareCount = compareList.size(); udf = new GenericUDFIn(); ObjectInspector[] argumentOIs = new ObjectInspector[compareCount]; ConstantObjectInspector constantObjectInspector = (ConstantObjectInspector) children.get(1).getWritableObjectInspector(); for (int i = 0; i < compareCount; i++) { argumentOIs[i] = constantObjectInspector; } outputObjectInspector = udf.initialize(argumentOIs); } TypeInfo outputTypeInfo = TypeInfoUtils.getTypeInfoFromObjectInspector(outputObjectInspector); ExprNodeGenericFuncDesc exprDesc = new ExprNodeGenericFuncDesc( TypeInfoFactory.booleanTypeInfo, udf, children); return executeTestModesAndVerify( typeInfo, betweenInVariation, compareList, columns, columnNames, children, udf, exprDesc, randomRows, rowSource, batchSource, outputTypeInfo, /* skipAdaptor */ false); } private boolean doBetweenStructInVariation(Random random, String structTypeName, BetweenInVariation betweenInVariation) throws Exception { StructTypeInfo structTypeInfo = (StructTypeInfo) TypeInfoUtils.getTypeInfoFromTypeString(structTypeName); ObjectInspector structObjectInspector = TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo( structTypeInfo); final int valueCount = 10 + random.nextInt(10); List<Object> valueList = new ArrayList<Object>(valueCount); for (int i = 0; i < valueCount; i++) { valueList.add( VectorRandomRowSource.randomWritable( random, structTypeInfo, structObjectInspector, DataTypePhysicalVariation.NONE, /* allowNull */ false)); } final boolean isInvert = false; // No convenient WritableComparator / WritableComparable available for STRUCT. List<Object> compareList = new ArrayList<Object>(); Set<Integer> includedSet = new HashSet<Integer>(); final int chooseLimit = 4 + random.nextInt(valueCount/2); int chooseCount = 0; while (chooseCount < chooseLimit) { final int index = random.nextInt(valueCount); if (includedSet.contains(index)) { continue; } includedSet.add(index); compareList.add(valueList.get(index)); chooseCount++; } //---------------------------------------------------------------------------------------------- GenerationSpec structGenerationSpec = GenerationSpec.createValueList(structTypeInfo, valueList); List<GenerationSpec> structGenerationSpecList = new ArrayList<GenerationSpec>(); List<DataTypePhysicalVariation> structExplicitDataTypePhysicalVariationList = new ArrayList<DataTypePhysicalVariation>(); structGenerationSpecList.add(structGenerationSpec); structExplicitDataTypePhysicalVariationList.add(DataTypePhysicalVariation.NONE); VectorRandomRowSource structRowSource = new VectorRandomRowSource(); structRowSource.initGenerationSpecSchema( random, structGenerationSpecList, /* maxComplexDepth */ 0, /* allowNull */ true, /* isUnicodeOk */ true, structExplicitDataTypePhysicalVariationList); Object[][] structRandomRows = structRowSource.randomRows(100000); // --------------------------------------------------------------------------------------------- List<GenerationSpec> generationSpecList = new ArrayList<GenerationSpec>(); List<DataTypePhysicalVariation> explicitDataTypePhysicalVariationList = new ArrayList<DataTypePhysicalVariation>(); List<TypeInfo> fieldTypeInfoList = structTypeInfo.getAllStructFieldTypeInfos(); final int fieldCount = fieldTypeInfoList.size(); for (int i = 0; i < fieldCount; i++) { GenerationSpec generationSpec = GenerationSpec.createOmitGeneration(fieldTypeInfoList.get(i)); generationSpecList.add(generationSpec); explicitDataTypePhysicalVariationList.add(DataTypePhysicalVariation.NONE); } VectorRandomRowSource rowSource = new VectorRandomRowSource(); rowSource.initGenerationSpecSchema( random, generationSpecList, /* maxComplexDepth */ 0, /* allowNull */ true, /* isUnicodeOk */ true, explicitDataTypePhysicalVariationList); Object[][] randomRows = rowSource.randomRows(100000); final int rowCount = randomRows.length; for (int r = 0; r < rowCount; r++) { List<Object> fieldValueList = (ArrayList) structRandomRows[r][0]; for (int f = 0; f < fieldCount; f++) { randomRows[r][f] = fieldValueList.get(f); } } // --------------------------------------------------------------------------------------------- // Currently, STRUCT IN vectorization assumes a GenericUDFStruct. List<ObjectInspector> structUdfObjectInspectorList = new ArrayList<ObjectInspector>(); List<ExprNodeDesc> structUdfChildren = new ArrayList<ExprNodeDesc>(fieldCount); List<String> rowColumnNameList = rowSource.columnNames(); for (int i = 0; i < fieldCount; i++) { TypeInfo fieldTypeInfo = fieldTypeInfoList.get(i); ExprNodeColumnDesc fieldExpr = new ExprNodeColumnDesc( fieldTypeInfo, rowColumnNameList.get(i), "table", false); structUdfChildren.add(fieldExpr); ObjectInspector fieldObjectInspector = VectorRandomRowSource.getObjectInspector(fieldTypeInfo, DataTypePhysicalVariation.NONE); structUdfObjectInspectorList.add(fieldObjectInspector); } StandardStructObjectInspector structUdfObjectInspector = ObjectInspectorFactory. getStandardStructObjectInspector(rowColumnNameList, structUdfObjectInspectorList); String structUdfTypeName = structUdfObjectInspector.getTypeName(); TypeInfo structUdfTypeInfo = TypeInfoUtils.getTypeInfoFromTypeString(structUdfTypeName); String structFuncText = "struct"; FunctionInfo fi = FunctionRegistry.getFunctionInfo(structFuncText); GenericUDF genericUDF = fi.getGenericUDF(); ExprNodeDesc col1Expr = new ExprNodeGenericFuncDesc( structUdfObjectInspector, genericUDF, structFuncText, structUdfChildren); // --------------------------------------------------------------------------------------------- List<String> columns = new ArrayList<String>(); List<ExprNodeDesc> children = new ArrayList<ExprNodeDesc>(); children.add(col1Expr); for (int i = 0; i < compareList.size(); i++) { Object compareObject = compareList.get(i); ExprNodeConstantDesc constDesc = new ExprNodeConstantDesc( structUdfTypeInfo, VectorRandomRowSource.getNonWritableObject( compareObject, structUdfTypeInfo, structUdfObjectInspector)); children.add(constDesc); } for (int i = 0; i < fieldCount; i++) { columns.add(rowColumnNameList.get(i)); } String[] columnNames = columns.toArray(new String[0]); VectorRandomBatchSource batchSource = VectorRandomBatchSource.createInterestingBatches( random, rowSource, randomRows, null); // --------------------------------------------------------------------------------------------- final GenericUDF udf = new GenericUDFIn(); final int compareCount = compareList.size(); ObjectInspector[] argumentOIs = new ObjectInspector[compareCount]; for (int i = 0; i < compareCount; i++) { argumentOIs[i] = structUdfObjectInspector; } final ObjectInspector outputObjectInspector = udf.initialize(argumentOIs); TypeInfo outputTypeInfo = TypeInfoUtils.getTypeInfoFromObjectInspector(outputObjectInspector); ExprNodeGenericFuncDesc exprDesc = new ExprNodeGenericFuncDesc( TypeInfoFactory.booleanTypeInfo, udf, children); return executeTestModesAndVerify( structUdfTypeInfo, betweenInVariation, compareList, columns, columnNames, children, udf, exprDesc, randomRows, rowSource, batchSource, outputTypeInfo, /* skipAdaptor */ true); } private boolean executeTestModesAndVerify(TypeInfo typeInfo, BetweenInVariation betweenInVariation, List<Object> compareList, List<String> columns, String[] columnNames, List<ExprNodeDesc> children, GenericUDF udf, ExprNodeGenericFuncDesc exprDesc, Object[][] randomRows, VectorRandomRowSource rowSource, VectorRandomBatchSource batchSource, TypeInfo outputTypeInfo, boolean skipAdaptor) throws Exception { final int rowCount = randomRows.length; Object[][] resultObjectsArray = new Object[BetweenInTestMode.count][]; for (int i = 0; i < BetweenInTestMode.count; i++) { Object[] resultObjects = new Object[rowCount]; resultObjectsArray[i] = resultObjects; BetweenInTestMode betweenInTestMode = BetweenInTestMode.values()[i]; switch (betweenInTestMode) { case ROW_MODE: if (!doRowCastTest( typeInfo, betweenInVariation, compareList, columns, children, udf, exprDesc, randomRows, rowSource.rowStructObjectInspector(), resultObjects)) { return false; } break; case ADAPTOR: if (skipAdaptor) { continue; } case VECTOR_EXPRESSION: if (!doVectorBetweenInTest( typeInfo, betweenInVariation, compareList, columns, columnNames, rowSource.typeInfos(), rowSource.dataTypePhysicalVariations(), children, udf, exprDesc, betweenInTestMode, batchSource, exprDesc.getWritableObjectInspector(), outputTypeInfo, resultObjects)) { return false; } break; default: throw new RuntimeException("Unexpected IF statement test mode " + betweenInTestMode); } } for (int i = 0; i < rowCount; i++) { // Row-mode is the expected value. Object expectedResult = resultObjectsArray[0][i]; for (int v = 1; v < BetweenInTestMode.count; v++) { BetweenInTestMode betweenInTestMode = BetweenInTestMode.values()[v]; if (skipAdaptor) { continue; } Object vectorResult = resultObjectsArray[v][i]; if (betweenInVariation.isFilter && expectedResult == null && vectorResult != null) { // This is OK. boolean vectorBoolean = ((BooleanWritable) vectorResult).get(); if (vectorBoolean) { Assert.fail( "Row " + i + " typeName " + typeInfo.getTypeName() + " outputTypeName " + outputTypeInfo.getTypeName() + " " + betweenInVariation + " " + betweenInTestMode + " result is NOT NULL and true" + " does not match row-mode expected result is NULL which means false here" + " row values " + Arrays.toString(randomRows[i]) + " exprDesc " + exprDesc.toString()); } } else if (expectedResult == null || vectorResult == null) { if (expectedResult != null || vectorResult != null) { Assert.fail( "Row " + i + " sourceTypeName " + typeInfo.getTypeName() + " " + betweenInVariation + " " + betweenInTestMode + " result is NULL " + (vectorResult == null ? "YES" : "NO result " + vectorResult.toString()) + " does not match row-mode expected result is NULL " + (expectedResult == null ? "YES" : "NO result " + expectedResult.toString()) + " row values " + Arrays.toString(randomRows[i]) + " exprDesc " + exprDesc.toString()); } } else { if (!expectedResult.equals(vectorResult)) { Assert.fail( "Row " + i + " sourceTypeName " + typeInfo.getTypeName() + " " + betweenInVariation + " " + betweenInTestMode + " result " + vectorResult.toString() + " (" + vectorResult.getClass().getSimpleName() + ")" + " does not match row-mode expected result " + expectedResult.toString() + " (" + expectedResult.getClass().getSimpleName() + ")" + " row values " + Arrays.toString(randomRows[i]) + " exprDesc " + exprDesc.toString()); } } } } return true; } private boolean doRowCastTest(TypeInfo typeInfo, BetweenInVariation betweenInVariation, List<Object> compareList, List<String> columns, List<ExprNodeDesc> children, GenericUDF udf, ExprNodeGenericFuncDesc exprDesc, Object[][] randomRows, ObjectInspector rowInspector, Object[] resultObjects) throws Exception { /* System.out.println( "*DEBUG* typeInfo " + typeInfo.toString() + " targetTypeInfo " + targetTypeInfo + " betweenInTestMode ROW_MODE" + " exprDesc " + exprDesc.toString()); */ HiveConf hiveConf = new HiveConf(); ExprNodeEvaluator evaluator = ExprNodeEvaluatorFactory.get(exprDesc, hiveConf); evaluator.initialize(rowInspector); final int rowCount = randomRows.length; for (int i = 0; i < rowCount; i++) { Object[] row = randomRows[i]; Object result = evaluator.evaluate(row); Object copyResult = ObjectInspectorUtils.copyToStandardObject( result, PrimitiveObjectInspectorFactory.writableBooleanObjectInspector, ObjectInspectorCopyOption.WRITABLE); resultObjects[i] = copyResult; } return true; } private void extractResultObjects(VectorizedRowBatch batch, int rowIndex, VectorExtractRow resultVectorExtractRow, Object[] scrqtchRow, ObjectInspector objectInspector, Object[] resultObjects) { boolean selectedInUse = batch.selectedInUse; int[] selected = batch.selected; for (int logicalIndex = 0; logicalIndex < batch.size; logicalIndex++) { final int batchIndex = (selectedInUse ? selected[logicalIndex] : logicalIndex); resultVectorExtractRow.extractRow(batch, batchIndex, scrqtchRow); Object copyResult = ObjectInspectorUtils.copyToStandardObject( scrqtchRow[0], objectInspector, ObjectInspectorCopyOption.WRITABLE); resultObjects[rowIndex++] = copyResult; } } private boolean doVectorBetweenInTest(TypeInfo typeInfo, BetweenInVariation betweenInVariation, List<Object> compareList, List<String> columns, String[] columnNames, TypeInfo[] typeInfos, DataTypePhysicalVariation[] dataTypePhysicalVariations, List<ExprNodeDesc> children, GenericUDF udf, ExprNodeGenericFuncDesc exprDesc, BetweenInTestMode betweenInTestMode, VectorRandomBatchSource batchSource, ObjectInspector objectInspector, TypeInfo outputTypeInfo, Object[] resultObjects) throws Exception { HiveConf hiveConf = new HiveConf(); if (betweenInTestMode == BetweenInTestMode.ADAPTOR) { hiveConf.setBoolVar(HiveConf.ConfVars.HIVE_TEST_VECTOR_ADAPTOR_OVERRIDE, true); } final boolean isFilter = betweenInVariation.isFilter; VectorizationContext vectorizationContext = new VectorizationContext( "name", columns, Arrays.asList(typeInfos), Arrays.asList(dataTypePhysicalVariations), hiveConf); VectorExpression vectorExpression = vectorizationContext.getVectorExpression(exprDesc, (isFilter ? VectorExpressionDescriptor.Mode.FILTER : VectorExpressionDescriptor.Mode.PROJECTION)); vectorExpression.transientInit(hiveConf); if (betweenInTestMode == BetweenInTestMode.VECTOR_EXPRESSION) { String vecExprString = vectorExpression.toString(); if (vectorExpression instanceof VectorUDFAdaptor) { System.out.println( "*NO NATIVE VECTOR EXPRESSION* typeInfo " + typeInfo.toString() + " betweenInTestMode " + betweenInTestMode + " betweenInVariation " + betweenInVariation + " vectorExpression " + vecExprString); } else if (dataTypePhysicalVariations[0] == DataTypePhysicalVariation.DECIMAL_64) { final String nameToCheck = vectorExpression.getClass().getSimpleName(); if (!nameToCheck.contains("Decimal64")) { System.out.println( "*EXPECTED DECIMAL_64 VECTOR EXPRESSION* typeInfo " + typeInfo.toString() + " betweenInTestMode " + betweenInTestMode + " betweenInVariation " + betweenInVariation + " vectorExpression " + vecExprString); } } } // System.out.println("*VECTOR EXPRESSION* " + vectorExpression.getClass().getSimpleName()); /* System.out.println( "*DEBUG* typeInfo " + typeInfo.toString() + " betweenInTestMode " + betweenInTestMode + " betweenInVariation " + betweenInVariation + " vectorExpression " + vectorExpression.toString()); */ VectorRandomRowSource rowSource = batchSource.getRowSource(); VectorizedRowBatchCtx batchContext = new VectorizedRowBatchCtx( columnNames, rowSource.typeInfos(), rowSource.dataTypePhysicalVariations(), /* dataColumnNums */ null, /* partitionColumnCount */ 0, /* virtualColumnCount */ 0, /* neededVirtualColumns */ null, vectorizationContext.getScratchColumnTypeNames(), vectorizationContext.getScratchDataTypePhysicalVariations()); VectorizedRowBatch batch = batchContext.createVectorizedRowBatch(); VectorExtractRow resultVectorExtractRow = null; Object[] scrqtchRow = null; if (!isFilter) { resultVectorExtractRow = new VectorExtractRow(); final int outputColumnNum = vectorExpression.getOutputColumnNum(); resultVectorExtractRow.init( new TypeInfo[] { outputTypeInfo }, new int[] { outputColumnNum }); scrqtchRow = new Object[1]; } boolean copySelectedInUse = false; int[] copySelected = new int[VectorizedRowBatch.DEFAULT_SIZE]; batchSource.resetBatchIteration(); int rowIndex = 0; while (true) { if (!batchSource.fillNextBatch(batch)) { break; } final int originalBatchSize = batch.size; if (isFilter) { copySelectedInUse = batch.selectedInUse; if (batch.selectedInUse) { System.arraycopy(batch.selected, 0, copySelected, 0, originalBatchSize); } } // In filter mode, the batch size can be made smaller. vectorExpression.evaluate(batch); if (!isFilter) { extractResultObjects(batch, rowIndex, resultVectorExtractRow, scrqtchRow, objectInspector, resultObjects); } else { final int currentBatchSize = batch.size; if (copySelectedInUse && batch.selectedInUse) { int selectIndex = 0; for (int i = 0; i < originalBatchSize; i++) { final int originalBatchIndex = copySelected[i]; final boolean booleanResult; if (selectIndex < currentBatchSize && batch.selected[selectIndex] == originalBatchIndex) { booleanResult = true; selectIndex++; } else { booleanResult = false; } resultObjects[rowIndex + i] = new BooleanWritable(booleanResult); } } else if (batch.selectedInUse) { int selectIndex = 0; for (int i = 0; i < originalBatchSize; i++) { final boolean booleanResult; if (selectIndex < currentBatchSize && batch.selected[selectIndex] == i) { booleanResult = true; selectIndex++; } else { booleanResult = false; } resultObjects[rowIndex + i] = new BooleanWritable(booleanResult); } } else if (currentBatchSize == 0) { // Whole batch got zapped. for (int i = 0; i < originalBatchSize; i++) { resultObjects[rowIndex + i] = new BooleanWritable(false); } } else { // Every row kept. for (int i = 0; i < originalBatchSize; i++) { resultObjects[rowIndex + i] = new BooleanWritable(true); } } } rowIndex += originalBatchSize; } return true; } }
apache/ofbiz-framework
37,415
applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.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.accounting.thirdparty.sagepay; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilProperties; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.entity.Delegator; import org.apache.ofbiz.entity.GenericEntityException; import org.apache.ofbiz.entity.GenericValue; import org.apache.ofbiz.entity.util.EntityQuery; import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.ModelService; import org.apache.ofbiz.service.ServiceUtil; public class SagePayServices { private static final String MODULE = SagePayServices.class.getName(); private static final String RESOURCE = "AccountingUiLabels"; private static Map<String, String> buildSagePayProperties(Map<String, Object> context, Delegator delegator) { Map<String, String> sagePayConfig = new HashMap<>(); String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId"); if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { try { GenericValue sagePay = EntityQuery.use(delegator).from("PaymentGatewaySagePay").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); if (sagePay != null) { for (Entry<String, Object> set : sagePay.entrySet()) { if (set.getValue() == null) { sagePayConfig.put(set.getKey(), null); } else { sagePayConfig.put(set.getKey(), set.getValue().toString()); } } } } catch (GenericEntityException e) { Debug.logError(e, MODULE); } } Debug.logInfo("SagePay Configuration : " + sagePayConfig.toString(), MODULE); return sagePayConfig; } public static Map<String, Object> paymentAuthentication(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentAuthentication", MODULE); Debug.logInfo("SagePay paymentAuthentication context : " + context, MODULE); Delegator delegator = ctx.getDelegator(); Map<String, Object> resultMap = new HashMap<>(); Map<String, String> props = buildSagePayProperties(context, delegator); String vendorTxCode = (String) context.get("vendorTxCode"); String cardHolder = (String) context.get("cardHolder"); String cardNumber = (String) context.get("cardNumber"); String expiryDate = (String) context.get("expiryDate"); String cardType = (String) context.get("cardType"); String cv2 = (String) context.get("cv2"); String amount = (String) context.get("amount"); String currency = (String) context.get("currency"); String description = (String) context.get("description"); String billingSurname = (String) context.get("billingSurname"); String billingFirstnames = (String) context.get("billingFirstnames"); String billingAddress = (String) context.get("billingAddress"); String billingAddress2 = (String) context.get("billingAddress2"); String billingCity = (String) context.get("billingCity"); String billingPostCode = (String) context.get("billingPostCode"); String billingCountry = (String) context.get("billingCountry"); String billingState = (String) context.get("billingState"); String billingPhone = (String) context.get("billingPhone"); Boolean isBillingSameAsDelivery = (Boolean) context.get("isBillingSameAsDelivery"); String deliverySurname = (String) context.get("deliverySurname"); String deliveryFirstnames = (String) context.get("deliveryFirstnames"); String deliveryAddress = (String) context.get("deliveryAddress"); String deliveryAddress2 = (String) context.get("deliveryAddress2"); String deliveryCity = (String) context.get("deliveryCity"); String deliveryPostCode = (String) context.get("deliveryPostCode"); String deliveryCountry = (String) context.get("deliveryCountry"); String deliveryState = (String) context.get("deliveryState"); String deliveryPhone = (String) context.get("deliveryPhone"); String startDate = (String) context.get("startDate"); String issueNumber = (String) context.get("issueNumber"); String basket = (String) context.get("basket"); String clientIPAddress = (String) context.get("clientIPAddress"); Locale locale = (Locale) context.get("locale"); HttpHost host = SagePayUtil.getHost(props); //start - authentication parameters Map<String, String> parameters = new HashMap<>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); String txType = props.get("authenticationTransType"); //start - required parameters StringBuilder errorRequiredParameters = new StringBuilder(); if (vpsProtocol == null) { errorRequiredParameters.append("Required transaction parameter 'protocolVersion' is missing. "); } if (vendor == null) { errorRequiredParameters.append("Required transaction parameter 'vendor' is missing. "); } if (txType == null) { errorRequiredParameters.append("Required transaction parameter 'authenticationsTransType' is missing. "); } if (errorRequiredParameters.length() > 0) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentAuthorisationException", UtilMisc.toMap("errorString", errorRequiredParameters), locale)); } parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", txType); parameters.put("Vendor", vendor); if (vendorTxCode != null) { parameters.put("VendorTxCode", vendorTxCode); } if (amount != null) { parameters.put("Amount", amount); } if (currency != null) { parameters.put("Currency", currency); } //GBP/USD if (description != null) { parameters.put("Description", description); } if (cardHolder != null) { parameters.put("CardHolder", cardHolder); } if (cardNumber != null) { parameters.put("CardNumber", cardNumber); } if (cardType != null) { parameters.put("CardType", cardType); } if (expiryDate != null) { parameters.put("ExpiryDate", expiryDate); } //start - billing details if (billingSurname != null) { parameters.put("BillingSurname", billingSurname); } if (billingFirstnames != null) { parameters.put("BillingFirstnames", billingFirstnames); } if (billingAddress != null) { parameters.put("BillingAddress", billingAddress); } if (billingAddress2 != null) { parameters.put("BillingAddress2", billingAddress2); } if (billingCity != null) { parameters.put("BillingCity", billingCity); } if (billingPostCode != null) { parameters.put("BillingPostCode", billingPostCode); } if (billingCountry != null) { parameters.put("BillingCountry", billingCountry); } if (billingState != null) { parameters.put("BillingState", billingState); } if (billingPhone != null) { parameters.put("BillingPhone", billingPhone); } //end - billing details //start - delivery details if (isBillingSameAsDelivery != null && isBillingSameAsDelivery) { if (billingSurname != null) { parameters.put("DeliverySurname", billingSurname); } if (billingFirstnames != null) { parameters.put("DeliveryFirstnames", billingFirstnames); } if (billingAddress != null) { parameters.put("DeliveryAddress", billingAddress); } if (billingAddress2 != null) { parameters.put("DeliveryAddress2", billingAddress2); } if (billingCity != null) { parameters.put("DeliveryCity", billingCity); } if (billingPostCode != null) { parameters.put("DeliveryPostCode", billingPostCode); } if (billingCountry != null) { parameters.put("DeliveryCountry", billingCountry); } if (billingState != null) { parameters.put("DeliveryState", billingState); } if (billingPhone != null) { parameters.put("DeliveryPhone", billingPhone); } } else { if (deliverySurname != null) { parameters.put("DeliverySurname", deliverySurname); } if (deliveryFirstnames != null) { parameters.put("DeliveryFirstnames", deliveryFirstnames); } if (deliveryAddress != null) { parameters.put("DeliveryAddress", deliveryAddress); } if (deliveryAddress2 != null) { parameters.put("DeliveryAddress2", deliveryAddress2); } if (deliveryCity != null) { parameters.put("DeliveryCity", deliveryCity); } if (deliveryPostCode != null) { parameters.put("DeliveryPostCode", deliveryPostCode); } if (deliveryCountry != null) { parameters.put("DeliveryCountry", deliveryCountry); } if (deliveryState != null) { parameters.put("DeliveryState", deliveryState); } if (deliveryPhone != null) { parameters.put("DeliveryPhone", deliveryPhone); } } //end - delivery details //end - required parameters //start - optional parameters if (cv2 != null) { parameters.put("CV2", cv2); } if (startDate != null) { parameters.put("StartDate", startDate); } if (issueNumber != null) { parameters.put("IssueNumber", issueNumber); } if (basket != null) { parameters.put("Basket", basket); } if (clientIPAddress != null) { parameters.put("ClientIPAddress", clientIPAddress); } //end - optional parameters //end - authentication parameters try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authenticationUrl"), parameters); HttpResponse response = httpClient.execute(host, httpPost); Map<String, String> responseData = SagePayUtil.getResponseData(response); String status = responseData.get("Status"); String statusDetail = responseData.get("StatusDetail"); resultMap.put("status", status); resultMap.put("statusDetail", statusDetail); //returning the below details back to the calling code, as it not returned back by the payment gateway resultMap.put("vendorTxCode", vendorTxCode); resultMap.put("amount", amount); resultMap.put("transactionType", txType); //start - transaction authorized if ("OK".equals(status)) { resultMap.put("vpsTxId", responseData.get("VPSTxId")); resultMap.put("securityKey", responseData.get("SecurityKey")); resultMap.put("txAuthNo", responseData.get("TxAuthNo")); resultMap.put("avsCv2", responseData.get("AVSCV2")); resultMap.put("addressResult", responseData.get("AddressResult")); resultMap.put("postCodeResult", responseData.get("PostCodeResult")); resultMap.put("cv2Result", responseData.get("CV2Result")); successMessage = "Payment authorized"; } //end - transaction authorized if ("NOTAUTHED".equals(status)) { resultMap.put("vpsTxId", responseData.get("VPSTxId")); resultMap.put("securityKey", responseData.get("SecurityKey")); resultMap.put("avsCv2", responseData.get("AVSCV2")); resultMap.put("addressResult", responseData.get("AddressResult")); resultMap.put("postCodeResult", responseData.get("PostCodeResult")); resultMap.put("cv2Result", responseData.get("CV2Result")); successMessage = "Payment not authorized"; } if ("MALFORMED".equals(status)) { //request not formed properly or parameters missing resultMap.put("vpsTxId", responseData.get("VPSTxId")); resultMap.put("securityKey", responseData.get("SecurityKey")); resultMap.put("avsCv2", responseData.get("AVSCV2")); resultMap.put("addressResult", responseData.get("AddressResult")); resultMap.put("postCodeResult", responseData.get("PostCodeResult")); resultMap.put("cv2Result", responseData.get("CV2Result")); } if ("INVALID".equals(status)) { //invalid information in request resultMap.put("vpsTxId", responseData.get("VPSTxId")); resultMap.put("securityKey", responseData.get("SecurityKey")); resultMap.put("avsCv2", responseData.get("AVSCV2")); resultMap.put("addressResult", responseData.get("AddressResult")); resultMap.put("postCodeResult", responseData.get("PostCodeResult")); resultMap.put("cv2Result", responseData.get("CV2Result")); } if ("REJECTED".equals(status)) { //invalid information in request resultMap.put("vpsTxId", responseData.get("VPSTxId")); resultMap.put("securityKey", responseData.get("SecurityKey")); resultMap.put("avsCv2", responseData.get("AVSCV2")); resultMap.put("addressResult", responseData.get("AddressResult")); resultMap.put("postCodeResult", responseData.get("PostCodeResult")); resultMap.put("cv2Result", responseData.get("CV2Result")); } resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage); } catch (UnsupportedEncodingException uee) { //exception in encoding parameters in httpPost Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale)); } catch (ClientProtocolException cpe) { //from httpClient execute Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale)); } catch (IOException ioe) { //from httpClient execute or getResponsedata Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } return resultMap; } public static Map<String, Object> paymentAuthorisation(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentAuthorisation", MODULE); Debug.logInfo("SagePay paymentAuthorisation context : " + context, MODULE); Delegator delegator = ctx.getDelegator(); Map<String, Object> resultMap = new HashMap<>(); Map<String, String> props = buildSagePayProperties(context, delegator); String vendorTxCode = (String) context.get("vendorTxCode"); String vpsTxId = (String) context.get("vpsTxId"); String securityKey = (String) context.get("securityKey"); String txAuthNo = (String) context.get("txAuthNo"); String amount = (String) context.get("amount"); Locale locale = (Locale) context.get("locale"); HttpHost host = SagePayUtil.getHost(props); //start - authorization parameters Map<String, String> parameters = new HashMap<>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); String txType = props.get("authoriseTransType"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", txType); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("VPSTxId", vpsTxId); parameters.put("SecurityKey", securityKey); parameters.put("TxAuthNo", txAuthNo); parameters.put("ReleaseAmount", amount); Debug.logInfo("authorization parameters -> " + parameters, MODULE); //end - authorization parameters try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authoriseUrl"), parameters); HttpResponse response = httpClient.execute(host, httpPost); Map<String, String> responseData = SagePayUtil.getResponseData(response); String status = responseData.get("Status"); String statusDetail = responseData.get("StatusDetail"); resultMap.put("status", status); resultMap.put("statusDetail", statusDetail); //start - payment refunded if ("OK".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentReleased", locale); } //end - payment refunded //start - refund request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentReleaseRequestMalformed", locale); } //end - refund request not formed properly or parameters missing //start - invalid information passed in parameters if ("INVALID".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentInvalidInformationPassed", locale); } //end - invalid information passed in parameters //start - problem at Sagepay if ("ERROR".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentError", locale); } //end - problem at Sagepay resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage); } catch (UnsupportedEncodingException uee) { //exception in encoding parameters in httpPost Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale)); } catch (ClientProtocolException cpe) { //from httpClient execute Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale)); } catch (IOException ioe) { //from httpClient execute or getResponsedata Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } return resultMap; } public static Map<String, Object> paymentRelease(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentRelease", MODULE); Debug.logInfo("SagePay paymentRelease context : " + context, MODULE); Delegator delegator = ctx.getDelegator(); Map<String, Object> resultMap = new HashMap<>(); Map<String, String> props = buildSagePayProperties(context, delegator); String vendorTxCode = (String) context.get("vendorTxCode"); String vpsTxId = (String) context.get("vpsTxId"); String securityKey = (String) context.get("securityKey"); String txAuthNo = (String) context.get("txAuthNo"); Locale locale = (Locale) context.get("locale"); HttpHost host = SagePayUtil.getHost(props); //start - release parameters Map<String, String> parameters = new HashMap<>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); String txType = props.get("releaseTransType"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", txType); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("VPSTxId", vpsTxId); parameters.put("SecurityKey", securityKey); parameters.put("TxAuthNo", txAuthNo); //end - release parameters try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("releaseUrl"), parameters); HttpResponse response = httpClient.execute(host, httpPost); Map<String, String> responseData = SagePayUtil.getResponseData(response); String status = responseData.get("Status"); String statusDetail = responseData.get("StatusDetail"); resultMap.put("status", status); resultMap.put("statusDetail", statusDetail); //start - payment released if ("OK".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentReleased", locale); } //end - payment released //start - release request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentReleaseRequestMalformed", locale); } //end - release request not formed properly or parameters missing //start - invalid information passed in parameters if ("INVALID".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentInvalidInformationPassed", locale); } //end - invalid information passed in parameters //start - problem at Sagepay if ("ERROR".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentError", locale); } //end - problem at Sagepay resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage); } catch (UnsupportedEncodingException uee) { //exception in encoding parameters in httpPost Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale)); } catch (ClientProtocolException cpe) { //from httpClient execute Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale)); } catch (IOException ioe) { //from httpClient execute or getResponsedata Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } return resultMap; } public static Map<String, Object> paymentVoid(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentVoid", MODULE); Debug.logInfo("SagePay paymentVoid context : " + context, MODULE); Delegator delegator = ctx.getDelegator(); Map<String, Object> resultMap = new HashMap<>(); Map<String, String> props = buildSagePayProperties(context, delegator); String vendorTxCode = (String) context.get("vendorTxCode"); String vpsTxId = (String) context.get("vpsTxId"); String securityKey = (String) context.get("securityKey"); String txAuthNo = (String) context.get("txAuthNo"); Locale locale = (Locale) context.get("locale"); HttpHost host = SagePayUtil.getHost(props); //start - void parameters Map<String, String> parameters = new HashMap<>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", "VOID"); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("VPSTxId", vpsTxId); parameters.put("SecurityKey", securityKey); parameters.put("TxAuthNo", txAuthNo); //end - void parameters try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("voidUrl"), parameters); HttpResponse response = httpClient.execute(host, httpPost); Map<String, String> responseData = SagePayUtil.getResponseData(response); String status = responseData.get("Status"); String statusDetail = responseData.get("StatusDetail"); resultMap.put("status", status); resultMap.put("statusDetail", statusDetail); //start - payment void if ("OK".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentVoided", locale); } //end - payment void //start - void request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentVoidRequestMalformed", locale); } //end - void request not formed properly or parameters missing //start - invalid information passed in parameters if ("INVALID".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentInvalidInformationPassed", locale); } //end - invalid information passed in parameters //start - problem at Sagepay if ("ERROR".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentError", locale); } //end - problem at Sagepay resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage); } catch (UnsupportedEncodingException uee) { //exception in encoding parameters in httpPost Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale)); } catch (ClientProtocolException cpe) { //from httpClient execute Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale)); } catch (IOException ioe) { //from httpClient execute or getResponsedata Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } return resultMap; } public static Map<String, Object> paymentRefund(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentRefund", MODULE); Debug.logInfo("SagePay paymentRefund context : " + context, MODULE); Delegator delegator = ctx.getDelegator(); Map<String, Object> resultMap = new HashMap<>(); Map<String, String> props = buildSagePayProperties(context, delegator); String vendorTxCode = (String) context.get("vendorTxCode"); String amount = (String) context.get("amount"); String currency = (String) context.get("currency"); String description = (String) context.get("description"); String relatedVPSTxId = (String) context.get("relatedVPSTxId"); String relatedVendorTxCode = (String) context.get("relatedVendorTxCode"); String relatedSecurityKey = (String) context.get("relatedSecurityKey"); String relatedTxAuthNo = (String) context.get("relatedTxAuthNo"); Locale locale = (Locale) context.get("locale"); HttpHost host = SagePayUtil.getHost(props); //start - refund parameters Map<String, String> parameters = new HashMap<>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", "REFUND"); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("Amount", amount); parameters.put("Currency", currency); parameters.put("Description", description); parameters.put("RelatedVPSTxId", relatedVPSTxId); parameters.put("RelatedVendorTxCode", relatedVendorTxCode); parameters.put("RelatedSecurityKey", relatedSecurityKey); parameters.put("RelatedTxAuthNo", relatedTxAuthNo); //end - refund parameters try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("refundUrl"), parameters); HttpResponse response = httpClient.execute(host, httpPost); Map<String, String> responseData = SagePayUtil.getResponseData(response); Debug.logInfo("response data -> " + responseData, MODULE); String status = responseData.get("Status"); String statusDetail = responseData.get("StatusDetail"); resultMap.put("status", status); resultMap.put("statusDetail", statusDetail); //start - payment refunded if ("OK".equals(status)) { resultMap.put("vpsTxId", responseData.get("VPSTxId")); resultMap.put("txAuthNo", responseData.get("TxAuthNo")); successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentRefunded", locale); } //end - payment refunded //start - refund not authorized by the acquiring bank if ("NOTAUTHED".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentRefundNotAuthorized", locale); } //end - refund not authorized by the acquiring bank //start - refund request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentRefundRequestMalformed", locale); } //end - refund request not formed properly or parameters missing //start - invalid information passed in parameters if ("INVALID".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentInvalidInformationPassed", locale); } //end - invalid information passed in parameters //start - problem at Sagepay if ("ERROR".equals(status)) { successMessage = UtilProperties.getMessage(RESOURCE, "AccountingSagePayPaymentError", locale); } //end - problem at Sagepay resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage); } catch (UnsupportedEncodingException uee) { //exception in encoding parameters in httpPost Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale)); } catch (ClientProtocolException cpe) { //from httpClient execute Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale)); } catch (IOException ioe) { //from httpClient execute or getResponsedata Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", MODULE); resultMap = ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } return resultMap; } }
googleapis/google-cloud-java
37,631
java-discoveryengine/proto-google-cloud-discoveryengine-v1/src/main/java/com/google/cloud/discoveryengine/v1/BatchUpdateUserLicensesMetadata.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/discoveryengine/v1/user_license_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1; /** * * * <pre> * Metadata related to the progress of the * [UserLicenseService.BatchUpdateUserLicenses][google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses] * operation. This will be returned by the google.longrunning.Operation.metadata * field. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata} */ public final class BatchUpdateUserLicensesMetadata extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata) BatchUpdateUserLicensesMetadataOrBuilder { private static final long serialVersionUID = 0L; // Use BatchUpdateUserLicensesMetadata.newBuilder() to construct. private BatchUpdateUserLicensesMetadata( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BatchUpdateUserLicensesMetadata() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BatchUpdateUserLicensesMetadata(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.UserLicenseServiceProto .internal_static_google_cloud_discoveryengine_v1_BatchUpdateUserLicensesMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.UserLicenseServiceProto .internal_static_google_cloud_discoveryengine_v1_BatchUpdateUserLicensesMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata.class, com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata.Builder.class); } private int bitField0_; public static final int CREATE_TIME_FIELD_NUMBER = 1; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } public static final int UPDATE_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp updateTime_; /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return Whether the updateTime field is set. */ @java.lang.Override public boolean hasUpdateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return The updateTime. */ @java.lang.Override public com.google.protobuf.Timestamp getUpdateTime() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } public static final int SUCCESS_COUNT_FIELD_NUMBER = 3; private long successCount_ = 0L; /** * * * <pre> * Count of user licenses successfully updated. * </pre> * * <code>int64 success_count = 3;</code> * * @return The successCount. */ @java.lang.Override public long getSuccessCount() { return successCount_; } public static final int FAILURE_COUNT_FIELD_NUMBER = 4; private long failureCount_ = 0L; /** * * * <pre> * Count of user licenses that failed to be updated. * </pre> * * <code>int64 failure_count = 4;</code> * * @return The failureCount. */ @java.lang.Override public long getFailureCount() { return failureCount_; } 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, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(2, getUpdateTime()); } if (successCount_ != 0L) { output.writeInt64(3, successCount_); } if (failureCount_ != 0L) { output.writeInt64(4, failureCount_); } 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, getCreateTime()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateTime()); } if (successCount_ != 0L) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(3, successCount_); } if (failureCount_ != 0L) { size += com.google.protobuf.CodedOutputStream.computeInt64Size(4, failureCount_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata other = (com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata) obj; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasUpdateTime() != other.hasUpdateTime()) return false; if (hasUpdateTime()) { if (!getUpdateTime().equals(other.getUpdateTime())) return false; } if (getSuccessCount() != other.getSuccessCount()) return false; if (getFailureCount() != other.getFailureCount()) 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 (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasUpdateTime()) { hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getUpdateTime().hashCode(); } hash = (37 * hash) + SUCCESS_COUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getSuccessCount()); hash = (37 * hash) + FAILURE_COUNT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getFailureCount()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Metadata related to the progress of the * [UserLicenseService.BatchUpdateUserLicenses][google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses] * operation. This will be returned by the google.longrunning.Operation.metadata * field. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata) com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadataOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.UserLicenseServiceProto .internal_static_google_cloud_discoveryengine_v1_BatchUpdateUserLicensesMetadata_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.UserLicenseServiceProto .internal_static_google_cloud_discoveryengine_v1_BatchUpdateUserLicensesMetadata_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata.class, com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata.Builder.class); } // Construct using // com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getCreateTimeFieldBuilder(); getUpdateTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } successCount_ = 0L; failureCount_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.discoveryengine.v1.UserLicenseServiceProto .internal_static_google_cloud_discoveryengine_v1_BatchUpdateUserLicensesMetadata_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata .getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata build() { com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata buildPartial() { com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata result = new com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.updateTime_ = updateTimeBuilder_ == null ? updateTime_ : updateTimeBuilder_.build(); to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.successCount_ = successCount_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.failureCount_ = failureCount_; } 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.discoveryengine.v1.BatchUpdateUserLicensesMetadata) { return mergeFrom( (com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata other) { if (other == com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata .getDefaultInstance()) return this; if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasUpdateTime()) { mergeUpdateTime(other.getUpdateTime()); } if (other.getSuccessCount() != 0L) { setSuccessCount(other.getSuccessCount()); } if (other.getFailureCount() != 0L) { setFailureCount(other.getFailureCount()); } 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(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getUpdateTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 24: { successCount_ = input.readInt64(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { failureCount_ = input.readInt64(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; } else { createTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && createTime_ != null && createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getCreateTimeBuilder().mergeFrom(value); } else { createTime_ = value; } } else { createTimeBuilder_.mergeFrom(value); } if (createTime_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public Builder clearCreateTime() { bitField0_ = (bitField0_ & ~0x00000001); createTime_ = null; if (createTimeBuilder_ != null) { createTimeBuilder_.dispose(); createTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { bitField0_ |= 0x00000001; onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Operation create time. * </pre> * * <code>.google.protobuf.Timestamp create_time = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.protobuf.Timestamp updateTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> updateTimeBuilder_; /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return Whether the updateTime field is set. */ public boolean hasUpdateTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> * * @return The updateTime. */ public com.google.protobuf.Timestamp getUpdateTime() { if (updateTimeBuilder_ == null) { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } else { return updateTimeBuilder_.getMessage(); } } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateTime_ = value; } else { updateTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (updateTimeBuilder_ == null) { updateTime_ = builderForValue.build(); } else { updateTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) { if (updateTimeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateTime_ != null && updateTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getUpdateTimeBuilder().mergeFrom(value); } else { updateTime_ = value; } } else { updateTimeBuilder_.mergeFrom(value); } if (updateTime_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public Builder clearUpdateTime() { bitField0_ = (bitField0_ & ~0x00000002); updateTime_ = null; if (updateTimeBuilder_ != null) { updateTimeBuilder_.dispose(); updateTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() { if (updateTimeBuilder_ != null) { return updateTimeBuilder_.getMessageOrBuilder(); } else { return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_; } } /** * * * <pre> * Operation last update time. If the operation is done, this is also the * finish time. * </pre> * * <code>.google.protobuf.Timestamp update_time = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getUpdateTimeFieldBuilder() { if (updateTimeBuilder_ == null) { updateTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getUpdateTime(), getParentForChildren(), isClean()); updateTime_ = null; } return updateTimeBuilder_; } private long successCount_; /** * * * <pre> * Count of user licenses successfully updated. * </pre> * * <code>int64 success_count = 3;</code> * * @return The successCount. */ @java.lang.Override public long getSuccessCount() { return successCount_; } /** * * * <pre> * Count of user licenses successfully updated. * </pre> * * <code>int64 success_count = 3;</code> * * @param value The successCount to set. * @return This builder for chaining. */ public Builder setSuccessCount(long value) { successCount_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Count of user licenses successfully updated. * </pre> * * <code>int64 success_count = 3;</code> * * @return This builder for chaining. */ public Builder clearSuccessCount() { bitField0_ = (bitField0_ & ~0x00000004); successCount_ = 0L; onChanged(); return this; } private long failureCount_; /** * * * <pre> * Count of user licenses that failed to be updated. * </pre> * * <code>int64 failure_count = 4;</code> * * @return The failureCount. */ @java.lang.Override public long getFailureCount() { return failureCount_; } /** * * * <pre> * Count of user licenses that failed to be updated. * </pre> * * <code>int64 failure_count = 4;</code> * * @param value The failureCount to set. * @return This builder for chaining. */ public Builder setFailureCount(long value) { failureCount_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Count of user licenses that failed to be updated. * </pre> * * <code>int64 failure_count = 4;</code> * * @return This builder for chaining. */ public Builder clearFailureCount() { bitField0_ = (bitField0_ & ~0x00000008); failureCount_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata) private static final com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata(); } public static com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BatchUpdateUserLicensesMetadata> PARSER = new com.google.protobuf.AbstractParser<BatchUpdateUserLicensesMetadata>() { @java.lang.Override public BatchUpdateUserLicensesMetadata 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<BatchUpdateUserLicensesMetadata> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BatchUpdateUserLicensesMetadata> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1.BatchUpdateUserLicensesMetadata getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,609
java-meet/proto-google-cloud-meet-v2/src/main/java/com/google/apps/meet/v2/ParticipantSession.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/apps/meet/v2/resource.proto // Protobuf Java Version: 3.25.8 package com.google.apps.meet.v2; /** * * * <pre> * Refers to each unique join or leave session when a user joins a conference * from a device. Note that any time a user joins the conference a new unique ID * is assigned. That means if a user joins a space multiple times from the same * device, they're assigned different IDs, and are also be treated as different * participant sessions. * </pre> * * Protobuf type {@code google.apps.meet.v2.ParticipantSession} */ public final class ParticipantSession extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.apps.meet.v2.ParticipantSession) ParticipantSessionOrBuilder { private static final long serialVersionUID = 0L; // Use ParticipantSession.newBuilder() to construct. private ParticipantSession(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ParticipantSession() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ParticipantSession(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_ParticipantSession_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_ParticipantSession_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2.ParticipantSession.class, com.google.apps.meet.v2.ParticipantSession.Builder.class); } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int START_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp startTime_; /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the startTime field is set. */ @java.lang.Override public boolean hasStartTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The startTime. */ @java.lang.Override public com.google.protobuf.Timestamp getStartTime() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } public static final int END_TIME_FIELD_NUMBER = 3; private com.google.protobuf.Timestamp endTime_; /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the endTime field is set. */ @java.lang.Override public boolean hasEndTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The endTime. */ @java.lang.Override public com.google.protobuf.Timestamp getEndTime() { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder() { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getStartTime()); } if (((bitField0_ & 0x00000002) != 0)) { output.writeMessage(3, getEndTime()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getStartTime()); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEndTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.apps.meet.v2.ParticipantSession)) { return super.equals(obj); } com.google.apps.meet.v2.ParticipantSession other = (com.google.apps.meet.v2.ParticipantSession) obj; if (!getName().equals(other.getName())) return false; if (hasStartTime() != other.hasStartTime()) return false; if (hasStartTime()) { if (!getStartTime().equals(other.getStartTime())) return false; } if (hasEndTime() != other.hasEndTime()) return false; if (hasEndTime()) { if (!getEndTime().equals(other.getEndTime())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); if (hasStartTime()) { hash = (37 * hash) + START_TIME_FIELD_NUMBER; hash = (53 * hash) + getStartTime().hashCode(); } if (hasEndTime()) { hash = (37 * hash) + END_TIME_FIELD_NUMBER; hash = (53 * hash) + getEndTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.apps.meet.v2.ParticipantSession parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.ParticipantSession parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.apps.meet.v2.ParticipantSession parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2.ParticipantSession parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.apps.meet.v2.ParticipantSession parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.apps.meet.v2.ParticipantSession parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.apps.meet.v2.ParticipantSession 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> * Refers to each unique join or leave session when a user joins a conference * from a device. Note that any time a user joins the conference a new unique ID * is assigned. That means if a user joins a space multiple times from the same * device, they're assigned different IDs, and are also be treated as different * participant sessions. * </pre> * * Protobuf type {@code google.apps.meet.v2.ParticipantSession} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.apps.meet.v2.ParticipantSession) com.google.apps.meet.v2.ParticipantSessionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_ParticipantSession_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_ParticipantSession_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.apps.meet.v2.ParticipantSession.class, com.google.apps.meet.v2.ParticipantSession.Builder.class); } // Construct using com.google.apps.meet.v2.ParticipantSession.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getStartTimeFieldBuilder(); getEndTimeFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; startTime_ = null; if (startTimeBuilder_ != null) { startTimeBuilder_.dispose(); startTimeBuilder_ = null; } endTime_ = null; if (endTimeBuilder_ != null) { endTimeBuilder_.dispose(); endTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.apps.meet.v2.ResourceProto .internal_static_google_apps_meet_v2_ParticipantSession_descriptor; } @java.lang.Override public com.google.apps.meet.v2.ParticipantSession getDefaultInstanceForType() { return com.google.apps.meet.v2.ParticipantSession.getDefaultInstance(); } @java.lang.Override public com.google.apps.meet.v2.ParticipantSession build() { com.google.apps.meet.v2.ParticipantSession result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.apps.meet.v2.ParticipantSession buildPartial() { com.google.apps.meet.v2.ParticipantSession result = new com.google.apps.meet.v2.ParticipantSession(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.apps.meet.v2.ParticipantSession result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.startTime_ = startTimeBuilder_ == null ? startTime_ : startTimeBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.endTime_ = endTimeBuilder_ == null ? endTime_ : endTimeBuilder_.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.apps.meet.v2.ParticipantSession) { return mergeFrom((com.google.apps.meet.v2.ParticipantSession) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.apps.meet.v2.ParticipantSession other) { if (other == com.google.apps.meet.v2.ParticipantSession.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasStartTime()) { mergeStartTime(other.getStartTime()); } if (other.hasEndTime()) { mergeEndTime(other.getEndTime()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { input.readMessage(getStartTimeFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getEndTimeFieldBuilder().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 name_ = ""; /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Identifier. Session id. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = IDENTIFIER];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.Timestamp startTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> startTimeBuilder_; /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the startTime field is set. */ public boolean hasStartTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The startTime. */ public com.google.protobuf.Timestamp getStartTime() { if (startTimeBuilder_ == null) { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } else { return startTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } startTime_ = value; } else { startTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (startTimeBuilder_ == null) { startTime_ = builderForValue.build(); } else { startTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && startTime_ != null && startTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getStartTimeBuilder().mergeFrom(value); } else { startTime_ = value; } } else { startTimeBuilder_.mergeFrom(value); } if (startTime_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearStartTime() { bitField0_ = (bitField0_ & ~0x00000002); startTime_ = null; if (startTimeBuilder_ != null) { startTimeBuilder_.dispose(); startTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getStartTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { if (startTimeBuilder_ != null) { return startTimeBuilder_.getMessageOrBuilder(); } else { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } } /** * * * <pre> * Output only. Timestamp when the user session starts. * </pre> * * <code>.google.protobuf.Timestamp start_time = 2 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getStartTimeFieldBuilder() { if (startTimeBuilder_ == null) { startTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getStartTime(), getParentForChildren(), isClean()); startTime_ = null; } return startTimeBuilder_; } private com.google.protobuf.Timestamp endTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> endTimeBuilder_; /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the endTime field is set. */ public boolean hasEndTime() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The endTime. */ public com.google.protobuf.Timestamp getEndTime() { if (endTimeBuilder_ == null) { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } else { return endTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setEndTime(com.google.protobuf.Timestamp value) { if (endTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } endTime_ = value; } else { endTimeBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setEndTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (endTimeBuilder_ == null) { endTime_ = builderForValue.build(); } else { endTimeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeEndTime(com.google.protobuf.Timestamp value) { if (endTimeBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && endTime_ != null && endTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) { getEndTimeBuilder().mergeFrom(value); } else { endTime_ = value; } } else { endTimeBuilder_.mergeFrom(value); } if (endTime_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearEndTime() { bitField0_ = (bitField0_ & ~0x00000004); endTime_ = null; if (endTimeBuilder_ != null) { endTimeBuilder_.dispose(); endTimeBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getEndTimeBuilder() { bitField0_ |= 0x00000004; onChanged(); return getEndTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder() { if (endTimeBuilder_ != null) { return endTimeBuilder_.getMessageOrBuilder(); } else { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } } /** * * * <pre> * Output only. Timestamp when the user session ends. Unset if the user * session hasn’t ended. * </pre> * * <code>.google.protobuf.Timestamp end_time = 3 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getEndTimeFieldBuilder() { if (endTimeBuilder_ == null) { endTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getEndTime(), getParentForChildren(), isClean()); endTime_ = null; } return endTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.apps.meet.v2.ParticipantSession) } // @@protoc_insertion_point(class_scope:google.apps.meet.v2.ParticipantSession) private static final com.google.apps.meet.v2.ParticipantSession DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.apps.meet.v2.ParticipantSession(); } public static com.google.apps.meet.v2.ParticipantSession getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ParticipantSession> PARSER = new com.google.protobuf.AbstractParser<ParticipantSession>() { @java.lang.Override public ParticipantSession 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<ParticipantSession> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ParticipantSession> getParserForType() { return PARSER; } @java.lang.Override public com.google.apps.meet.v2.ParticipantSession getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,693
java-oracledatabase/proto-google-cloud-oracledatabase-v1/src/main/java/com/google/cloud/oracledatabase/v1/ListDbSystemShapesResponse.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/oracledatabase/v1/oracledatabase.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.oracledatabase.v1; /** * * * <pre> * The response for `DbSystemShape.List`. * </pre> * * Protobuf type {@code google.cloud.oracledatabase.v1.ListDbSystemShapesResponse} */ public final class ListDbSystemShapesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.oracledatabase.v1.ListDbSystemShapesResponse) ListDbSystemShapesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDbSystemShapesResponse.newBuilder() to construct. private ListDbSystemShapesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDbSystemShapesResponse() { dbSystemShapes_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDbSystemShapesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_ListDbSystemShapesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_ListDbSystemShapesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.class, com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.Builder.class); } public static final int DB_SYSTEM_SHAPES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.oracledatabase.v1.DbSystemShape> dbSystemShapes_; /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.oracledatabase.v1.DbSystemShape> getDbSystemShapesList() { return dbSystemShapes_; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder> getDbSystemShapesOrBuilderList() { return dbSystemShapes_; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ @java.lang.Override public int getDbSystemShapesCount() { return dbSystemShapes_.size(); } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ @java.lang.Override public com.google.cloud.oracledatabase.v1.DbSystemShape getDbSystemShapes(int index) { return dbSystemShapes_.get(index); } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ @java.lang.Override public com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder getDbSystemShapesOrBuilder( int index) { return dbSystemShapes_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should 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 identifying a page of results the server should 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 < dbSystemShapes_.size(); i++) { output.writeMessage(1, dbSystemShapes_.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 < dbSystemShapes_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dbSystemShapes_.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.oracledatabase.v1.ListDbSystemShapesResponse)) { return super.equals(obj); } com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse other = (com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse) obj; if (!getDbSystemShapesList().equals(other.getDbSystemShapesList())) 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 (getDbSystemShapesCount() > 0) { hash = (37 * hash) + DB_SYSTEM_SHAPES_FIELD_NUMBER; hash = (53 * hash) + getDbSystemShapesList().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.oracledatabase.v1.ListDbSystemShapesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse 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.oracledatabase.v1.ListDbSystemShapesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse 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.oracledatabase.v1.ListDbSystemShapesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse 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.oracledatabase.v1.ListDbSystemShapesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse 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.oracledatabase.v1.ListDbSystemShapesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse 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.oracledatabase.v1.ListDbSystemShapesResponse 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 for `DbSystemShape.List`. * </pre> * * Protobuf type {@code google.cloud.oracledatabase.v1.ListDbSystemShapesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.oracledatabase.v1.ListDbSystemShapesResponse) com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_ListDbSystemShapesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_ListDbSystemShapesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.class, com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.Builder.class); } // Construct using com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dbSystemShapesBuilder_ == null) { dbSystemShapes_ = java.util.Collections.emptyList(); } else { dbSystemShapes_ = null; dbSystemShapesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.oracledatabase.v1.V1mainProto .internal_static_google_cloud_oracledatabase_v1_ListDbSystemShapesResponse_descriptor; } @java.lang.Override public com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse getDefaultInstanceForType() { return com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse build() { com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse buildPartial() { com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse result = new com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse result) { if (dbSystemShapesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dbSystemShapes_ = java.util.Collections.unmodifiableList(dbSystemShapes_); bitField0_ = (bitField0_ & ~0x00000001); } result.dbSystemShapes_ = dbSystemShapes_; } else { result.dbSystemShapes_ = dbSystemShapesBuilder_.build(); } } private void buildPartial0( com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse 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.oracledatabase.v1.ListDbSystemShapesResponse) { return mergeFrom((com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse other) { if (other == com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse.getDefaultInstance()) return this; if (dbSystemShapesBuilder_ == null) { if (!other.dbSystemShapes_.isEmpty()) { if (dbSystemShapes_.isEmpty()) { dbSystemShapes_ = other.dbSystemShapes_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDbSystemShapesIsMutable(); dbSystemShapes_.addAll(other.dbSystemShapes_); } onChanged(); } } else { if (!other.dbSystemShapes_.isEmpty()) { if (dbSystemShapesBuilder_.isEmpty()) { dbSystemShapesBuilder_.dispose(); dbSystemShapesBuilder_ = null; dbSystemShapes_ = other.dbSystemShapes_; bitField0_ = (bitField0_ & ~0x00000001); dbSystemShapesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDbSystemShapesFieldBuilder() : null; } else { dbSystemShapesBuilder_.addAllMessages(other.dbSystemShapes_); } } } 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.oracledatabase.v1.DbSystemShape m = input.readMessage( com.google.cloud.oracledatabase.v1.DbSystemShape.parser(), extensionRegistry); if (dbSystemShapesBuilder_ == null) { ensureDbSystemShapesIsMutable(); dbSystemShapes_.add(m); } else { dbSystemShapesBuilder_.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.oracledatabase.v1.DbSystemShape> dbSystemShapes_ = java.util.Collections.emptyList(); private void ensureDbSystemShapesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dbSystemShapes_ = new java.util.ArrayList<com.google.cloud.oracledatabase.v1.DbSystemShape>( dbSystemShapes_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.oracledatabase.v1.DbSystemShape, com.google.cloud.oracledatabase.v1.DbSystemShape.Builder, com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder> dbSystemShapesBuilder_; /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public java.util.List<com.google.cloud.oracledatabase.v1.DbSystemShape> getDbSystemShapesList() { if (dbSystemShapesBuilder_ == null) { return java.util.Collections.unmodifiableList(dbSystemShapes_); } else { return dbSystemShapesBuilder_.getMessageList(); } } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public int getDbSystemShapesCount() { if (dbSystemShapesBuilder_ == null) { return dbSystemShapes_.size(); } else { return dbSystemShapesBuilder_.getCount(); } } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public com.google.cloud.oracledatabase.v1.DbSystemShape getDbSystemShapes(int index) { if (dbSystemShapesBuilder_ == null) { return dbSystemShapes_.get(index); } else { return dbSystemShapesBuilder_.getMessage(index); } } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder setDbSystemShapes( int index, com.google.cloud.oracledatabase.v1.DbSystemShape value) { if (dbSystemShapesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDbSystemShapesIsMutable(); dbSystemShapes_.set(index, value); onChanged(); } else { dbSystemShapesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder setDbSystemShapes( int index, com.google.cloud.oracledatabase.v1.DbSystemShape.Builder builderForValue) { if (dbSystemShapesBuilder_ == null) { ensureDbSystemShapesIsMutable(); dbSystemShapes_.set(index, builderForValue.build()); onChanged(); } else { dbSystemShapesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder addDbSystemShapes(com.google.cloud.oracledatabase.v1.DbSystemShape value) { if (dbSystemShapesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDbSystemShapesIsMutable(); dbSystemShapes_.add(value); onChanged(); } else { dbSystemShapesBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder addDbSystemShapes( int index, com.google.cloud.oracledatabase.v1.DbSystemShape value) { if (dbSystemShapesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDbSystemShapesIsMutable(); dbSystemShapes_.add(index, value); onChanged(); } else { dbSystemShapesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder addDbSystemShapes( com.google.cloud.oracledatabase.v1.DbSystemShape.Builder builderForValue) { if (dbSystemShapesBuilder_ == null) { ensureDbSystemShapesIsMutable(); dbSystemShapes_.add(builderForValue.build()); onChanged(); } else { dbSystemShapesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder addDbSystemShapes( int index, com.google.cloud.oracledatabase.v1.DbSystemShape.Builder builderForValue) { if (dbSystemShapesBuilder_ == null) { ensureDbSystemShapesIsMutable(); dbSystemShapes_.add(index, builderForValue.build()); onChanged(); } else { dbSystemShapesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder addAllDbSystemShapes( java.lang.Iterable<? extends com.google.cloud.oracledatabase.v1.DbSystemShape> values) { if (dbSystemShapesBuilder_ == null) { ensureDbSystemShapesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dbSystemShapes_); onChanged(); } else { dbSystemShapesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder clearDbSystemShapes() { if (dbSystemShapesBuilder_ == null) { dbSystemShapes_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dbSystemShapesBuilder_.clear(); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public Builder removeDbSystemShapes(int index) { if (dbSystemShapesBuilder_ == null) { ensureDbSystemShapesIsMutable(); dbSystemShapes_.remove(index); onChanged(); } else { dbSystemShapesBuilder_.remove(index); } return this; } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public com.google.cloud.oracledatabase.v1.DbSystemShape.Builder getDbSystemShapesBuilder( int index) { return getDbSystemShapesFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder getDbSystemShapesOrBuilder( int index) { if (dbSystemShapesBuilder_ == null) { return dbSystemShapes_.get(index); } else { return dbSystemShapesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public java.util.List<? extends com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder> getDbSystemShapesOrBuilderList() { if (dbSystemShapesBuilder_ != null) { return dbSystemShapesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dbSystemShapes_); } } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public com.google.cloud.oracledatabase.v1.DbSystemShape.Builder addDbSystemShapesBuilder() { return getDbSystemShapesFieldBuilder() .addBuilder(com.google.cloud.oracledatabase.v1.DbSystemShape.getDefaultInstance()); } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public com.google.cloud.oracledatabase.v1.DbSystemShape.Builder addDbSystemShapesBuilder( int index) { return getDbSystemShapesFieldBuilder() .addBuilder(index, com.google.cloud.oracledatabase.v1.DbSystemShape.getDefaultInstance()); } /** * * * <pre> * The list of Database System shapes. * </pre> * * <code>repeated .google.cloud.oracledatabase.v1.DbSystemShape db_system_shapes = 1;</code> */ public java.util.List<com.google.cloud.oracledatabase.v1.DbSystemShape.Builder> getDbSystemShapesBuilderList() { return getDbSystemShapesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.oracledatabase.v1.DbSystemShape, com.google.cloud.oracledatabase.v1.DbSystemShape.Builder, com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder> getDbSystemShapesFieldBuilder() { if (dbSystemShapesBuilder_ == null) { dbSystemShapesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.oracledatabase.v1.DbSystemShape, com.google.cloud.oracledatabase.v1.DbSystemShape.Builder, com.google.cloud.oracledatabase.v1.DbSystemShapeOrBuilder>( dbSystemShapes_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dbSystemShapes_ = null; } return dbSystemShapesBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should 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 identifying a page of results the server should 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 identifying a page of results the server should 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 identifying a page of results the server should 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 identifying a page of results the server should 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.oracledatabase.v1.ListDbSystemShapesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.oracledatabase.v1.ListDbSystemShapesResponse) private static final com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse(); } public static com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDbSystemShapesResponse> PARSER = new com.google.protobuf.AbstractParser<ListDbSystemShapesResponse>() { @java.lang.Override public ListDbSystemShapesResponse 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<ListDbSystemShapesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDbSystemShapesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.oracledatabase.v1.ListDbSystemShapesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/kafka
38,132
clients/src/main/java/org/apache/kafka/common/security/authenticator/SaslServerAuthenticator.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.common.security.authenticator; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.config.SaslConfigs; import org.apache.kafka.common.config.internals.BrokerSecurityConfigs; import org.apache.kafka.common.errors.AuthenticationException; import org.apache.kafka.common.errors.IllegalSaslStateException; import org.apache.kafka.common.errors.InvalidRequestException; import org.apache.kafka.common.errors.SaslAuthenticationException; import org.apache.kafka.common.errors.UnsupportedSaslMechanismException; import org.apache.kafka.common.errors.UnsupportedVersionException; import org.apache.kafka.common.internals.SecurityManagerCompatibility; import org.apache.kafka.common.message.SaslAuthenticateResponseData; import org.apache.kafka.common.message.SaslHandshakeResponseData; import org.apache.kafka.common.network.Authenticator; import org.apache.kafka.common.network.ByteBufferSend; import org.apache.kafka.common.network.ChannelBuilders; import org.apache.kafka.common.network.ChannelMetadataRegistry; import org.apache.kafka.common.network.ClientInformation; import org.apache.kafka.common.network.InvalidReceiveException; import org.apache.kafka.common.network.ListenerName; import org.apache.kafka.common.network.NetworkReceive; import org.apache.kafka.common.network.ReauthenticationContext; import org.apache.kafka.common.network.Send; import org.apache.kafka.common.network.SslTransportLayer; import org.apache.kafka.common.network.TransportLayer; import org.apache.kafka.common.protocol.ApiKeys; import org.apache.kafka.common.protocol.Errors; import org.apache.kafka.common.requests.AbstractResponse; import org.apache.kafka.common.requests.ApiVersionsRequest; import org.apache.kafka.common.requests.ApiVersionsResponse; import org.apache.kafka.common.requests.RequestAndSize; import org.apache.kafka.common.requests.RequestContext; import org.apache.kafka.common.requests.RequestHeader; import org.apache.kafka.common.requests.SaslAuthenticateRequest; import org.apache.kafka.common.requests.SaslAuthenticateResponse; import org.apache.kafka.common.requests.SaslHandshakeRequest; import org.apache.kafka.common.requests.SaslHandshakeResponse; import org.apache.kafka.common.security.auth.AuthenticateCallbackHandler; import org.apache.kafka.common.security.auth.KafkaPrincipal; import org.apache.kafka.common.security.auth.KafkaPrincipalBuilder; import org.apache.kafka.common.security.auth.KafkaPrincipalSerde; import org.apache.kafka.common.security.auth.SaslAuthenticationContext; import org.apache.kafka.common.security.auth.SecurityProtocol; import org.apache.kafka.common.security.kerberos.KerberosError; import org.apache.kafka.common.security.kerberos.KerberosName; import org.apache.kafka.common.security.kerberos.KerberosShortNamer; import org.apache.kafka.common.security.scram.ScramLoginModule; import org.apache.kafka.common.security.scram.internals.ScramMechanism; import org.apache.kafka.common.utils.Time; import org.apache.kafka.common.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletionException; import java.util.function.Function; import javax.net.ssl.SSLSession; import javax.security.auth.Subject; import javax.security.sasl.Sasl; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; public class SaslServerAuthenticator implements Authenticator { private static final Logger LOG = LoggerFactory.getLogger(SaslServerAuthenticator.class); /** * The internal state transitions for initial authentication of a channel on the * server side are declared in order, starting with {@link #INITIAL_REQUEST} and * ending in either {@link #COMPLETE} or {@link #FAILED}. * <p> * Re-authentication of a channel on the server side starts with the state * {@link #REAUTH_PROCESS_HANDSHAKE}. It may then flow to * {@link #REAUTH_BAD_MECHANISM} before a transition to {@link #FAILED} if * re-authentication is attempted with a mechanism different than the original * one; otherwise it joins the authentication flow at the {@link #AUTHENTICATE} * state and likewise ends at either {@link #COMPLETE} or {@link #FAILED}. */ private enum SaslState { INITIAL_REQUEST, // May be SaslHandshake or ApiVersions for authentication HANDSHAKE_OR_VERSIONS_REQUEST, // May be SaslHandshake or ApiVersions HANDSHAKE_REQUEST, // After an ApiVersions request, next request must be SaslHandshake AUTHENTICATE, // Authentication tokens (SaslHandshake v1 and above indicate SaslAuthenticate headers) COMPLETE, // Authentication completed successfully FAILED, // Authentication failed REAUTH_PROCESS_HANDSHAKE, // Initial state for re-authentication, processes SASL handshake request REAUTH_BAD_MECHANISM, // When re-authentication requested with wrong mechanism, generate exception } private final SecurityProtocol securityProtocol; private final ListenerName listenerName; private final String connectionId; private final Map<String, Subject> subjects; private final TransportLayer transportLayer; private final List<String> enabledMechanisms; private final Map<String, ?> configs; private final KafkaPrincipalBuilder principalBuilder; private final Map<String, AuthenticateCallbackHandler> callbackHandlers; private final Map<String, Long> connectionsMaxReauthMsByMechanism; private final Time time; private final ReauthInfo reauthInfo; private final ChannelMetadataRegistry metadataRegistry; private final Function<Short, ApiVersionsResponse> apiVersionSupplier; // Current SASL state private SaslState saslState = SaslState.INITIAL_REQUEST; // Next SASL state to be set when outgoing writes associated with the current SASL state complete private SaslState pendingSaslState = null; // Exception that will be thrown by `authenticate()` when SaslState is set to FAILED after outbound writes complete private AuthenticationException pendingException = null; private SaslServer saslServer; private String saslMechanism; // buffers used in `authenticate` private Integer saslAuthRequestMaxReceiveSize; private NetworkReceive netInBuffer; private Send netOutBuffer; private Send authenticationFailureSend = null; // flag indicating if sasl tokens are sent as Kafka SaslAuthenticate request/responses private boolean enableKafkaSaslAuthenticateHeaders; public SaslServerAuthenticator(Map<String, ?> configs, Map<String, AuthenticateCallbackHandler> callbackHandlers, String connectionId, Map<String, Subject> subjects, KerberosShortNamer kerberosNameParser, ListenerName listenerName, SecurityProtocol securityProtocol, TransportLayer transportLayer, Map<String, Long> connectionsMaxReauthMsByMechanism, ChannelMetadataRegistry metadataRegistry, Time time, Function<Short, ApiVersionsResponse> apiVersionSupplier) { this.callbackHandlers = callbackHandlers; this.connectionId = connectionId; this.subjects = subjects; this.listenerName = listenerName; this.securityProtocol = securityProtocol; this.enableKafkaSaslAuthenticateHeaders = false; this.transportLayer = transportLayer; this.connectionsMaxReauthMsByMechanism = connectionsMaxReauthMsByMechanism; this.time = time; this.reauthInfo = new ReauthInfo(); this.metadataRegistry = metadataRegistry; this.apiVersionSupplier = apiVersionSupplier; this.configs = configs; @SuppressWarnings("unchecked") List<String> enabledMechanisms = (List<String>) this.configs.get(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG); if (enabledMechanisms == null || enabledMechanisms.isEmpty()) throw new IllegalArgumentException("No SASL mechanisms are enabled"); this.enabledMechanisms = new ArrayList<>(new HashSet<>(enabledMechanisms)); for (String mechanism : this.enabledMechanisms) { if (!callbackHandlers.containsKey(mechanism)) throw new IllegalArgumentException("Callback handler not specified for SASL mechanism " + mechanism); if (!subjects.containsKey(mechanism)) throw new IllegalArgumentException("Subject cannot be null for SASL mechanism " + mechanism); LOG.trace("{} for mechanism={}: {}", BrokerSecurityConfigs.CONNECTIONS_MAX_REAUTH_MS_CONFIG, mechanism, connectionsMaxReauthMsByMechanism.get(mechanism)); } // Note that the old principal builder does not support SASL, so we do not need to pass the // authenticator or the transport layer this.principalBuilder = ChannelBuilders.createPrincipalBuilder(configs, kerberosNameParser, null); saslAuthRequestMaxReceiveSize = (Integer) configs.get(BrokerSecurityConfigs.SASL_SERVER_MAX_RECEIVE_SIZE_CONFIG); if (saslAuthRequestMaxReceiveSize == null) saslAuthRequestMaxReceiveSize = BrokerSecurityConfigs.DEFAULT_SASL_SERVER_MAX_RECEIVE_SIZE; } private void createSaslServer(String mechanism) throws IOException { this.saslMechanism = mechanism; Subject subject = subjects.get(mechanism); final AuthenticateCallbackHandler callbackHandler = callbackHandlers.get(mechanism); if (mechanism.equals(SaslConfigs.GSSAPI_MECHANISM)) { saslServer = createSaslKerberosServer(callbackHandler, configs, subject); } else { try { saslServer = SecurityManagerCompatibility.get().callAs(subject, () -> Sasl.createSaslServer(saslMechanism, "kafka", serverAddress().getHostName(), configs, callbackHandler)); if (saslServer == null) { throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication with server mechanism " + saslMechanism); } } catch (CompletionException e) { throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication with server mechanism " + saslMechanism, e.getCause()); } } } private SaslServer createSaslKerberosServer(final AuthenticateCallbackHandler saslServerCallbackHandler, final Map<String, ?> configs, Subject subject) throws IOException { // server is using a JAAS-authenticated subject: determine service principal name and hostname from kafka server's subject. final String servicePrincipal = SaslClientAuthenticator.firstPrincipal(subject); KerberosName kerberosName; try { kerberosName = KerberosName.parse(servicePrincipal); } catch (IllegalArgumentException e) { throw new KafkaException("Principal has name with unexpected format " + servicePrincipal); } final String servicePrincipalName = kerberosName.serviceName(); final String serviceHostname = kerberosName.hostName(); LOG.debug("Creating SaslServer for {} with mechanism {}", kerberosName, saslMechanism); try { return SecurityManagerCompatibility.get().callAs(subject, () -> Sasl.createSaslServer(saslMechanism, servicePrincipalName, serviceHostname, configs, saslServerCallbackHandler)); } catch (CompletionException e) { throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication", e.getCause()); } } /** * Evaluates client responses via `SaslServer.evaluateResponse` and returns the issued challenge to the client until * authentication succeeds or fails. * * The messages are sent and received as size delimited bytes that consists of a 4 byte network-ordered size N * followed by N bytes representing the opaque payload. */ @SuppressWarnings("fallthrough") @Override public void authenticate() throws IOException { if (saslState != SaslState.REAUTH_PROCESS_HANDSHAKE) { if (netOutBuffer != null && !flushNetOutBufferAndUpdateInterestOps()) return; if (saslServer != null && saslServer.isComplete()) { setSaslState(SaslState.COMPLETE); return; } // allocate on heap (as opposed to any socket server memory pool) if (netInBuffer == null) netInBuffer = new NetworkReceive(saslAuthRequestMaxReceiveSize, connectionId); try { netInBuffer.readFrom(transportLayer); } catch (InvalidReceiveException e) { throw new SaslAuthenticationException("Failing SASL authentication due to invalid receive size", e); } if (!netInBuffer.complete()) return; netInBuffer.payload().rewind(); } byte[] clientToken = new byte[netInBuffer.payload().remaining()]; netInBuffer.payload().get(clientToken, 0, clientToken.length); netInBuffer = null; // reset the networkReceive as we read all the data. try { switch (saslState) { case REAUTH_PROCESS_HANDSHAKE: case HANDSHAKE_OR_VERSIONS_REQUEST: case HANDSHAKE_REQUEST: case INITIAL_REQUEST: handleKafkaRequest(clientToken); break; case REAUTH_BAD_MECHANISM: throw new SaslAuthenticationException(reauthInfo.badMechanismErrorMessage); case AUTHENTICATE: handleSaslToken(clientToken); // When the authentication exchange is complete and no more tokens are expected from the client, // update SASL state. Current SASL state will be updated when outgoing writes to the client complete. if (saslServer.isComplete()) setSaslState(SaslState.COMPLETE); break; default: break; } } catch (AuthenticationException e) { // Exception will be propagated after response is sent to client setSaslState(SaslState.FAILED, e); } catch (Exception e) { // In the case of IOExceptions and other unexpected exceptions, fail immediately saslState = SaslState.FAILED; LOG.debug("Failed during {}: {}", reauthInfo.authenticationOrReauthenticationText(), e.getMessage()); throw e; } } @Override public KafkaPrincipal principal() { Optional<SSLSession> sslSession = transportLayer instanceof SslTransportLayer ? Optional.of(((SslTransportLayer) transportLayer).sslSession()) : Optional.empty(); SaslAuthenticationContext context = new SaslAuthenticationContext(saslServer, securityProtocol, clientAddress(), listenerName.value(), sslSession); KafkaPrincipal principal = principalBuilder.build(context); if (ScramMechanism.isScram(saslMechanism) && Boolean.parseBoolean((String) saslServer.getNegotiatedProperty(ScramLoginModule.TOKEN_AUTH_CONFIG))) { principal.tokenAuthenticated(true); } return principal; } @Override public Optional<KafkaPrincipalSerde> principalSerde() { return Optional.of(principalBuilder); } @Override public boolean complete() { return saslState == SaslState.COMPLETE; } @Override public void handleAuthenticationFailure() throws IOException { sendAuthenticationFailureResponse(); } @Override public void close() throws IOException { if (principalBuilder instanceof Closeable) Utils.closeQuietly((Closeable) principalBuilder, "principal builder"); if (saslServer != null) saslServer.dispose(); } @Override public void reauthenticate(ReauthenticationContext reauthenticationContext) throws IOException { NetworkReceive saslHandshakeReceive = reauthenticationContext.networkReceive(); if (saslHandshakeReceive == null) throw new IllegalArgumentException( "Invalid saslHandshakeReceive in server-side re-authentication context: null"); SaslServerAuthenticator previousSaslServerAuthenticator = (SaslServerAuthenticator) reauthenticationContext.previousAuthenticator(); reauthInfo.reauthenticating(previousSaslServerAuthenticator.saslMechanism, previousSaslServerAuthenticator.principal(), reauthenticationContext.reauthenticationBeginNanos()); previousSaslServerAuthenticator.close(); netInBuffer = saslHandshakeReceive; LOG.debug("Beginning re-authentication: {}", this); netInBuffer.payload().rewind(); setSaslState(SaslState.REAUTH_PROCESS_HANDSHAKE); authenticate(); } @Override public Long serverSessionExpirationTimeNanos() { return reauthInfo.sessionExpirationTimeNanos; } @Override public Long reauthenticationLatencyMs() { return reauthInfo.reauthenticationLatencyMs(); } @Override public boolean connectedClientSupportsReauthentication() { return reauthInfo.connectedClientSupportsReauthentication; } private void setSaslState(SaslState saslState) { setSaslState(saslState, null); } private void setSaslState(SaslState saslState, AuthenticationException exception) { if (netOutBuffer != null && !netOutBuffer.completed()) { pendingSaslState = saslState; pendingException = exception; } else { this.saslState = saslState; LOG.debug("Set SASL server state to {} during {}", saslState, reauthInfo.authenticationOrReauthenticationText()); this.pendingSaslState = null; this.pendingException = null; if (exception != null) throw exception; } } private boolean flushNetOutBufferAndUpdateInterestOps() throws IOException { boolean flushedCompletely = flushNetOutBuffer(); if (flushedCompletely) { transportLayer.removeInterestOps(SelectionKey.OP_WRITE); if (pendingSaslState != null) setSaslState(pendingSaslState, pendingException); } else transportLayer.addInterestOps(SelectionKey.OP_WRITE); return flushedCompletely; } private boolean flushNetOutBuffer() throws IOException { if (!netOutBuffer.completed()) netOutBuffer.writeTo(transportLayer); return netOutBuffer.completed(); } private InetAddress serverAddress() { return transportLayer.socketChannel().socket().getLocalAddress(); } private InetAddress clientAddress() { return transportLayer.socketChannel().socket().getInetAddress(); } private int clientPort() { return transportLayer.socketChannel().socket().getPort(); } private void handleSaslToken(byte[] clientToken) throws IOException { if (!enableKafkaSaslAuthenticateHeaders) { byte[] response = saslServer.evaluateResponse(clientToken); if (saslServer.isComplete()) { reauthInfo.calcCompletionTimesAndReturnSessionLifetimeMs(); if (reauthInfo.reauthenticating()) reauthInfo.ensurePrincipalUnchanged(principal()); } if (response != null) { netOutBuffer = ByteBufferSend.sizePrefixed(ByteBuffer.wrap(response)); flushNetOutBufferAndUpdateInterestOps(); } } else { ByteBuffer requestBuffer = ByteBuffer.wrap(clientToken); RequestHeader header = RequestHeader.parse(requestBuffer); ApiKeys apiKey = header.apiKey(); RequestContext requestContext = new RequestContext(header, connectionId, clientAddress(), Optional.of(clientPort()), KafkaPrincipal.ANONYMOUS, listenerName, securityProtocol, ClientInformation.EMPTY, false); RequestAndSize requestAndSize = requestContext.parseRequest(requestBuffer); if (apiKey != ApiKeys.SASL_AUTHENTICATE) { IllegalSaslStateException e = new IllegalSaslStateException("Unexpected Kafka request of type " + apiKey + " during SASL authentication."); buildResponseOnAuthenticateFailure(requestContext, requestAndSize.request.getErrorResponse(e)); throw e; } short version = header.apiVersion(); if (!header.isApiVersionSupported()) { // We cannot create an error response if the request version of SaslAuthenticate is not supported // This should not normally occur since clients typically check supported versions using ApiVersionsRequest throw new UnsupportedVersionException("Version " + version + " is not supported for apiKey " + apiKey); } /* * The client sends multiple SASL_AUTHENTICATE requests, and the client is known * to support the required version if any one of them indicates it supports that * version. */ if (!reauthInfo.connectedClientSupportsReauthentication) reauthInfo.connectedClientSupportsReauthentication = version > 0; SaslAuthenticateRequest saslAuthenticateRequest = (SaslAuthenticateRequest) requestAndSize.request; try { byte[] responseToken = saslServer.evaluateResponse( Utils.copyArray(saslAuthenticateRequest.data().authBytes())); if (reauthInfo.reauthenticating() && saslServer.isComplete()) reauthInfo.ensurePrincipalUnchanged(principal()); // For versions with SASL_AUTHENTICATE header, send a response to SASL_AUTHENTICATE request even if token is empty. byte[] responseBytes = responseToken == null ? new byte[0] : responseToken; long sessionLifetimeMs = !saslServer.isComplete() ? 0L : reauthInfo.calcCompletionTimesAndReturnSessionLifetimeMs(); sendKafkaResponse(requestContext, new SaslAuthenticateResponse( new SaslAuthenticateResponseData() .setErrorCode(Errors.NONE.code()) .setAuthBytes(responseBytes) .setSessionLifetimeMs(sessionLifetimeMs))); } catch (SaslAuthenticationException e) { buildResponseOnAuthenticateFailure(requestContext, new SaslAuthenticateResponse( new SaslAuthenticateResponseData() .setErrorCode(Errors.SASL_AUTHENTICATION_FAILED.code()) .setErrorMessage(e.getMessage()))); throw e; } catch (SaslException e) { KerberosError kerberosError = KerberosError.fromException(e); if (kerberosError != null && kerberosError.retriable()) { // Handle retriable Kerberos exceptions as I/O exceptions rather than authentication exceptions throw e; } else { // DO NOT include error message from the `SaslException` in the client response since it may // contain sensitive data like the existence of the user. String errorMessage = "Authentication failed during " + reauthInfo.authenticationOrReauthenticationText() + " due to invalid credentials with SASL mechanism " + saslMechanism; buildResponseOnAuthenticateFailure(requestContext, new SaslAuthenticateResponse( new SaslAuthenticateResponseData() .setErrorCode(Errors.SASL_AUTHENTICATION_FAILED.code()) .setErrorMessage(errorMessage))); throw new SaslAuthenticationException(errorMessage, e); } } } } /** * @throws InvalidRequestException if the request is not in Kafka format or if the API key is invalid. Clients * that support SASL without support for KIP-43 (e.g. Kafka Clients 0.9.x) are in the former bucket - the first * packet such clients send is a GSSAPI token starting with 0x60. */ private void handleKafkaRequest(byte[] requestBytes) throws IOException, AuthenticationException { try { ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes); RequestHeader header = RequestHeader.parse(requestBuffer); ApiKeys apiKey = header.apiKey(); // Raise an error prior to parsing if the api cannot be handled at this layer. This avoids // unnecessary exposure to some of the more complex schema types. if (apiKey != ApiKeys.API_VERSIONS && apiKey != ApiKeys.SASL_HANDSHAKE) throw new InvalidRequestException("Unexpected Kafka request of type " + apiKey + " during SASL handshake."); LOG.debug("Handling Kafka request {} during {}", apiKey, reauthInfo.authenticationOrReauthenticationText()); RequestContext requestContext = new RequestContext(header, connectionId, clientAddress(), Optional.of(clientPort()), KafkaPrincipal.ANONYMOUS, listenerName, securityProtocol, ClientInformation.EMPTY, false); RequestAndSize requestAndSize = requestContext.parseRequest(requestBuffer); // A valid Kafka request was received, we can now update the sasl state if (saslState == SaslState.INITIAL_REQUEST) setSaslState(SaslState.HANDSHAKE_OR_VERSIONS_REQUEST); if (apiKey == ApiKeys.API_VERSIONS) handleApiVersionsRequest(requestContext, (ApiVersionsRequest) requestAndSize.request); else { String clientMechanism = handleHandshakeRequest(requestContext, (SaslHandshakeRequest) requestAndSize.request); if (!reauthInfo.reauthenticating() || reauthInfo.saslMechanismUnchanged(clientMechanism)) { createSaslServer(clientMechanism); setSaslState(SaslState.AUTHENTICATE); } } } catch (InvalidRequestException e) { if (saslState == SaslState.INITIAL_REQUEST) { // InvalidRequestException is thrown if the request is not in Kafka format or if the API key is invalid. // If it's the initial request, this could be an ancient client (see method documentation for more details), // a client configured with the wrong security protocol or a non kafka-client altogether (eg http client). throw new InvalidRequestException("Invalid request, potential reasons: kafka client configured with the " + "wrong security protocol, it does not support KIP-43 or it is not a kafka client.", e); } throw e; } } private String handleHandshakeRequest(RequestContext context, SaslHandshakeRequest handshakeRequest) throws IOException, UnsupportedSaslMechanismException { String clientMechanism = handshakeRequest.data().mechanism(); short version = context.header.apiVersion(); if (version >= 1) this.enableKafkaSaslAuthenticateHeaders(true); if (enabledMechanisms.contains(clientMechanism)) { LOG.debug("Using SASL mechanism '{}' provided by client", clientMechanism); sendKafkaResponse(context, new SaslHandshakeResponse( new SaslHandshakeResponseData().setErrorCode(Errors.NONE.code()).setMechanisms(enabledMechanisms))); return clientMechanism; } else { LOG.debug("SASL mechanism '{}' requested by client is not supported", clientMechanism); buildResponseOnAuthenticateFailure(context, new SaslHandshakeResponse( new SaslHandshakeResponseData().setErrorCode(Errors.UNSUPPORTED_SASL_MECHANISM.code()).setMechanisms(enabledMechanisms))); throw new UnsupportedSaslMechanismException("Unsupported SASL mechanism " + clientMechanism); } } // Visible to override for testing protected void enableKafkaSaslAuthenticateHeaders(boolean flag) { this.enableKafkaSaslAuthenticateHeaders = flag; } private void handleApiVersionsRequest(RequestContext context, ApiVersionsRequest apiVersionsRequest) throws IOException { if (saslState != SaslState.HANDSHAKE_OR_VERSIONS_REQUEST) throw new IllegalStateException("Unexpected ApiVersions request received during SASL authentication state " + saslState); if (apiVersionsRequest.hasUnsupportedRequestVersion()) sendKafkaResponse(context, apiVersionsRequest.getErrorResponse(0, Errors.UNSUPPORTED_VERSION.exception())); else if (!apiVersionsRequest.isValid()) sendKafkaResponse(context, apiVersionsRequest.getErrorResponse(0, Errors.INVALID_REQUEST.exception())); else { metadataRegistry.registerClientInformation(new ClientInformation(apiVersionsRequest.data().clientSoftwareName(), apiVersionsRequest.data().clientSoftwareVersion())); sendKafkaResponse(context, apiVersionSupplier.apply(apiVersionsRequest.version())); setSaslState(SaslState.HANDSHAKE_REQUEST); } } /** * Build a {@link Send} response on {@link #authenticate()} failure. The actual response is sent out when * {@link #sendAuthenticationFailureResponse()} is called. */ private void buildResponseOnAuthenticateFailure(RequestContext context, AbstractResponse response) { authenticationFailureSend = context.buildResponseSend(response); } /** * Send any authentication failure response that may have been previously built. */ private void sendAuthenticationFailureResponse() throws IOException { if (authenticationFailureSend == null) return; sendKafkaResponse(authenticationFailureSend); authenticationFailureSend = null; } private void sendKafkaResponse(RequestContext context, AbstractResponse response) throws IOException { sendKafkaResponse(context.buildResponseSend(response)); } private void sendKafkaResponse(Send send) throws IOException { netOutBuffer = send; flushNetOutBufferAndUpdateInterestOps(); } /** * Information related to re-authentication */ private class ReauthInfo { public String previousSaslMechanism; public KafkaPrincipal previousKafkaPrincipal; public long reauthenticationBeginNanos; public Long sessionExpirationTimeNanos; public boolean connectedClientSupportsReauthentication; public long authenticationEndNanos; public String badMechanismErrorMessage; public void reauthenticating(String previousSaslMechanism, KafkaPrincipal previousKafkaPrincipal, long reauthenticationBeginNanos) { this.previousSaslMechanism = Objects.requireNonNull(previousSaslMechanism); this.previousKafkaPrincipal = Objects.requireNonNull(previousKafkaPrincipal); this.reauthenticationBeginNanos = reauthenticationBeginNanos; } public boolean reauthenticating() { return previousSaslMechanism != null; } public String authenticationOrReauthenticationText() { return reauthenticating() ? "re-authentication" : "authentication"; } public void ensurePrincipalUnchanged(KafkaPrincipal reauthenticatedKafkaPrincipal) throws SaslAuthenticationException { if (!previousKafkaPrincipal.equals(reauthenticatedKafkaPrincipal)) { throw new SaslAuthenticationException(String.format( "Cannot change principals during re-authentication from %s.%s: %s.%s", previousKafkaPrincipal.getPrincipalType(), previousKafkaPrincipal.getName(), reauthenticatedKafkaPrincipal.getPrincipalType(), reauthenticatedKafkaPrincipal.getName())); } } /* * We define the REAUTH_BAD_MECHANISM state because the failed re-authentication * metric does not get updated if we send back an error immediately upon the * start of re-authentication. */ public boolean saslMechanismUnchanged(String clientMechanism) { if (previousSaslMechanism.equals(clientMechanism)) return true; badMechanismErrorMessage = String.format( "SASL mechanism '%s' requested by client is not supported for re-authentication of mechanism '%s'", clientMechanism, previousSaslMechanism); LOG.debug(badMechanismErrorMessage); setSaslState(SaslState.REAUTH_BAD_MECHANISM); return false; } private long calcCompletionTimesAndReturnSessionLifetimeMs() { long retvalSessionLifetimeMs = 0L; long authenticationEndMs = time.milliseconds(); authenticationEndNanos = time.nanoseconds(); Long credentialExpirationMs = (Long) saslServer .getNegotiatedProperty(SaslInternalConfigs.CREDENTIAL_LIFETIME_MS_SASL_NEGOTIATED_PROPERTY_KEY); Long connectionsMaxReauthMs = connectionsMaxReauthMsByMechanism.get(saslMechanism); boolean maxReauthSet = connectionsMaxReauthMs != null && connectionsMaxReauthMs > 0; if (credentialExpirationMs != null || maxReauthSet) { if (credentialExpirationMs == null) retvalSessionLifetimeMs = zeroIfNegative(connectionsMaxReauthMs); else if (!maxReauthSet) retvalSessionLifetimeMs = zeroIfNegative(credentialExpirationMs - authenticationEndMs); else retvalSessionLifetimeMs = zeroIfNegative(Math.min(credentialExpirationMs - authenticationEndMs, connectionsMaxReauthMs)); sessionExpirationTimeNanos = Math.addExact(authenticationEndNanos, Utils.msToNs(retvalSessionLifetimeMs)); } if (credentialExpirationMs != null) { LOG.debug( "Authentication complete; session max lifetime from broker config={} ms, credential expiration={} ({} ms); session expiration = {} ({} ms), sending {} ms to client", connectionsMaxReauthMs, new Date(credentialExpirationMs), credentialExpirationMs - authenticationEndMs, new Date(authenticationEndMs + retvalSessionLifetimeMs), retvalSessionLifetimeMs, retvalSessionLifetimeMs); } else { if (sessionExpirationTimeNanos != null) LOG.debug( "Authentication complete; session max lifetime from broker config={} ms, no credential expiration; session expiration = {} ({} ms), sending {} ms to client", connectionsMaxReauthMs, new Date(authenticationEndMs + retvalSessionLifetimeMs), retvalSessionLifetimeMs, retvalSessionLifetimeMs); else LOG.debug( "Authentication complete; session max lifetime from broker config={} ms, no credential expiration; no session expiration, sending 0 ms to client", connectionsMaxReauthMs); } return retvalSessionLifetimeMs; } public Long reauthenticationLatencyMs() { if (!reauthenticating()) return null; // record at least 1 ms if there is some latency long latencyNanos = authenticationEndNanos - reauthenticationBeginNanos; return latencyNanos == 0L ? 0L : Math.max(1L, Math.round(latencyNanos / 1000.0 / 1000.0)); } private long zeroIfNegative(long value) { return Math.max(0L, value); } } }
apache/flink
38,124
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskExecutorSubmissionTest.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.runtime.taskexecutor; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.JobID; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.NettyShuffleEnvironmentOptions; import org.apache.flink.runtime.blob.PermanentBlobKey; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.deployment.InputGateDeploymentDescriptor; import org.apache.flink.runtime.deployment.ResultPartitionDeploymentDescriptor; import org.apache.flink.runtime.deployment.TaskDeploymentDescriptor; import org.apache.flink.runtime.deployment.TaskDeploymentDescriptorFactory.ShuffleDescriptorAndIndex; import org.apache.flink.runtime.execution.Environment; import org.apache.flink.runtime.execution.ExecutionState; import org.apache.flink.runtime.executiongraph.ExecutionAttemptID; import org.apache.flink.runtime.executiongraph.ExecutionGraphException; import org.apache.flink.runtime.executiongraph.JobInformation; import org.apache.flink.runtime.executiongraph.PartitionInfo; import org.apache.flink.runtime.executiongraph.TaskInformation; import org.apache.flink.runtime.io.network.partition.PartitionNotFoundException; import org.apache.flink.runtime.io.network.partition.ResultPartitionType; import org.apache.flink.runtime.jobgraph.IntermediateDataSetID; import org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID; import org.apache.flink.runtime.jobgraph.JobType; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobmaster.JobMasterId; import org.apache.flink.runtime.jobmaster.TestingAbstractInvokables; import org.apache.flink.runtime.jobmaster.utils.TestingJobMasterGateway; import org.apache.flink.runtime.jobmaster.utils.TestingJobMasterGatewayBuilder; import org.apache.flink.runtime.messages.Acknowledge; import org.apache.flink.runtime.shuffle.NettyShuffleDescriptor; import org.apache.flink.runtime.shuffle.PartitionDescriptor; import org.apache.flink.runtime.shuffle.PartitionDescriptorBuilder; import org.apache.flink.runtime.shuffle.PartitionWithMetrics; import org.apache.flink.runtime.shuffle.ShuffleEnvironment; import org.apache.flink.runtime.taskexecutor.slot.TaskSlotTable; import org.apache.flink.runtime.taskmanager.Task; import org.apache.flink.runtime.testtasks.BlockingNoOpInvokable; import org.apache.flink.runtime.util.NettyShuffleDescriptorBuilder; import org.apache.flink.testutils.TestingUtils; import org.apache.flink.testutils.executor.TestExecutorExtension; import org.apache.flink.util.NetUtils; import org.apache.flink.util.Preconditions; import org.apache.flink.util.SerializedValue; import org.apache.flink.util.concurrent.FutureUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mockito; import java.io.IOException; import java.net.URL; import java.time.Duration; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledExecutorService; import static org.apache.flink.core.testutils.FlinkAssertions.assertThatFuture; import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId; import static org.apache.flink.runtime.util.NettyShuffleDescriptorBuilder.createRemoteWithIdAndLocation; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; /** Tests for submission logic of the {@link TaskExecutor}. */ class TaskExecutorSubmissionTest { @RegisterExtension private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_EXTENSION = TestingUtils.defaultExecutorExtension(); private static final Duration timeout = Duration.ofMillis(10000L); private JobID jobId = new JobID(); private TestInfo testInfo; @BeforeEach void setUp(TestInfo testInfo) { this.testInfo = testInfo; } /** * Tests that we can submit a task to the TaskManager given that we've allocated a slot there. */ @Test void testTaskSubmission() throws Exception { final ExecutionAttemptID eid = createExecutionAttemptId(); final TaskDeploymentDescriptor tdd = createTestTaskDeploymentDescriptor( "test task", eid, FutureCompletingInvokable.class); final CompletableFuture<Void> taskRunningFuture = new CompletableFuture<>(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setSlotSize(1) .addTaskManagerActionListener( eid, ExecutionState.RUNNING, taskRunningFuture) .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd, env.getJobMasterId(), timeout).get(); taskRunningFuture.get(); } } /** * Tests that the TaskManager sends a proper exception back to the sender if the submit task * message fails. */ @Test void testSubmitTaskFailure() throws Exception { final ExecutionAttemptID eid = createExecutionAttemptId(); final TaskDeploymentDescriptor tdd = createTestTaskDeploymentDescriptor( "test task", eid, BlockingNoOpInvokable.class, 0); // this will make the submission fail because the number of key groups // must be >= 1 try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60)); assertThatFuture(tmGateway.submitTask(tdd, env.getJobMasterId(), timeout)) .eventuallyFailsWith(ExecutionException.class) .withCauseInstanceOf(IllegalArgumentException.class); } } /** Tests that we can cancel the task of the TaskManager given that we've submitted it. */ @Test void testTaskSubmissionAndCancelling() throws Exception { final ExecutionAttemptID eid1 = createExecutionAttemptId(); final ExecutionAttemptID eid2 = createExecutionAttemptId(); final TaskDeploymentDescriptor tdd1 = createTestTaskDeploymentDescriptor("test task", eid1, BlockingNoOpInvokable.class); final TaskDeploymentDescriptor tdd2 = createTestTaskDeploymentDescriptor("test task", eid2, BlockingNoOpInvokable.class); final CompletableFuture<Void> task1RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task1CanceledFuture = new CompletableFuture<>(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setSlotSize(2) .addTaskManagerActionListener( eid1, ExecutionState.RUNNING, task1RunningFuture) .addTaskManagerActionListener( eid2, ExecutionState.RUNNING, task2RunningFuture) .addTaskManagerActionListener( eid1, ExecutionState.CANCELED, task1CanceledFuture) .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd1.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd1, env.getJobMasterId(), timeout).get(); task1RunningFuture.get(); taskSlotTable.allocateSlot(1, jobId, tdd2.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd2, env.getJobMasterId(), timeout).get(); task2RunningFuture.get(); assertThat(taskSlotTable.getTask(eid1).getExecutionState()) .isEqualTo(ExecutionState.RUNNING); assertThat(taskSlotTable.getTask(eid2).getExecutionState()) .isEqualTo(ExecutionState.RUNNING); tmGateway.cancelTask(eid1, timeout); task1CanceledFuture.get(); assertThat(taskSlotTable.getTask(eid1).getExecutionState()) .isEqualTo(ExecutionState.CANCELED); assertThat(taskSlotTable.getTask(eid2).getExecutionState()) .isEqualTo(ExecutionState.RUNNING); } } /** * Tests that submitted tasks will fail when attempting to send/receive data if no * ResultPartitions/InputGates are set up. */ @Test void testGateChannelEdgeMismatch() throws Exception { final ExecutionAttemptID eid1 = createExecutionAttemptId(); final ExecutionAttemptID eid2 = createExecutionAttemptId(); final TaskDeploymentDescriptor tdd1 = createTestTaskDeploymentDescriptor( "Sender", eid1, TestingAbstractInvokables.Sender.class); final TaskDeploymentDescriptor tdd2 = createTestTaskDeploymentDescriptor( "Receiver", eid2, TestingAbstractInvokables.Receiver.class); final CompletableFuture<Void> task1RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task1FailedFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2FailedFuture = new CompletableFuture<>(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .addTaskManagerActionListener( eid1, ExecutionState.RUNNING, task1RunningFuture) .addTaskManagerActionListener( eid2, ExecutionState.RUNNING, task2RunningFuture) .addTaskManagerActionListener( eid1, ExecutionState.FAILED, task1FailedFuture) .addTaskManagerActionListener( eid2, ExecutionState.FAILED, task2FailedFuture) .setSlotSize(2) .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd1.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd1, env.getJobMasterId(), timeout).get(); task1RunningFuture.get(); taskSlotTable.allocateSlot(1, jobId, tdd2.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd2, env.getJobMasterId(), timeout).get(); task2RunningFuture.get(); task1FailedFuture.get(); task2FailedFuture.get(); assertThat(taskSlotTable.getTask(eid1).getExecutionState()) .isEqualTo(ExecutionState.FAILED); assertThat(taskSlotTable.getTask(eid2).getExecutionState()) .isEqualTo(ExecutionState.FAILED); } } @Test void testRunJobWithForwardChannel() throws Exception { ResourceID producerLocation = ResourceID.generate(); NettyShuffleDescriptor sdd = createRemoteWithIdAndLocation( new IntermediateResultPartitionID(), producerLocation); TaskDeploymentDescriptor tdd1 = createSender(sdd); TaskDeploymentDescriptor tdd2 = createReceiver(sdd); ExecutionAttemptID eid1 = tdd1.getExecutionAttemptId(); ExecutionAttemptID eid2 = tdd2.getExecutionAttemptId(); final CompletableFuture<Void> task1RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task1FinishedFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2FinishedFuture = new CompletableFuture<>(); final JobMasterId jobMasterId = JobMasterId.generate(); TestingJobMasterGateway testingJobMasterGateway = new TestingJobMasterGatewayBuilder() .setFencingTokenSupplier(() -> jobMasterId) .build(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setResourceID(producerLocation) .setSlotSize(2) .addTaskManagerActionListener( eid1, ExecutionState.RUNNING, task1RunningFuture) .addTaskManagerActionListener( eid2, ExecutionState.RUNNING, task2RunningFuture) .addTaskManagerActionListener( eid1, ExecutionState.FINISHED, task1FinishedFuture) .addTaskManagerActionListener( eid2, ExecutionState.FINISHED, task2FinishedFuture) .setJobMasterId(jobMasterId) .setJobMasterGateway(testingJobMasterGateway) .useRealNonMockShuffleEnvironment() .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd1.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd1, jobMasterId, timeout).get(); task1RunningFuture.get(); taskSlotTable.allocateSlot(1, jobId, tdd2.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd2, jobMasterId, timeout).get(); task2RunningFuture.get(); task1FinishedFuture.get(); task2FinishedFuture.get(); assertThat(taskSlotTable.getTask(eid1).getExecutionState()) .isEqualTo(ExecutionState.FINISHED); assertThat(taskSlotTable.getTask(eid2).getExecutionState()) .isEqualTo(ExecutionState.FINISHED); } } @Test void testGetPartitionWithMetrics() throws Exception { ResourceID producerLocation = ResourceID.generate(); NettyShuffleDescriptor sdd = createRemoteWithIdAndLocation( new IntermediateResultPartitionID(), producerLocation); PartitionDescriptor partitionDescriptor = PartitionDescriptorBuilder.newBuilder() .setPartitionId(sdd.getResultPartitionID().getPartitionId()) .setPartitionType(ResultPartitionType.BLOCKING) .build(); ResultPartitionDeploymentDescriptor resultPartitionDeploymentDescriptor = new ResultPartitionDeploymentDescriptor(partitionDescriptor, sdd, 1); TaskDeploymentDescriptor tdd = createTestTaskDeploymentDescriptor( "task", sdd.getResultPartitionID().getProducerId(), TestingAbstractInvokables.Sender.class, 1, Collections.singletonList(resultPartitionDeploymentDescriptor), Collections.emptyList()); ExecutionAttemptID eid = tdd.getExecutionAttemptId(); final CompletableFuture<Void> taskFinishedFuture = new CompletableFuture<>(); final JobMasterId jobMasterId = JobMasterId.generate(); TestingJobMasterGateway testingJobMasterGateway = new TestingJobMasterGatewayBuilder() .setFencingTokenSupplier(() -> jobMasterId) .build(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setResourceID(producerLocation) .setSlotSize(1) .addTaskManagerActionListener( eid, ExecutionState.FINISHED, taskFinishedFuture) .setJobMasterId(jobMasterId) .setJobMasterGateway(testingJobMasterGateway) .useRealNonMockShuffleEnvironment() .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd, jobMasterId, timeout).get(); taskFinishedFuture.get(); Collection<PartitionWithMetrics> partitionWithMetricsCollection = tmGateway.getAndRetainPartitionWithMetrics(jobId).get(); assertThat(partitionWithMetricsCollection.size()).isOne(); PartitionWithMetrics partitionWithMetrics = partitionWithMetricsCollection.iterator().next(); assertThat(partitionWithMetrics.getPartition().getResultPartitionID()) .isEqualTo(sdd.getResultPartitionID()); assertThat(partitionWithMetrics.getPartition().isUnknown()).isEqualTo(sdd.isUnknown()); assertThat(partitionWithMetrics.getPartition().storesLocalResourcesOn()) .isEqualTo(sdd.storesLocalResourcesOn()); assertThat( partitionWithMetrics .getPartitionMetrics() .getPartitionBytes() .getSubpartitionBytes()) // the sender task will send two int value, the expected bytes is 16. .isEqualTo(new long[] {16}); } } /** * This tests creates two tasks. The sender sends data but fails to send the state update back * to the job manager. the second one blocks to be canceled */ @Test void testCancellingDependentAndStateUpdateFails() throws Exception { ResourceID producerLocation = ResourceID.generate(); NettyShuffleDescriptor sdd = createRemoteWithIdAndLocation( new IntermediateResultPartitionID(), producerLocation); TaskDeploymentDescriptor tdd1 = createSender(sdd); TaskDeploymentDescriptor tdd2 = createReceiver(sdd); ExecutionAttemptID eid1 = tdd1.getExecutionAttemptId(); ExecutionAttemptID eid2 = tdd2.getExecutionAttemptId(); final CompletableFuture<Void> task1RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2RunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> task1FailedFuture = new CompletableFuture<>(); final CompletableFuture<Void> task2CanceledFuture = new CompletableFuture<>(); final JobMasterId jobMasterId = JobMasterId.generate(); TestingJobMasterGateway testingJobMasterGateway = new TestingJobMasterGatewayBuilder() .setFencingTokenSupplier(() -> jobMasterId) .setUpdateTaskExecutionStateFunction( taskExecutionState -> { if (taskExecutionState != null && taskExecutionState.getID().equals(eid1) && taskExecutionState.getExecutionState() == ExecutionState.RUNNING) { return FutureUtils.completedExceptionally( new ExecutionGraphException( "The execution attempt " + eid2 + " was not found.")); } else { return CompletableFuture.completedFuture(Acknowledge.get()); } }) .build(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setResourceID(producerLocation) .setSlotSize(2) .addTaskManagerActionListener( eid1, ExecutionState.RUNNING, task1RunningFuture) .addTaskManagerActionListener( eid2, ExecutionState.RUNNING, task2RunningFuture) .addTaskManagerActionListener( eid1, ExecutionState.FAILED, task1FailedFuture) .addTaskManagerActionListener( eid2, ExecutionState.CANCELED, task2CanceledFuture) .setJobMasterId(jobMasterId) .setJobMasterGateway(testingJobMasterGateway) .useRealNonMockShuffleEnvironment() .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd1.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd1, jobMasterId, timeout).get(); task1RunningFuture.get(); taskSlotTable.allocateSlot(1, jobId, tdd2.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd2, jobMasterId, timeout).get(); task2RunningFuture.get(); task1FailedFuture.get(); assertThat(taskSlotTable.getTask(eid1).getExecutionState()) .isEqualTo(ExecutionState.FAILED); tmGateway.cancelTask(eid2, timeout); task2CanceledFuture.get(); assertThat(taskSlotTable.getTask(eid2).getExecutionState()) .isEqualTo(ExecutionState.CANCELED); } } /** * Tests that repeated remote {@link PartitionNotFoundException}s ultimately fail the receiver. */ @Test void testRemotePartitionNotFound() throws Exception { try (NetUtils.Port port = NetUtils.getAvailablePort()) { final int dataPort = port.getPort(); Configuration config = new Configuration(); config.set(NettyShuffleEnvironmentOptions.DATA_PORT, dataPort); config.set(NettyShuffleEnvironmentOptions.NETWORK_REQUEST_BACKOFF_INITIAL, 100); config.set(NettyShuffleEnvironmentOptions.NETWORK_REQUEST_BACKOFF_MAX, 200); // Remote location (on the same TM though) for the partition NettyShuffleDescriptor sdd = NettyShuffleDescriptorBuilder.newBuilder().setDataPort(dataPort).buildRemote(); TaskDeploymentDescriptor tdd = createReceiver(sdd); ExecutionAttemptID eid = tdd.getExecutionAttemptId(); final CompletableFuture<Void> taskRunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> taskFailedFuture = new CompletableFuture<>(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setSlotSize(2) .addTaskManagerActionListener( eid, ExecutionState.RUNNING, taskRunningFuture) .addTaskManagerActionListener( eid, ExecutionState.FAILED, taskFailedFuture) .setConfiguration(config) .setLocalCommunication(false) .useRealNonMockShuffleEnvironment() .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd, env.getJobMasterId(), timeout).get(); taskRunningFuture.get(); taskFailedFuture.get(); assertThat(taskSlotTable.getTask(eid).getFailureCause()) .isInstanceOf(PartitionNotFoundException.class); } } } /** Tests that the TaskManager fails the task if the partition update fails. */ @Test void testUpdateTaskInputPartitionsFailure() throws Exception { final ExecutionAttemptID eid = createExecutionAttemptId(); final TaskDeploymentDescriptor tdd = createTestTaskDeploymentDescriptor("test task", eid, BlockingNoOpInvokable.class); final CompletableFuture<Void> taskRunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> taskFailedFuture = new CompletableFuture<>(); final ShuffleEnvironment<?, ?> shuffleEnvironment = mock(ShuffleEnvironment.class, Mockito.RETURNS_MOCKS); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setShuffleEnvironment(shuffleEnvironment) .setSlotSize(1) .addTaskManagerActionListener( eid, ExecutionState.RUNNING, taskRunningFuture) .addTaskManagerActionListener(eid, ExecutionState.FAILED, taskFailedFuture) .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd, env.getJobMasterId(), timeout).get(); taskRunningFuture.get(); final ResourceID producerLocation = env.getTaskExecutor().getResourceID(); NettyShuffleDescriptor shuffleDescriptor = createRemoteWithIdAndLocation( new IntermediateResultPartitionID(), producerLocation); final PartitionInfo partitionUpdate = new PartitionInfo(new IntermediateDataSetID(), shuffleDescriptor); doThrow(new IOException()) .when(shuffleEnvironment) .updatePartitionInfo(eid, partitionUpdate); final CompletableFuture<Acknowledge> updateFuture = tmGateway.updatePartitions( eid, Collections.singletonList(partitionUpdate), timeout); updateFuture.get(); taskFailedFuture.get(); Task task = taskSlotTable.getTask(tdd.getExecutionAttemptId()); assertThat(task.getExecutionState()).isEqualTo(ExecutionState.FAILED); assertThat(task.getFailureCause()).isInstanceOf(IOException.class); } } /** * Tests that repeated local {@link PartitionNotFoundException}s ultimately fail the receiver. */ @Test void testLocalPartitionNotFound() throws Exception { ResourceID producerLocation = ResourceID.generate(); NettyShuffleDescriptor shuffleDescriptor = createRemoteWithIdAndLocation( new IntermediateResultPartitionID(), producerLocation); TaskDeploymentDescriptor tdd = createReceiver(shuffleDescriptor); ExecutionAttemptID eid = tdd.getExecutionAttemptId(); Configuration config = new Configuration(); config.set(NettyShuffleEnvironmentOptions.NETWORK_REQUEST_BACKOFF_INITIAL, 100); config.set(NettyShuffleEnvironmentOptions.NETWORK_REQUEST_BACKOFF_MAX, 200); final CompletableFuture<Void> taskRunningFuture = new CompletableFuture<>(); final CompletableFuture<Void> taskFailedFuture = new CompletableFuture<>(); try (TaskSubmissionTestEnvironment env = new TaskSubmissionTestEnvironment.Builder(jobId) .setResourceID(producerLocation) .setSlotSize(1) .addTaskManagerActionListener( eid, ExecutionState.RUNNING, taskRunningFuture) .addTaskManagerActionListener(eid, ExecutionState.FAILED, taskFailedFuture) .setConfiguration(config) .useRealNonMockShuffleEnvironment() .build(EXECUTOR_EXTENSION.getExecutor())) { TaskExecutorGateway tmGateway = env.getTaskExecutorGateway(); TaskSlotTable<Task> taskSlotTable = env.getTaskSlotTable(); taskSlotTable.allocateSlot(0, jobId, tdd.getAllocationId(), Duration.ofSeconds(60)); tmGateway.submitTask(tdd, env.getJobMasterId(), timeout).get(); taskRunningFuture.get(); taskFailedFuture.get(); assertThat(taskSlotTable.getTask(eid).getExecutionState()) .isEqualTo(ExecutionState.FAILED); assertThat(taskSlotTable.getTask(eid).getFailureCause()) .isInstanceOf(PartitionNotFoundException.class); } } private TaskDeploymentDescriptor createSender(NettyShuffleDescriptor shuffleDescriptor) throws IOException { return createSender(shuffleDescriptor, TestingAbstractInvokables.Sender.class); } private TaskDeploymentDescriptor createSender( NettyShuffleDescriptor shuffleDescriptor, Class<? extends AbstractInvokable> abstractInvokable) throws IOException { PartitionDescriptor partitionDescriptor = PartitionDescriptorBuilder.newBuilder() .setPartitionId(shuffleDescriptor.getResultPartitionID().getPartitionId()) .build(); ResultPartitionDeploymentDescriptor resultPartitionDeploymentDescriptor = new ResultPartitionDeploymentDescriptor(partitionDescriptor, shuffleDescriptor, 1); return createTestTaskDeploymentDescriptor( "Sender", shuffleDescriptor.getResultPartitionID().getProducerId(), abstractInvokable, 1, Collections.singletonList(resultPartitionDeploymentDescriptor), Collections.emptyList()); } private TaskDeploymentDescriptor createReceiver(NettyShuffleDescriptor shuffleDescriptor) throws IOException { InputGateDeploymentDescriptor inputGateDeploymentDescriptor = new InputGateDeploymentDescriptor( new IntermediateDataSetID(), ResultPartitionType.PIPELINED, 0, new ShuffleDescriptorAndIndex[] { new ShuffleDescriptorAndIndex(shuffleDescriptor, 0) }); return createTestTaskDeploymentDescriptor( "Receiver", createExecutionAttemptId(), TestingAbstractInvokables.Receiver.class, 1, Collections.emptyList(), Collections.singletonList(inputGateDeploymentDescriptor)); } private TaskDeploymentDescriptor createTestTaskDeploymentDescriptor( String taskName, ExecutionAttemptID eid, Class<? extends AbstractInvokable> abstractInvokable) throws IOException { return createTestTaskDeploymentDescriptor(taskName, eid, abstractInvokable, 1); } private TaskDeploymentDescriptor createTestTaskDeploymentDescriptor( String taskName, ExecutionAttemptID eid, Class<? extends AbstractInvokable> abstractInvokable, int maxNumberOfSubtasks) throws IOException { return createTestTaskDeploymentDescriptor( taskName, eid, abstractInvokable, maxNumberOfSubtasks, Collections.emptyList(), Collections.emptyList()); } private TaskDeploymentDescriptor createTestTaskDeploymentDescriptor( String taskName, ExecutionAttemptID eid, Class<? extends AbstractInvokable> abstractInvokable, int maxNumberOfSubtasks, List<ResultPartitionDeploymentDescriptor> producedPartitions, List<InputGateDeploymentDescriptor> inputGates) throws IOException { Preconditions.checkNotNull(producedPartitions); Preconditions.checkNotNull(inputGates); return createTaskDeploymentDescriptor( jobId, testInfo.getDisplayName(), eid, new SerializedValue<>(new ExecutionConfig()), taskName, maxNumberOfSubtasks, 1, new Configuration(), new Configuration(), abstractInvokable.getName(), producedPartitions, inputGates, Collections.emptyList(), Collections.emptyList()); } static TaskDeploymentDescriptor createTaskDeploymentDescriptor( JobID jobId, String jobName, ExecutionAttemptID executionAttemptId, SerializedValue<ExecutionConfig> serializedExecutionConfig, String taskName, int maxNumberOfSubtasks, int numberOfSubtasks, Configuration jobConfiguration, Configuration taskConfiguration, String invokableClassName, List<ResultPartitionDeploymentDescriptor> producedPartitions, List<InputGateDeploymentDescriptor> inputGates, Collection<PermanentBlobKey> requiredJarFiles, Collection<URL> requiredClasspaths) throws IOException { JobInformation jobInformation = new JobInformation( jobId, JobType.STREAMING, jobName, serializedExecutionConfig, jobConfiguration, requiredJarFiles, requiredClasspaths); TaskInformation taskInformation = new TaskInformation( executionAttemptId.getJobVertexId(), taskName, numberOfSubtasks, maxNumberOfSubtasks, invokableClassName, taskConfiguration); SerializedValue<JobInformation> serializedJobInformation = new SerializedValue<>(jobInformation); SerializedValue<TaskInformation> serializedJobVertexInformation = new SerializedValue<>(taskInformation); return new TaskDeploymentDescriptor( jobId, new TaskDeploymentDescriptor.NonOffloaded<>(serializedJobInformation), new TaskDeploymentDescriptor.NonOffloaded<>(serializedJobVertexInformation), executionAttemptId, new AllocationID(), null, producedPartitions, inputGates); } /** Test invokable which completes the given future when executed. */ public static class FutureCompletingInvokable extends AbstractInvokable { static final CompletableFuture<Boolean> COMPLETABLE_FUTURE = new CompletableFuture<>(); public FutureCompletingInvokable(Environment environment) { super(environment); } @Override public void invoke() throws Exception { COMPLETABLE_FUTURE.complete(true); } } }
oracle/graalpython
37,872
graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/formatting/FloatFormatter.java
/* * Copyright (c) 2017, 2023, Oracle and/or its affiliates. * Copyright (c) 2016 Jython Developers * * Licensed under PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 */ package com.oracle.graal.python.runtime.formatting; import static com.oracle.graal.python.runtime.formatting.InternalFormat.Spec.specified; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import com.oracle.graal.python.runtime.formatting.InternalFormat.Spec; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.nodes.Node; /** * A class that provides the implementation of floating-point formatting. In a limited way, it acts * like a StringFormattingBuffer to which text and one or more numbers may be appended, formatted * according to the format specifier supplied at construction. These are ephemeral objects that are * not, on their own, thread safe. */ public class FloatFormatter extends InternalFormat.Formatter { /** The rounding mode dominant in the formatter. */ static final RoundingMode ROUND_PY = RoundingMode.HALF_EVEN; /** If it contains no decimal point, this length is zero, and 1 otherwise. */ private int lenPoint; /** The length of the fractional part, right of the decimal point. */ private int lenFraction; /** The length of the exponent marker ("e"), "inf" or "nan", or zero if there isn't one. */ private int lenMarker; /** The length of the exponent sign and digits or zero if there isn't one. */ private int lenExponent; /** if >=0, minimum digits to follow decimal point (where consulted) */ private int minFracDigits; /** * Construct the formatter from a client-supplied buffer, to which the result will be appended, * and a specification. Sets {@link #mark} to the end of the buffer. * * @param result destination buffer * @param spec parsed conversion specification * @param addDot0 reflects flag {@code Py_DTSF_ADD_DOT_0} in CPython, applicable only for 'r' * specifier */ public FloatFormatter(FormattingBuffer result, Spec spec, boolean addDot0, Node raisingNode) { super(result, spec, raisingNode); if (!addDot0 && spec.type == 'r') { minFracDigits = 0; } else if (spec.alternate) { // Alternate form means do not trim the zero fractional digits. // This should be equivalent to Py_DTSF_ALT flag in CPython minFracDigits = -1; } else if (spec.type == 'r' || spec.type == Spec.NONE) { // These formats by default show at least one fractional digit. minFracDigits = 1; } else { /* * Every other format (if it does not ignore the setting) will by default trim off all * the trailing zero fractional digits. */ minFracDigits = 0; } } public FloatFormatter(FormattingBuffer result, Spec spec, Node raisingNode) { this(result, spec, true, raisingNode); } public FloatFormatter(Spec spec, Node raisingNode) { this(new FormattingBuffer.StringFormattingBuffer(size(spec)), spec, raisingNode); } /** * Recommend a buffer size for a given specification, assuming one float is converted. This will * be a "right" answer for e and g-format, and for f-format with values up to 9,999,999. * * @param spec parsed conversion specification */ public static int size(Spec spec) { // Rule of thumb used here (no right answer): // in e format each float occupies: (p-1) + len("+1.e+300") = p+7; // in f format each float occupies: p + len("1,000,000.%") = p+11; // or an explicit (minimum) width may be given, with one overshoot possible. return Math.max(spec.width + 1, spec.getPrecision(6) + 11); } /** * Override the default truncation behaviour for the specification originally supplied. Some * formats remove trailing zero digits, trimming to zero or one. Set member * <code>minFracDigits</code>, to modify this behaviour. * * @param minFracDigits if &lt;0 prevent truncation; if >=0 the minimum number of fractional * digits; when this is zero, and all fractional digits are zero, the decimal point * will also be removed. */ public void setMinFracDigits(int minFracDigits) { this.minFracDigits = minFracDigits; } @Override protected void reset() { // Clear the variables describing the latest number in result. super.reset(); lenPoint = lenFraction = lenMarker = lenExponent = 0; } @Override protected int[] sectionLengths() { return new int[]{lenSign, lenWhole, lenPoint, lenFraction, lenMarker, lenExponent}; } /* * Re-implement the text appends so they return the right type. */ @Override public FloatFormatter append(char c) { super.append(c); return this; } @Override public FloatFormatter append(CharSequence csq) { super.append(csq); return this; } @Override public FloatFormatter append(CharSequence csq, int begin, int end) // throws IndexOutOfBoundsException { super.append(csq, begin, end); return this; } /** * Format a floating-point number according to the specification represented by this * <code>FloatFormatter</code>. * * @param value to convert * @return this object */ public FloatFormatter format(double value) { return format(value, null); } /** * Format a floating-point number according to the specification represented by this * <code>FloatFormatter</code>. The conversion type, precision, and flags for grouping or * percentage are dealt with here. At the point this is used, we know the {@link #spec} is one * of the floating-point types. This entry point allows explicit control of the prefix of * positive numbers, overriding defaults for the format type. * * @param value to convert * @param positivePrefixString to use before positive values (e.g. "+") or null to default to "" * @return this object */ @TruffleBoundary public FloatFormatter format(double value, String positivePrefixString) { String positivePrefix = positivePrefixString; // Puts all instance variables back to their starting defaults, and start = result.length(). setStart(); // Precision defaults to 6 (or 12 for none-format) int precision = spec.getPrecision(6); /* * By default, the prefix of a positive number is "", but the format specifier may override * it, and the built-in type complex needs to override the format. */ char sign = spec.sign; if (positivePrefix == null && specified(sign) && sign != '-') { positivePrefix = Character.toString(sign); } char type = spec.type; int expThresholdAdj = 0; if (!specified(spec.type) && specified(spec.precision)) { // No specifier normally means do what __str__ would do, but if precision is specified, // we switch to g, moreover, CPython also adjusts the exponential notation threshold type = 'g'; expThresholdAdj = -1; } // Different process for each format type, ignoring case for now. switch (Character.toLowerCase(type)) { case 'e': // Exponential case: 1.23e-45 format_e(value, positivePrefix, precision); break; case 'f': // Fixed case: 123.45 format_f(value, positivePrefix, precision); break; case 'g': // General format: fixed or exponential according to value. format_g(value, positivePrefix, precision, expThresholdAdj); break; case 'n': // Locale aware version of 'g' format_g(value, positivePrefix, precision, expThresholdAdj); DecimalFormat format = getCurrentDecimalFormat(); if (format != null) { setGroupingAndGroupSize(format); DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); if (lenPoint > 0) { result.setCharAt(lenWhole, symbols.getDecimalSeparator()); } } break; case Spec.NONE: case 'r': // For float.__repr__, very special case, breaks all the rules. format_r(value, positivePrefix); break; case '%': // Multiplies by 100 and displays in f-format, followed by a percent sign. format_f(100. * value, positivePrefix, precision); result.append('%'); break; default: // Should never get here, since this was checked in PyFloat. throw unknownFormat(spec.type, "float", raisingNode); } // If the format type is an upper-case letter, convert the result to upper case. if (Character.isUpperCase(spec.type)) { uppercase(); } // If required to, group the whole-part digits. groupWholePartIfRequired(); return this; } /** * Convert just the letters in the representation of the current number (in {@link #result}) to * upper case. (That's the exponent marker or the "inf" or "nan".) */ @Override protected void uppercase() { int letters = indexOfMarker(); int end = letters + lenMarker; for (int i = letters; i < end; i++) { char c = result.charAt(i); result.setCharAt(i, Character.toUpperCase(c)); } } /** * Common code to deal with the sign, and the special cases "0", "-0", "nan, "inf", or "-inf". * If the method returns <code>false</code>, we have started a non-zero number and the sign is * already in {@link #result}. The client need then only encode <i>abs(value)</i>. If the method * returns <code>true</code>, and {@link #lenMarker}==0, the value was "0" or "-0": the caller * may have to zero-extend this, and/or add an exponent, to match the requested format. If the * method returns <code>true</code>, and {@link #lenMarker}>0, the method has placed "nan, "inf" * in the {@link #result} buffer (preceded by a sign if necessary). * * @param value to convert * @return true if the value was one of "0", "-0", "nan, "inf", or "-inf". * @param positivePrefix to use before positive values (e.g. "+") or null to default to "" */ private boolean signAndSpecialNumber(double value, String positivePrefix) { // This is easiest via the raw bits long bits = Double.doubleToRawLongBits(value); // NaN is always positive if (Double.isNaN(value)) { bits &= ~SIGN_MASK; } if ((bits & SIGN_MASK) != 0) { // Negative: encode a minus sign and strip it off bits result.append('-'); lenSign = 1; bits &= ~SIGN_MASK; } else if (positivePrefix != null) { // Positive, and a prefix is required. Note CPython 2.7 produces "+nan", " nan". result.append(positivePrefix); lenSign = positivePrefix.length(); } if (bits == 0L) { // All zero means it's zero. (It may have been negative, producing -0.) result.append('0'); lenWhole = 1; return true; } else if ((bits & EXP_MASK) == EXP_MASK) { // This is characteristic of NaN or Infinity. result.append(((bits & ~EXP_MASK) == 0L) ? "inf" : "nan"); lenMarker = 3; return true; } else { return false; } } private static final long SIGN_MASK = 0x8000000000000000L; private static final long EXP_MASK = 0x7ff0000000000000L; /** * The e-format helper function of {@link #format(double, String)} that uses Java's * {@link BigDecimal} to provide conversion and rounding. The converted number is appended to * the {@link #result} buffer, and {@link #start} will be set to the index of its first * character. * * @param value to convert * @param positivePrefix to use before positive values (e.g. "+") or null to default to "" * @param precision precision (maximum number of fractional digits) */ private void format_e(double value, String positivePrefix, int precision) { // Exponent (default value is for 0.0 and -0.0) int exp = 0; if (!signAndSpecialNumber(value, positivePrefix)) { // Convert abs(value) to decimal with p+1 digits of accuracy. MathContext mc = new MathContext(precision + 1, ROUND_PY); BigDecimal vv = new BigDecimal(Math.abs(value), mc); // Take explicit control in order to get exponential notation out of BigDecimal. String digits = vv.unscaledValue().toString(); int digitCount = digits.length(); result.append(digits.charAt(0)); lenWhole = 1; if (digitCount > 1) { // There is a fractional part result.append('.').append(digits.substring(1)); lenPoint = 1; lenFraction = digitCount - 1; } exp = lenFraction - vv.scale(); } // If the result is not already complete, add point and zeros as necessary, and exponent. if (lenMarker == 0) { ensurePointAndTrailingZeros(precision); appendExponent(exp); } } /** * The f-format inner helper function of {@link #format(double, String)} that uses Java's * {@link BigDecimal} to provide conversion and rounding. The converted number is appended to * the {@link #result} buffer, and {@link #start} will be set to the index of its first * character. * * @param value to convert * @param positivePrefix to use before positive values (e.g. "+") or null to default to "" * @param precision precision (maximum number of fractional digits) */ private void format_f(double value, String positivePrefix, int precision) { if (!signAndSpecialNumber(value, positivePrefix)) { // Convert value to decimal exactly. (This can be very long.) BigDecimal vLong = new BigDecimal(Math.abs(value)); // Truncate to the defined number of places to the right of the decimal point). BigDecimal vv = vLong.setScale(precision, ROUND_PY); // When converted to text, the number of fractional digits is exactly the scale we set. String raw = vv.toPlainString(); result.append(raw); if ((lenFraction = vv.scale()) > 0) { // There is a decimal point and some digits following lenWhole = result.length() - (start + lenSign + (lenPoint = 1) + lenFraction); } else { // There are no fractional digits and so no decimal point lenWhole = result.length() - (start + lenSign); } } // Finally, ensure we have all the fractional digits we should. if (lenMarker == 0) { ensurePointAndTrailingZeros(precision); } } /** * Append a decimal point and trailing fractional zeros if necessary for 'e' and 'f' format. * This should not be called if the result is not numeric ("inf" for example). This method deals * with the following complexities: on return there will be at least the number of fractional * digits specified in the argument <code>n</code>, and at least {@link #minFracDigits}; * further, if <code>minFracDigits&lt;0</code>, signifying the "alternate mode" of certain * formats, the method will ensure there is a decimal point, even if there are no fractional * digits to follow. * * @param numDigits smallest number of fractional digits on return */ private void ensurePointAndTrailingZeros(int numDigits) { int n = numDigits; // Set n to the number of fractional digits we should have. if (n < minFracDigits) { n = minFracDigits; } // Do we have a decimal point already? if (lenPoint == 0) { // No decimal point: add one if there will be any fractional digits or if (n > 0 || minFracDigits < 0) { // First need to add a decimal point. result.append('.'); lenPoint = 1; } } // Do we have enough fractional digits already? int f = lenFraction; if (n > f) { // Make up the required number of zeros. for (; f < n; f++) { result.append('0'); } lenFraction = f; } } /** * Implementation of the variants of g-format, that uses Java's {@link BigDecimal} to provide * conversion and rounding. These variants are g-format proper, alternate g-format (available * for "%#g" formatting), n-format (as g but subsequently "internationalised"), and none-format * (type code Spec.NONE). * <p> * None-format is the basis of <code>float.__str__</code>. * <p> * According to the Python documentation for g-format, the precise rules are as follows: suppose * that the result formatted with presentation type <code>'e'</code> and precision <i>p-1</i> * would have exponent exp. Then if <i>-4 &lt;= exp < p</i>, the number is formatted with * presentation type <code>'f'</code> and precision <i>p-1-exp</i>. Otherwise, the number is * formatted with presentation type <code>'e'</code> and precision <i>p-1</i>. In both cases * insignificant trailing zeros are removed from the significand, and the decimal point is also * removed if there are no remaining digits following it. * <p> * The Python documentation says none-format is the same as g-format, but the observed behaviour * differs from this, in that f-format is only used if <i>-4 &lt;= exp < p-1</i> (i.e. one * less), and at least one digit to the right of the decimal point is preserved in the f-format * (but not the e-format). That behaviour is controlled through the following arguments, with * these recommended values: * * <table> * <tr> * <th>type</th> * <th>precision</th> * <th>minFracDigits</th> * <th>expThresholdAdj</th> * <td>expThreshold</td> * </tr> * <tr> * <th>g</th> * <td>p</td> * <td>0</td> * <td>0</td> * <td>p</td> * </tr> * <tr> * <th>#g</th> * <td>p</td> * <td>-</td> * <td>0</td> * <td>p</td> * </tr> * <tr> * <th>\0</th> * <td>p</td> * <td>1</td> * <td>-1</td> * <td>p-1</td> * </tr> * <tr> * <th>__str__</th> * <td>12</td> * <td>1</td> * <td>-1</td> * <td>11</td> * </tr> * </table> * * @param value to convert * @param positivePrefix to use before positive values (e.g. "+") or null to default to "" * @param precision total number of significant digits (precision 0 behaves as 1) * @param expThresholdAdj <code>+precision =</code> the exponent at which to resume using * exponential notation */ private void format_g(double value, String positivePrefix, int precision, int expThresholdAdj) { // Precision 0 behaves as 1 int prec = Math.max(1, precision); // Use exponential notation if exponent would be bigger thatn: int expThreshold = prec + expThresholdAdj; if (signAndSpecialNumber(value, positivePrefix)) { // Finish formatting if zero result. (This is a no-op for nan or inf.) zeroHelper(prec, expThreshold); } else { // Convert abs(value) to decimal with p digits of accuracy. MathContext mc = new MathContext(prec, ROUND_PY); BigDecimal vv = new BigDecimal(Math.abs(value), mc); // This gives us the digits we need for either fixed or exponential format. String pointlessDigits = vv.unscaledValue().toString(); // If we were to complete this as e-format, the exponent would be: int exp = pointlessDigits.length() - vv.scale() - 1; if (-4 <= exp && exp < expThreshold) { // Finish the job as f-format with variable-prec p-(exp+1). appendFixed(pointlessDigits, exp, prec); } else { // Finish the job as e-format. appendExponential(pointlessDigits, exp); } } } /** * Implementation of r-format (<code>float.__repr__</code>) that uses Java's * {@link Double#toString(double)} to provide conversion and rounding. That method gives us * almost what we need, but not quite (sometimes it yields 18 digits): here we always round to * 17 significant digits. Much of the formatting after conversion is shared with * format_g(double, String, int, int, int). <code>minFracDigits</code> is consulted since while * <code>float.__repr__</code> truncates to one digit, within <code>complex.__repr__</code> we * truncate fully. * * @param value to convert * @param positivePrefix to use before positive values (e.g. "+") or null to default to "" */ private void format_r(double value, String positivePrefix) { // Characteristics of repr (precision = 17 and go exponential at 16). int precision = 17; int expThreshold = precision - 1; if (signAndSpecialNumber(value, positivePrefix)) { // Finish formatting if zero result. (This is a no-op for nan or inf.) zeroHelper(precision, expThreshold); } else { // Generate digit sequence (with no decimal point) with custom rounding. FormattingBuffer.StringFormattingBuffer pointlessBuffer = new FormattingBuffer.StringFormattingBuffer(20); int exp = reprDigits(Math.abs(value), precision, pointlessBuffer); if (-4 <= exp && exp < expThreshold) { // Finish the job as f-format with variable-precision p-(exp+1). appendFixed(pointlessBuffer, exp, precision); } else { // Finish the job as e-format. appendExponential(pointlessBuffer, exp); } } } /** * Common code for g-format, none-format and r-format called when the conversion yields "inf", * "nan" or zero. The method completes formatting of the zero, with the appropriate number of * decimal places or (in particular circumstances) exponential; notation. * * @param precision of conversion (number of significant digits). * @param expThreshold if zero, causes choice of exponential notation for zero. */ private void zeroHelper(int precision, int expThreshold) { if (lenMarker == 0) { // May be 0 or -0 so we still need to ... if (minFracDigits < 0) { // In "alternate format", we won't economise trailing zeros. appendPointAndTrailingZeros(precision - 1); } else if (lenFraction < minFracDigits) { // Otherwise, it should be at least the stated minimum length. appendTrailingZeros(minFracDigits); } // And just occasionally (in none-format) we go exponential even when exp = 0... if (0 >= expThreshold) { appendExponent(0); } } } /** * Common code for g-format, none-format and r-format used when the exponent is such that a * fixed-point presentation is chosen. Normally the method removes trailing digits so as to * shorten the presentation without loss of significance. This method respects the minimum * number of fractional digits (digits after the decimal point), in member * <code>minFracDigits</code>, which is 0 for g-format and 1 for none-format and r-format. When * <code>minFracDigits&lt;0</code> this signifies "no truncation" mode, in which trailing zeros * generated in the conversion are not removed. This supports "%#g" format. * * @param digits from converting the value at a given precision. * @param exp would be the exponent (in e-format), used to position the decimal point. * @param precision of conversion (number of significant digits). */ private void appendFixed(CharSequence digits, int exp, int precision) { // Check for "alternate format", where we won't economise trailing zeros. boolean noTruncate = (minFracDigits < 0); int digitCount = digits.length(); if (exp < 0) { // For a negative exponent, we must insert leading zeros 0.000 ... result.append("0."); lenWhole = lenPoint = 1; for (int i = -1; i > exp; --i) { result.append('0'); } // Then the generated digits (always enough to satisfy no-truncate mode). result.append(digits); lenFraction = digitCount - exp - 1; } else { // For a non-negative exponent, it's a question of placing the decimal point. int w = exp + 1; if (w < digitCount) { // There are w whole-part digits result.append(digits.subSequence(0, w)); lenWhole = w; result.append('.').append(digits.subSequence(w, digitCount)); lenPoint = 1; lenFraction = digitCount - w; } else { // All the digits are whole-part digits. result.append(digits); // Just occasionally (in r-format) we need more digits than the precision. while (digitCount < w) { result.append('0'); digitCount += 1; } lenWhole = digitCount; } } if (noTruncate) { // Extend the fraction as BigDecimal will have economised on zeros. appendPointAndTrailingZeros(lenFraction + precision - digitCount); } // Finally, ensure we have all and only the fractional digits we should. if (!noTruncate) { if (lenFraction < minFracDigits) { // Otherwise, it should be at least the stated minimum length. appendTrailingZeros(minFracDigits); } else { // And no more removeTrailingZeros(minFracDigits); } } } /** * Common code for g-format, none-format and r-format used when the exponent is such that an * exponential presentation is chosen. Normally the method removes trailing digits so as to * shorten the presentation without loss of significance. Although no minimum number of * fractional digits is enforced in the exponential presentation, when * <code>minFracDigits&lt;0</code> this signifies "no truncation" mode, in which trailing zeros * generated in the conversion are not removed. This supports "%#g" format. * * @param digits from converting the value at a given precision. * @param exp would be the exponent (in e-format), used to position the decimal point. */ private void appendExponential(CharSequence digits, int exp) { // The whole-part is the first digit. result.append(digits.charAt(0)); lenWhole = 1; // And the rest of the digits form the fractional part int digitCount = digits.length(); result.append('.').append(digits.subSequence(1, digitCount)); lenPoint = 1; lenFraction = digitCount - 1; // In no-truncate mode, the fraction is full precision. Otherwise trim it. if (minFracDigits >= 0) { // Note positive minFracDigits only applies to fixed formats. removeTrailingZeros(0); } // Finally, append the exponent as e+nn. appendExponent(exp); } /** * Convert a double to digits and an exponent for use in <code>float.__repr__</code> (or * r-format). This method takes advantage of (or assumes) a close correspondence between * {@link Double#toString(double)} and Python <code>float.__repr__</code>. The correspondence * appears to be exact, insofar as the Java method produces the minimal non-zero digit string. * It mostly chooses the same number of digits (and the same digits) as the CPython repr, but in * a few cases <code>Double.toString</code> produces more digits. This method truncates to the * number <code>maxDigits</code>, which in practice is always 17. * * @param value to convert * @param maxDigits maximum number of digits to return in <code>buf</code>. * @param buf for digits of result (recommend size be 20) * @return the exponent */ private static int reprDigits(double value, int maxDigits, FormattingBuffer.StringFormattingBuffer buf) { // Most of the work is done by Double. String s = Double.toString(value); // Variables for scanning the string int p = 0, end = s.length(), first = 0, point = end, exp; char c = 0; boolean allZero = true; // Scan whole part and fractional part digits buf.ensureAdditionalCapacity(s.length()); // this may over-allocate a bit while (p < end) { c = s.charAt(p++); if (Character.isDigit(c)) { if (allZero) { if (c != '0') { // This is the first non-zero digit. buf.append(c); allZero = false; // p is one *after* the first non-zero digit. first = p; } // Only seen zeros so far: do nothing. } else { // We've started, so every digit counts. buf.append(c); } } else if (c == '.') { // We remember this location (one *after* '.') to calculate the exponent later. point = p; } else { // Something after the mantissa. (c=='E' we hope.) break; } } // Possibly followed by an exponent. p has already advanced past the 'E'. if (p < end && c == 'E') { // If there is an exponent, the mantissa must be in standard form: m.mmmm assert point == first + 1; exp = Integer.parseInt(s.substring(p)); } else { // Exponent is based on relationship of decimal point and first non-zero digit. exp = point - first - 1; // But that's only correct when the point is to the right (or absent). if (exp < 0) { // The point is to the left of the first digit exp += 1; // = -(first-point) } } /* * XXX This still does not round in all the cases it could. I think Java stops generating * digits when the residual is <= ulp/2. This is to neglect the possibility that the extra * ulp/2 (before it becomes a different double) could take us to a rounder numeral. To fix * this, we could express ulp/2 as digits in the same scale as those in the buffer, and * consider adding them. But Java's behaviour here is probably a manifestation of bug * JDK-4511638. */ // Sometimes the result is more digits than we want for repr. if (buf.length() > maxDigits) { // Chop the trailing digits, remembering the most significant lost digit. int d = buf.charAt(maxDigits); buf.setLength(maxDigits); // We round half up. Not absolutely correct since Double has already rounded. if (d >= '5') { // Treat this as a "carry one" into the numeral buf[0:maxDigits]. for (p = maxDigits - 1; p >= 0; p--) { // Each pass of the loop does one carry from buf[p+1] to buf[p]. d = buf.charAt(p) + 1; if (d <= '9') { // Carry propagation stops here. buf.setCharAt(p, (char) d); break; } else { // 9 + 1 -> 0 carry 1. Keep looping. buf.setCharAt(p, '0'); } } if (p < 0) { /* * We fell off the bottom of the buffer with one carry still to propagate. You * may expect: buf.insert(0, '1') here, but note that every digit in * buf[0:maxDigits] is currently '0', so all we need is: */ buf.setCharAt(0, '1'); exp += 1; } } } return exp; } /** * Append the trailing fractional zeros, as required by certain formats, so that the total * number of fractional digits is no less than specified. If <code>n&lt;=0</code>, the method * leaves the {@link #result} buffer unchanged. * * @param n smallest number of fractional digits on return */ private void appendTrailingZeros(int n) { int f = lenFraction; if (n > f) { if (lenPoint == 0) { // First need to add a decimal point. (Implies lenFraction=0.) result.append('.'); lenPoint = 1; } // Now make up the required number of zeros. for (; f < n; f++) { result.append('0'); } lenFraction = f; } } /** * Append the trailing fractional zeros, as required by certain formats, so that the total * number of fractional digits is no less than specified. If there is no decimal point * originally (and therefore no fractional part), the method will add a decimal point, even if * it adds no zeros. * * @param n smallest number of fractional digits on return */ private void appendPointAndTrailingZeros(int n) { if (lenPoint == 0) { // First need to add a decimal point. (Implies lenFraction=0.) result.append('.'); lenPoint = 1; } // Now make up the required number of zeros. int f; for (f = lenFraction; f < n; f++) { result.append('0'); } lenFraction = f; } /** * Remove trailing zeros from the fractional part, as required by certain formats, leaving at * least the number of fractional digits specified. If the resultant number of fractional digits * is zero, this method will also remove the trailing decimal point (if there is one). * * @param n smallest number of fractional digits on return */ private void removeTrailingZeros(int n) { if (lenPoint > 0) { // There's a decimal point at least, and there may be some fractional digits. int f = lenFraction; if (n == 0 || f > n) { int fracStart = result.length() - f; for (; f > n; --f) { if (result.charAt(fracStart - 1 + f) != '0') { // Keeping this one as it isn't a zero break; } } // f is now the number of fractional digits we wish to retain. if (f == 0 && lenPoint > 0) { // We will be stripping all the fractional digits. Take the decimal point too. lenPoint = lenFraction = 0; f = -1; } else { lenFraction = f; } // Snip the characters we are going to remove (if any). if (fracStart + f < result.length()) { result.setLength(fracStart + f); } } } } /** * Append the current value of {@code exp} in the format <code>"e{:+02d}"</code> (for example * <code>e+05</code>, <code>e-10</code>, <code>e+308</code> , etc.). * * @param expArg exponent value to append */ private void appendExponent(int expArg) { int exp = expArg; int marker = result.length(); String e; // Deal with sign and leading-zero convention by explicit tests. if (exp < 0) { e = (exp <= -10) ? "e-" : "e-0"; exp = -exp; } else { e = (exp < 10) ? "e+0" : "e+"; } result.append(e).append(exp); lenMarker = 1; lenExponent = result.length() - marker - 1; } /** * Return the index in {@link #result} of the first letter. This is a helper for * {@link #uppercase()} and #getExponent() */ private int indexOfMarker() { return start + lenSign + lenWhole + lenPoint + lenFraction; } }
google/closure-templates
37,865
java/src/com/google/template/soy/idomsrc/GenIdomCodeVisitor.java
/* * Copyright 2015 Google Inc. * * 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.template.soy.idomsrc; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableMap.toImmutableMap; import static com.google.template.soy.idomsrc.IdomRuntime.INCREMENTAL_DOM; import static com.google.template.soy.idomsrc.IdomRuntime.INCREMENTAL_DOM_LIB_TYPE; import static com.google.template.soy.idomsrc.IdomRuntime.INCREMENTAL_DOM_PARAM_NAME; import static com.google.template.soy.idomsrc.IdomRuntime.SOY_IDOM; import static com.google.template.soy.idomsrc.IdomRuntime.SOY_IDOM_TYPE_ATTRIBUTE; import static com.google.template.soy.idomsrc.IdomRuntime.SOY_IDOM_TYPE_HTML; import static com.google.template.soy.idomsrc.IdomRuntime.STATE_PREFIX; import static com.google.template.soy.idomsrc.IdomRuntime.STATE_VAR_PREFIX; import static com.google.template.soy.jssrc.dsl.Expressions.EMPTY_OBJECT_LITERAL; import static com.google.template.soy.jssrc.dsl.Expressions.LITERAL_EMPTY_STRING; import static com.google.template.soy.jssrc.dsl.Expressions.dottedIdNoRequire; import static com.google.template.soy.jssrc.dsl.Expressions.id; import static com.google.template.soy.jssrc.dsl.Statements.returnValue; import static com.google.template.soy.jssrc.dsl.Whitespace.BLANK_LINE; import static com.google.template.soy.jssrc.internal.JsRuntime.ELEMENT_LIB_IDOM; import static com.google.template.soy.jssrc.internal.JsRuntime.GOOG_SOY_ALIAS; import static com.google.template.soy.jssrc.internal.JsRuntime.OPT_DATA; import static com.google.template.soy.soytree.SoyTreeUtils.isConstantExpr; import com.google.common.base.Ascii; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.template.soy.base.SourceLocation.ByteSpan; import com.google.template.soy.base.internal.SanitizedContentKind; import com.google.template.soy.jssrc.SoyJsSrcOptions; import com.google.template.soy.jssrc.dsl.ClassExpression; import com.google.template.soy.jssrc.dsl.ClassExpression.MethodDeclaration; import com.google.template.soy.jssrc.dsl.CodeChunk; import com.google.template.soy.jssrc.dsl.Expression; import com.google.template.soy.jssrc.dsl.Expressions; import com.google.template.soy.jssrc.dsl.GoogRequire; import com.google.template.soy.jssrc.dsl.Id; import com.google.template.soy.jssrc.dsl.JsCodeBuilder; import com.google.template.soy.jssrc.dsl.JsDoc; import com.google.template.soy.jssrc.dsl.Statement; import com.google.template.soy.jssrc.dsl.Statements; import com.google.template.soy.jssrc.dsl.VariableDeclaration; import com.google.template.soy.jssrc.internal.CanInitOutputVarVisitor; import com.google.template.soy.jssrc.internal.DelTemplateNamer; import com.google.template.soy.jssrc.internal.GenJsCodeVisitor; import com.google.template.soy.jssrc.internal.IsComputableAsJsExprsVisitor; import com.google.template.soy.jssrc.internal.JavaScriptValueFactoryImpl; import com.google.template.soy.jssrc.internal.JsRuntime; import com.google.template.soy.jssrc.internal.JsType; import com.google.template.soy.jssrc.internal.OutputVarHandler; import com.google.template.soy.jssrc.internal.StandardNames; import com.google.template.soy.jssrc.internal.TranslateExprNodeVisitor; import com.google.template.soy.passes.ShouldEnsureDataIsDefinedVisitor; import com.google.template.soy.soytree.ExternNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyTreeUtils; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateElementNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.defn.TemplateParam; import com.google.template.soy.soytree.defn.TemplateStateVar; import com.google.template.soy.types.SoyType; import com.google.template.soy.types.SoyTypeRegistry; import com.google.template.soy.types.TemplateType; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; /** * Generates a series of JavaScript control statements and function calls for rendering one or more * templates as HTML. This heavily leverages {@link GenJsCodeVisitor}, adding logic to print the * function calls and changing how statements are combined. */ public final class GenIdomCodeVisitor extends GenJsCodeVisitor { private static final String NAMESPACE_EXTENSION = ".incrementaldom"; private final Deque<SanitizedContentKind> contentKind; private boolean hasNonConstantState; private TemplateNode currentTemplateNode; GenIdomCodeVisitor( IdomVisitorsState state, SoyJsSrcOptions jsSrcOptions, JavaScriptValueFactoryImpl javaScriptValueFactory, DelTemplateNamer incrementalDomDelTemplateNamer, IsComputableAsJsExprsVisitor isComputableAsJsExprsVisitor, CanInitOutputVarVisitor canInitOutputVarVisitor, SoyTypeRegistry typeRegistry, OutputVarHandler outputVarHandler) { super( state, jsSrcOptions, javaScriptValueFactory, incrementalDomDelTemplateNamer, isComputableAsJsExprsVisitor, canInitOutputVarVisitor, typeRegistry, outputVarHandler); contentKind = new ArrayDeque<>(); } @Override protected JsType getJsTypeForParamForDeclaration(SoyType paramType) { return jsTypeRegistry.getWithDelegate(JsType.forIdomSrcDeclarations(), paramType); } @Override protected JsType getJsTypeForParam(SoyType paramType) { return jsTypeRegistry.getWithDelegate(JsType.forIdomSrc(), paramType); } @Override protected JsType getJsTypeForParamTypeCheck(SoyType paramType) { return jsTypeRegistry.getWithDelegate(JsType.forIdomSrcTypeChecks(), paramType); } @Override protected void visit(SoyNode node) { try { super.visit(node); } catch (RuntimeException e) { throw new AssertionError( "error from : " + node.getKind() + " @ " + node.getSourceLocation(), e); } } /** * Changes module namespaces, adding an extension of '.incrementaldom' to allow it to co-exist * with templates generated by jssrc. */ @Override protected String getGoogModuleNamespace(String soyNamespace) { return soyNamespace + NAMESPACE_EXTENSION; } @Override protected JsType getTemplateReturnType(TemplateNode node) { return JsType.templateReturnTypeForIdom(node.getContentKind()); } @Override protected void visitTemplateNode(TemplateNode node) { currentTemplateNode = node; contentKind.push(node.getContentKind()); visitTemplateNodeInternal(node); contentKind.pop(); currentTemplateNode = null; } @Override protected void visitExternNode(ExternNode node) { ((IdomVisitorsState) state).enterCall("unused", contentKind); contentKind.push(SanitizedContentKind.TEXT); super.visitExternNode(node); contentKind.pop(); ((IdomVisitorsState) state).exitCall(); } private void visitTemplateNodeInternal(TemplateNode node) { String alias; if (node instanceof TemplateDelegateNode) { alias = node.getPartialTemplateName(); } else { alias = templateAliases.get(node.getTemplateName()); } if (node instanceof TemplateElementNode) { hasNonConstantState = calcHasNonConstantState((TemplateElementNode) node); } super.visitTemplateNode(node); if ((node instanceof TemplateDelegateNode && node.getChildren().isEmpty())) { return; } SanitizedContentKind kind = node.getContentKind(); if (kind.isHtml() || kind == SanitizedContentKind.ATTRIBUTES) { Expression type; if (kind.isHtml()) { type = SOY_IDOM_TYPE_HTML; } else { type = SOY_IDOM_TYPE_ATTRIBUTE; } getJsCodeBuilder() .append( Statements.assign( id(alias) .castAs( "!" + ELEMENT_LIB_IDOM.alias() + ".IdomFunction", ImmutableSet.of(ELEMENT_LIB_IDOM)) .dotAccess("contentKind"), type)); if (isModifiable(node) && !node.getChildren().isEmpty()) { getJsCodeBuilder() .append( Statements.assign( id(alias + MODIFIABLE_DEFAULT_IMPL_SUFFIX) .castAs( "!" + ELEMENT_LIB_IDOM.alias() + ".IdomFunction", ImmutableSet.of(ELEMENT_LIB_IDOM)) .dotAccess("contentKind"), type)); } } if (node instanceof TemplateElementNode) { TemplateElementNode element = (TemplateElementNode) node; String elementName = this.getSoyElementClassName(alias); String elementAccessor = elementName + "Interface"; getJsCodeBuilder().append(BLANK_LINE); getJsCodeBuilder().append(generateAccessorInterface(elementAccessor, element)); getJsCodeBuilder().append(generateRenderInternal(element, alias)); getJsCodeBuilder().append(generateSyncInternal(element, alias)); getJsCodeBuilder().append(generateClassForSoyElement(elementName, element, alias)); } } private Statement generateRenderInternal(TemplateElementNode node, String alias) { String paramsType = hasOnlyImplicitParams(node) ? "null" : "!" + alias + ".Params"; JsDoc jsDoc = JsDoc.builder() .addParam(INCREMENTAL_DOM_PARAM_NAME, "!incrementaldomlib.IncrementalDomRenderer") .addParam(StandardNames.OPT_DATA, paramsType) .addAnnotation("public") .addAnnotation("override") .addParameterizedAnnotation("this", "exports." + getSoyElementClassName(alias)) .addParameterizedAnnotation("suppress", "checkTypes") .build(); // Build `renderInternal` method. try (var unused = templateTranslationContext.enterSoyAndJsScope()) { Expression fn = Expressions.function( jsDoc, // Various parts of the js codegen expects these values to be in the local // scope. Statements.of( VariableDeclaration.builder(StandardNames.DOLLAR_IJDATA) .setRhs(Expressions.THIS.dotAccess("ijData")) .build(), Statements.of( node.getStateVars().stream() .map( stateVar -> VariableDeclaration.builder( STATE_VAR_PREFIX + STATE_PREFIX + stateVar.name()) .setRhs(getStateVarWithCasts(stateVar)) .build()) .collect(toImmutableList())), generateIncrementalDomRenderCalls(node, alias, /* isPositionalStyle= */ false))); return VariableDeclaration.builder("$" + getSoyElementClassName(alias) + "Render") .setJsDoc(jsDoc) .setRhs(fn) .build(); } } private Statement generateInitInternal(TemplateElementNode node) { ImmutableList.Builder<Statement> stateVarInitializations = ImmutableList.builder(); JsCodeBuilder jsCodeBuilder = getJsCodeBuilder(); for (TemplateStateVar stateVar : node.getStateVars()) { JsType jsType = jsTypeRegistry.getWithDelegate(JsType.forIdomSrcState(), stateVar.authoredType()); for (GoogRequire require : jsType.googRequires()) { jsCodeBuilder.addGoogRequire(require); } Expression rhsValue; if (isConstantExpr(stateVar.defaultValue())) { rhsValue = translateExpr(stateVar.defaultValue()); if (!rhsValue.hasOuterCast()) { rhsValue = rhsValue.castAs(jsType.typeExpr(), jsType.googRequires()); } } else { rhsValue = Expressions.LITERAL_UNDEFINED.castAsUnknown(); } JsDoc stateVarJsdoc = JsDoc.builder().addParameterizedAnnotation("private", jsType.typeExpr()).build(); stateVarInitializations.add( Statements.assign( Expressions.THIS.dotAccess(STATE_PREFIX + stateVar.name()), rhsValue, stateVarJsdoc)); } return Statements.of(stateVarInitializations.build()); } private Statement generateSyncInternal(TemplateElementNode node, String alias) { String paramsType = hasOnlyImplicitParams(node) ? "null" : "!" + alias + ".Params"; JsDoc jsDoc = JsDoc.builder() .addParam(StandardNames.OPT_DATA, paramsType) .addAnnotation("public") .addAnnotation("override") .addParameterizedAnnotation("this", "exports." + getSoyElementClassName(alias)) .addParameterizedAnnotation("suppress", "checkTypes") .addParam("syncOnlyData", "boolean=") .build(); try (var exitScope = templateTranslationContext.enterSoyAndJsScope()) { return VariableDeclaration.builder("$" + this.getSoyElementClassName(alias) + "SyncInternal") .setJsDoc(jsDoc) .setRhs( Expressions.function( jsDoc, Statements.of( // Various parts of the js codegen expects these parameters to be in the local // scope. VariableDeclaration.builder(StandardNames.DOLLAR_IJDATA) .setRhs(Expressions.THIS.dotAccess("ijData")) .build(), genSyncStateCalls(node, alias)))) .build(); } } @Override protected JsDoc generatePositionalFunctionJsDoc(TemplateNode node, boolean addVariantParam) { JsDoc.Builder jsDocBuilder = JsDoc.builder(); addInternalCallerParam(jsDocBuilder); addIjDataParam(jsDocBuilder, /* forPositionalSignature= */ true); maybeAddRenderer(jsDocBuilder, node); for (TemplateParam param : paramsInOrder(node)) { JsType jsType = getJsTypeForParamForDeclaration(param.authoredType()); jsDocBuilder.addParam( GenJsCodeVisitor.getPositionalParamName(param), jsType.typeExpr() + (param.isRequired() ? "" : "=")); } if (addVariantParam) { jsDocBuilder.addParam(StandardNames.OPT_VARIANT, "string="); } addReturnTypeAndAnnotations(node, jsDocBuilder); // TODO(b/11787791): make the checkTypes suppression more fine grained. jsDocBuilder.addParameterizedAnnotation("suppress", "checkTypes"); return jsDocBuilder.build(); } @Override protected JsDoc generateEmptyFunctionJsDoc(TemplateNode node) { JsDoc.Builder jsDocBuilder = JsDoc.builder(); String ijDataTypeExpression = ijDataTypeExpression(jsDocBuilder); jsDocBuilder.addAnnotation( "type", String.format("{function(?Object<string, *>=, ?%s=):string}", ijDataTypeExpression)); jsDocBuilder.addParameterizedAnnotation("suppress", "checkTypes"); return jsDocBuilder.build(); } @Override protected JsDoc generateFunctionJsDoc( TemplateNode node, String alias, boolean suppressCheckTypes, boolean addVariantParam) { JsDoc.Builder jsDocBuilder = JsDoc.builder(); maybeAddRenderer(jsDocBuilder, node); // This is true if there are any calls with data="all" (which implicitly add optional parameters // from those template) or if all parameters are optional (but there are some parameters). boolean noRequiredParams = new ShouldEnsureDataIsDefinedVisitor().exec(node); if (hasOnlyImplicitParams(node)) { // If there are indirect parameters, allow an arbitrary object. // Either way, allow null, since the caller may not pass parameters. jsDocBuilder.addParam( StandardNames.OPT_DATA, noRequiredParams ? "?Object<string, *>=" : "null="); } else if (noRequiredParams) { // All parameters are optional or only owned by an indirect callee; caller doesn't need to // pass an object. jsDocBuilder.addParam(StandardNames.OPT_DATA, "?" + alias + ".Params="); } else { jsDocBuilder.addParam(StandardNames.OPT_DATA, "!" + alias + ".Params"); } addIjDataParam(jsDocBuilder, /* forPositionalSignature= */ false); if (addVariantParam) { jsDocBuilder.addParam(StandardNames.OPT_VARIANT, "string="); } addReturnTypeAndAnnotations(node, jsDocBuilder); if (suppressCheckTypes) { // TODO(b/11787791): make the checkTypes suppression more fine grained. jsDocBuilder.addParameterizedAnnotation("suppress", "checkTypes"); } else { if (fileSetMetadata .getTemplate(node.getTemplateName()) .getTemplateType() .getActualParameters() .stream() .anyMatch(TemplateType.Parameter::isImplicit)) { jsDocBuilder.addParameterizedAnnotation("suppress", "missingProperties"); } } return jsDocBuilder.build(); } private static void maybeAddRenderer(JsDoc.Builder jsDocBuilder, TemplateNode node) { SanitizedContentKind kind = node.getContentKind(); if (kind.isHtml() || kind == SanitizedContentKind.ATTRIBUTES) { jsDocBuilder.addGoogRequire(INCREMENTAL_DOM_LIB_TYPE); jsDocBuilder.addParam( INCREMENTAL_DOM_PARAM_NAME, "!incrementaldomlib.IncrementalDomRenderer"); } } /** Returns the simple type of IjData, adding requires as necessary. */ @Override protected String ijDataTypeExpression(JsDoc.Builder jsDocBuilder) { jsDocBuilder.addGoogRequire(GOOG_SOY_ALIAS); return GOOG_SOY_ALIAS.alias() + ".IjData"; } @Override protected void addIjDataParam(JsDoc.Builder jsDocBuilder, boolean forPositionalSignature) { String ijDataTypeExpression = ijDataTypeExpression(jsDocBuilder); if (forPositionalSignature) { jsDocBuilder.addParam(StandardNames.DOLLAR_IJDATA, "!" + ijDataTypeExpression); } else { jsDocBuilder.addParam(StandardNames.OPT_IJDATA, "?" + ijDataTypeExpression + "="); } } /** Return the parameters always present in positional calls. */ @Override protected ImmutableList<Expression> getFixedParamsToPositionalCall(TemplateNode node) { SanitizedContentKind kind = node.getContentKind(); ImmutableList.Builder<Expression> params = ImmutableList.builder(); params.addAll(super.getFixedParamsToPositionalCall(node)); if (kind.isHtml() || kind == SanitizedContentKind.ATTRIBUTES) { params.add(id(INCREMENTAL_DOM_PARAM_NAME)); } return params.build(); } /** Return the parameters always present in non-positional calls. */ @Override protected ImmutableList<Expression> getFixedParamsForNonPositionalCall(TemplateNode node) { SanitizedContentKind kind = node.getContentKind(); ImmutableList.Builder<Expression> params = ImmutableList.builder(); if (kind.isHtml() || kind == SanitizedContentKind.ATTRIBUTES) { params.add(id(INCREMENTAL_DOM_PARAM_NAME)); } params.addAll(super.getFixedParamsForNonPositionalCall(node)); return params.build(); } @Override protected ImmutableList<Expression> templateArguments( TemplateNode node, boolean isPositionalStyle) { ImmutableList<Expression> arguments = super.templateArguments(node, isPositionalStyle); SanitizedContentKind kind = node.getContentKind(); if (kind.isHtml() || kind == SanitizedContentKind.ATTRIBUTES) { return ImmutableList.<Expression>builder().add(INCREMENTAL_DOM).addAll(arguments).build(); } return arguments; } @Override protected Statement generateFunctionBody( TemplateNode node, String alias, @Nullable String objectParamName, boolean addStubMapLogic) { ImmutableList.Builder<Statement> bodyStatements = ImmutableList.builder(); boolean isPositionalStyle = objectParamName == null; if (!isPositionalStyle) { bodyStatements.add(redeclareIjData(node)); } else { bodyStatements.add( JsRuntime.SOY_ARE_YOU_AN_INTERNAL_CALLER .call(id(StandardNames.ARE_YOU_AN_INTERNAL_CALLER)) .asStatement()); } if (addStubMapLogic) { bodyStatements.add(generateStubbingTest(node, alias, isPositionalStyle)); } // Generate statement to ensure data is defined, if necessary. if (!isPositionalStyle && new ShouldEnsureDataIsDefinedVisitor().exec(node)) { bodyStatements.add( Statements.assign( OPT_DATA, OPT_DATA.or( EMPTY_OBJECT_LITERAL.castAsNoRequire(objectParamName), templateTranslationContext.codeGenerator()))); } if (isPositionalStyle && node instanceof TemplateElementNode) { throw new IllegalStateException("elements cannot be compiled into positional style."); } bodyStatements.add( node instanceof TemplateElementNode ? this.generateFunctionBodyForSoyElement((TemplateElementNode) node, alias) : this.generateIncrementalDomRenderCalls(node, alias, isPositionalStyle)); return Statements.of(bodyStatements.build()); } private boolean calcHasNonConstantState(TemplateElementNode node) { return node.getStateVars().stream().anyMatch(v -> !isConstantExpr(v.defaultValue())); } private Statement genSyncStateCalls(TemplateElementNode node, String alias) { Statement typeChecks = genParamTypeChecks(node, alias, false); ImmutableList<TemplateStateVar> headerVars = node.getStateVars(); ImmutableMap<TemplateStateVar, Boolean> isNonConst = headerVars.stream().collect(toImmutableMap(v -> v, v -> !isConstantExpr(v.defaultValue()))); ImmutableList.Builder<Statement> stateReassignmentBuilder = ImmutableList.builder(); TemplateStateVar lastNonConstVar = headerVars.reverse().stream().filter(isNonConst::get).findFirst().orElse(null); boolean haveVisitedLastNonConstVar = lastNonConstVar == null; String prefix = STATE_PREFIX; for (TemplateStateVar headerVar : headerVars) { if (isNonConst.get(headerVar)) { stateReassignmentBuilder.add( Statements.assign( Expressions.THIS.dotAccess(prefix + headerVar.name()), translateExpr(headerVar.defaultValue()))); } haveVisitedLastNonConstVar = haveVisitedLastNonConstVar || headerVar.equals(lastNonConstVar); // Only need to alias if there's another non-constant var to come that may reference this. if (!haveVisitedLastNonConstVar) { stateReassignmentBuilder.add( VariableDeclaration.builder(STATE_VAR_PREFIX + STATE_PREFIX + headerVar.name()) .setRhs(Expressions.THIS.dotAccess(prefix + headerVar.name())) .build()); } } ImmutableList<Statement> assignments = stateReassignmentBuilder.build(); Statement stateReassignments = Statements.of(assignments); return Statements.of(typeChecks, stateReassignments); } /** Generates idom#elementOpen, idom#elementClose, etc. function calls for the given node. */ private Statement generateIncrementalDomRenderCalls( TemplateNode node, String alias, boolean isPositionalStyle) { boolean isTextTemplate = isTextContent(node.getContentKind()); Statement typeChecks = genParamTypeChecks(node, alias, isPositionalStyle); // Note: we do not try to combine this into a single return statement if the content is // computable as a JsExpr. A JavaScript compiler, such as Closure Compiler, is able to perform // the transformation. if (isTextTemplate) { // We do our own initialization below, so mark it as such. outputVars.pushOutputVar("output"); outputVars.setOutputVarInited(); } ((IdomVisitorsState) state).enterCall(alias, contentKind); GenIdomTemplateBodyVisitor visitor = (GenIdomTemplateBodyVisitor) state.createTemplateBodyVisitor(genJsExprsVisitor); Statement body = Statements.of(visitor.visitChildren(node)); staticVarDeclarations.addAll(visitor.getStaticVarDeclarations()); ((IdomVisitorsState) state).exitCall(); if (isTextTemplate) { VariableDeclaration declare = VariableDeclaration.builder("output").setMutable().setRhs(LITERAL_EMPTY_STRING).build(); outputVars.popOutputVar(); body = Statements.of(declare, body, returnValue(sanitize(declare.ref(), node.getContentKind()))); } return Statements.of(typeChecks, body); } /** * Generates main template function body for Soy elements. Specifically, generates code to create * a new instance of the element class and invoke its #render method. */ private Statement generateFunctionBodyForSoyElement(TemplateElementNode node, String alias) { String tplName = node.getHtmlElementMetadata().getFinalCallee().isEmpty() ? node.getTemplateName() : node.getHtmlElementMetadata().getFinalCallee(); Expression firstElementKey = // Since Soy element roots cannot have manual keys (see go/soy-element-keyed-roots), // this will always be the first element key. JsRuntime.XID.call(Expressions.stringLiteral(tplName + "-root")); List<Expression> params = Arrays.asList( dottedIdNoRequire("exports." + getSoyElementClassName(alias)), firstElementKey, Expressions.stringLiteral(node.getHtmlElementMetadata().getTag()), OPT_DATA, JsRuntime.IJ_DATA, id("$" + this.getSoyElementClassName(alias) + "Render")); return Statements.of(INCREMENTAL_DOM.dotAccess("handleSoyElement").call(params).asStatement()); } /** Generates class expression for the given template node, provided it is a Soy element. */ private CodeChunk generateClassForSoyElement( String soyElementClassName, TemplateElementNode node, String alias) { String paramsType = hasOnlyImplicitParams(node) ? "null" : "!" + alias + ".Params"; ByteSpan byteSpan = SoyTreeUtils.getByteSpan( currentTemplateNode, currentTemplateNode.getTemplateNameLocation()); ClassExpression.Builder classBuilder = ClassExpression.builder() .setBaseClass(SOY_IDOM.dotAccess("$SoyElement")) .setName(Id.create(soyElementClassName)); try (var unused = templateTranslationContext.enterSoyAndJsScope()) { ImmutableList.Builder<Statement> stateVarInitializations = ImmutableList.builder(); stateVarInitializations.add(generateInitInternal(node)); if (hasNonConstantState) { stateVarInitializations.add( Statements.assign( Expressions.THIS.dotAccess("syncStateFromData"), id("$" + soyElementClassName + "SyncInternal"))); } // Build constructor method. Statement ctorBody = Statements.of( id("super").call().asStatement(), Statements.of(stateVarInitializations.build())); MethodDeclaration constructorMethod = MethodDeclaration.builder(Id.builder("constructor").setSpan(byteSpan).build(), ctorBody) .build(); classBuilder.addMethod(constructorMethod); } for (TemplateStateVar stateVar : node.getStateVars()) { for (MethodDeclaration m : generateStateMethodsForSoyElementClass("exports." + soyElementClassName, stateVar)) { classBuilder.addMethod(m); } } for (TemplateParam param : node.getParams()) { if (param.isImplicit()) { continue; } classBuilder.addMethod( this.generateGetParamMethodForSoyElementClass( param, /* isAbstract= */ false, /* isInjected= */ false)); } for (TemplateParam injectedParam : node.getInjectedParams()) { classBuilder.addMethod( this.generateGetParamMethodForSoyElementClass( injectedParam, /* isAbstract= */ false, /* isInjected= */ true)); } ClassExpression soyElementClass = classBuilder.build(); String elementAccessor = "exports." + soyElementClassName + "Interface"; return Statements.assign( exportWithSpan(soyElementClassName, byteSpan), soyElementClass, JsDoc.builder() .addAnnotation( "extends", "{soyIdom.$SoyElement<" + paramsType + ",!" + elementAccessor + ">}") .addParameterizedAnnotation("implements", elementAccessor) .build()); } /** Generates class expression for the given template node, provided it is a Soy element. */ private CodeChunk generateAccessorInterface(String className, TemplateElementNode node) { ClassExpression.Builder classBuilder = ClassExpression.builder(); for (TemplateParam param : node.getParams()) { if (param.isImplicit()) { continue; } classBuilder.addMethod( this.generateGetParamMethodForSoyElementClass( param, /* isAbstract= */ true, /* isInjected= */ false)); } for (TemplateParam injectedParam : node.getInjectedParams()) { classBuilder.addMethod( this.generateGetParamMethodForSoyElementClass( injectedParam, /* isAbstract= */ true, /* isInjected= */ true)); } ByteSpan byteSpan = SoyTreeUtils.getByteSpan(node, node.getTemplateNameLocation()); return Statements.assign( exportWithSpan(className, byteSpan), classBuilder.build(), JsDoc.builder().addAnnotation("interface").build()); } private static Expression exportWithSpan(String symbol, ByteSpan byteSpan) { return JsRuntime.EXPORTS.dotAccess(Id.builder(symbol).setSpan(byteSpan).build()); } /** * Generates `getFoo` (index 0) and `setFoo` (index 1) methods for a given `foo` state variable. */ private ImmutableList<MethodDeclaration> generateStateMethodsForSoyElementClass( String soyElementClassName, TemplateStateVar stateVar) { ImmutableList.Builder<MethodDeclaration> methods = ImmutableList.builder(); ByteSpan byteSpan = SoyTreeUtils.getByteSpan(currentTemplateNode, stateVar.nameLocation()); JsType typeForState = jsTypeRegistry.getWithDelegate(JsType.forIdomSrcDeclarations(), stateVar.authoredType()); JsType typeForGetters = jsTypeRegistry.getWithDelegate(JsType.forIdomSrcGetters(), stateVar.authoredType()); String stateAccessorSuffix = Ascii.toUpperCase(stateVar.name().substring(0, 1)) + stateVar.name().substring(1); try (var unused = templateTranslationContext.enterSoyAndJsScope()) { // Generate getters. Expression getterStateValue = maybeCastAs( id("this").dotAccess(STATE_PREFIX + stateVar.name()), typeForState, typeForGetters); methods.add( MethodDeclaration.builder( Id.builder("get" + stateAccessorSuffix).setSpan(byteSpan).build(), Statements.returnValue(getterStateValue)) .setJsDoc( JsDoc.builder() .addParameterizedAnnotation("return", typeForGetters.typeExpr()) .build()) .build()); } // Generate setters. try (var unused = templateTranslationContext.enterSoyAndJsScope()) { ImmutableList.Builder<Statement> setStateMethodStatements = ImmutableList.builder(); JsType typeForSetters = jsTypeRegistry.getWithDelegate(JsType.forIdomSrcSetters(), stateVar.authoredType()); Optional<Expression> typeAssertion = typeForSetters.getSoyParamTypeAssertion( id(stateVar.name()), stateVar.name(), /* paramKind= */ "@state", templateTranslationContext.codeGenerator()); if (typeAssertion.isPresent()) { setStateMethodStatements.add(typeAssertion.get().asStatement()); } Expression setterStateValue = id("this").dotAccess(STATE_PREFIX + stateVar.name()); // TODO(b/230911572): remove this cast when types are always aligned. Expression setterParam = maybeCastAs(id(stateVar.name()), typeForSetters, typeForState); setStateMethodStatements.add( setterStateValue.assign(setterParam).asStatement(), Statements.returnValue(id("this"))); methods.add( MethodDeclaration.builder( Id.builder("set" + stateAccessorSuffix).setSpan(byteSpan).build(), Statements.of(setStateMethodStatements.build())) .setJsDoc( JsDoc.builder() .addParam(stateVar.name(), typeForSetters.typeExpr()) .addParameterizedAnnotation("return", "!" + soyElementClassName) .build()) .build()); } return methods.build(); } /** Generates `get[X]` for a given parameter value. */ private MethodDeclaration generateGetParamMethodForSoyElementClass( TemplateParam param, boolean isAbstract, boolean isInjected) { JsType jsType = jsTypeRegistry.getWithDelegate(JsType.forIdomSrcGetters(), param.authoredType()); String accessorSuffix = Ascii.toUpperCase(param.name().substring(0, 1)) + param.name().substring(1); ByteSpan byteSpan = SoyTreeUtils.getByteSpan(currentTemplateNode, param.nameLocation()); if (isAbstract) { return MethodDeclaration.builder( Id.builder("get" + accessorSuffix).setSpan(byteSpan).build(), Statements.of(ImmutableList.of())) .setJsDoc( JsDoc.builder() .addAnnotation("abstract") // Injected params are marked as optional, see: .addParameterizedAnnotation("return", jsType.typeExpr()) .build()) .build(); } try (var unused = templateTranslationContext.enterSoyAndJsScope()) { // TODO(b/230911572): remove this cast when types are always aligned. Expression value = maybeCastAs( id("this").dotAccess(isInjected ? "ijData" : "data").dotAccess(param.name()), jsTypeRegistry.getWithDelegate(JsType.forIdomSrcState(), param.authoredType()), jsType); if (param.hasDefault()) { value = templateTranslationContext .codeGenerator() .declarationBuilder() .setMutable() .setRhs(value) .build() .ref(); value = value.withInitialStatement( genParamDefault(param, value, jsType, templateTranslationContext.codeGenerator())); } // Injected params are marked as optional to account for unused templates, see: // We can assert the presence of the injected param if it being called. Optional<Expression> typeAssertion = isInjected ? jsType.getSoyParamTypeAssertion( value, param.name(), /* paramKind= */ "@inject", templateTranslationContext.codeGenerator()) : Optional.empty(); return MethodDeclaration.builder( Id.builder("get" + accessorSuffix).setSpan(byteSpan).build(), Statements.returnValue(typeAssertion.orElse(value))) .setJsDoc(JsDoc.builder().addAnnotation("override").addAnnotation("public").build()) .build(); } } /** Constructs template class name, e.g. converts template `ns.foo` => `$FooElement`. */ private String getSoyElementClassName(String alias) { Preconditions.checkState( alias.startsWith("$"), "Alias should start with '$', or template class name may be malformed."); // `alias` has '$' as the 0th char, so capitalize the 1st char. return Ascii.toUpperCase(alias.charAt(1)) /// ...and concat the rest of the alias. + alias.substring(2) + "Element"; } /** * Determines if a given type of content represents text or some sort of HTML. * * @param contentKind The kind of content to check. * @return True if the content represents text, false otherwise. */ private static boolean isTextContent(SanitizedContentKind contentKind) { return !contentKind.isHtml() && contentKind != SanitizedContentKind.ATTRIBUTES; } private Expression getStateVarWithCasts(TemplateStateVar stateVar) { // Access the state variable and cast if the declared type is // different from what we would expect it to be inline in a template, // as described in the -TypeChecks accessors. SoyType stateVarType = stateVar.typeOrDefault(null); return maybeCastAs( Expressions.THIS.dotAccess(STATE_PREFIX + stateVar.name()), jsTypeRegistry.getWithDelegate(JsType.forIdomSrcState(), stateVarType), jsTypeRegistry.getWithDelegate(JsType.forIdomSrcTypeChecks(), stateVarType)); } private static Expression maybeCastAs( Expression expression, JsType currentType, JsType desiredType) { if (!currentType.typeExpr().equals(desiredType.typeExpr())) { expression = expression.castAs(desiredType.typeExpr(), desiredType.googRequires()); } return expression; } @Override protected TranslateExprNodeVisitor getExprTranslator() { return state.createTranslateExprNodeVisitor(); } @Override protected boolean isIncrementalDom() { return true; } }
apache/felix-dev
37,688
bundlerepository/src/main/java/org/apache/felix/bundlerepository/impl/DataModelHelperImpl.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.bundlerepository.impl; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Dictionary; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.felix.bundlerepository.Capability; import org.apache.felix.bundlerepository.DataModelHelper; import org.apache.felix.bundlerepository.Property; import org.apache.felix.bundlerepository.Repository; import org.apache.felix.bundlerepository.Requirement; import org.apache.felix.bundlerepository.Resource; import org.apache.felix.utils.filter.FilterImpl; import org.apache.felix.utils.manifest.Attribute; import org.apache.felix.utils.manifest.Clause; import org.apache.felix.utils.manifest.Directive; import org.apache.felix.utils.manifest.Parser; import org.apache.felix.utils.version.VersionCleaner; import org.apache.felix.utils.version.VersionRange; import org.osgi.framework.Bundle; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.Version; public class DataModelHelperImpl implements DataModelHelper { public static final String BUNDLE_LICENSE = "Bundle-License"; public static final String BUNDLE_SOURCE = "Bundle-Source"; public Requirement requirement(String name, String filter) { RequirementImpl req = new RequirementImpl(); req.setName(name); if (filter != null) { req.setFilter(filter); } return req; } public Filter filter(String filter) { try { return FilterImpl.newInstance(filter); } catch (InvalidSyntaxException e) { IllegalArgumentException ex = new IllegalArgumentException(); ex.initCause(e); throw ex; } } public Repository repository(final URL url) throws Exception { InputStream is = null; try { if (url.getPath().endsWith(".zip")) { ZipInputStream zin = new ZipInputStream(FileUtil.openURL(url)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { if (entry.getName().equals("repository.xml") || entry.getName().equals("index.xml")) { is = zin; break; } entry = zin.getNextEntry(); } // as the ZipInputStream is not used further it would not be closed. if (is == null) { try { zin.close(); } catch (IOException ex) { // Not much we can do. } } } else if (url.getPath().endsWith(".gz")) { is = new GZIPInputStream(FileUtil.openURL(url)); } else { is = FileUtil.openURL(url); } if (is != null) { String repositoryUri = url.toExternalForm(); String baseUri; if (repositoryUri.endsWith(".zip")) { baseUri = new StringBuilder("jar:").append(repositoryUri).append("!/").toString(); } else if (repositoryUri.endsWith(".xml")) { baseUri = repositoryUri.substring(0, repositoryUri.lastIndexOf('/') + 1); } else { baseUri = repositoryUri; } RepositoryImpl repository = repository(is, URI.create(baseUri)); repository.setURI(repositoryUri); return repository; } else { // This should not happen. throw new Exception("Unable to get input stream for repository."); } } finally { try { if (is != null) { is.close(); } } catch (IOException ex) { // Not much we can do. } } } public RepositoryImpl repository(InputStream is, URI baseURI) throws Exception { RepositoryParser parser = RepositoryParser.getParser(); RepositoryImpl repository = parser.parseRepository(is, baseURI); return repository; } public Repository repository(Resource[] resources) { return new RepositoryImpl(resources); } public Capability capability(String name, Map properties) { CapabilityImpl cap = new CapabilityImpl(name); for (Iterator it = properties.entrySet().iterator(); it.hasNext();) { Map.Entry e = (Map.Entry) it.next(); cap.addProperty((String) e.getKey(), (String) e.getValue()); } return cap; } public String writeRepository(Repository repository) { try { StringWriter sw = new StringWriter(); writeRepository(repository, sw); return sw.toString(); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public void writeRepository(Repository repository, Writer writer) throws IOException { XmlWriter w = new XmlWriter(writer); toXml(w, repository); } public String writeResource(Resource resource) { try { StringWriter sw = new StringWriter(); writeResource(resource, sw); return sw.toString(); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public void writeResource(Resource resource, Writer writer) throws IOException { XmlWriter w = new XmlWriter(writer); toXml(w, resource); } public String writeCapability(Capability capability) { try { StringWriter sw = new StringWriter(); writeCapability(capability, sw); return sw.toString(); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public void writeCapability(Capability capability, Writer writer) throws IOException { XmlWriter w = new XmlWriter(writer); toXml(w, capability); } public String writeRequirement(Requirement requirement) { try { StringWriter sw = new StringWriter(); writeRequirement(requirement, sw); return sw.toString(); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public void writeRequirement(Requirement requirement, Writer writer) throws IOException { XmlWriter w = new XmlWriter(writer); toXml(w, requirement); } public String writeProperty(Property property) { try { StringWriter sw = new StringWriter(); writeProperty(property, sw); return sw.toString(); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public void writeProperty(Property property, Writer writer) throws IOException { XmlWriter w = new XmlWriter(writer); toXml(w, property); } private static void toXml(XmlWriter w, Repository repository) throws IOException { SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss.SSS"); w.element(RepositoryParser.REPOSITORY) .attribute(RepositoryParser.NAME, repository.getName()) .attribute(RepositoryParser.LASTMODIFIED, format.format(new Date(repository.getLastModified()))); if (repository instanceof RepositoryImpl) { Referral[] referrals = ((RepositoryImpl) repository).getReferrals(); for (int i = 0; referrals != null && i < referrals.length; i++) { w.element(RepositoryParser.REFERRAL) .attribute(RepositoryParser.DEPTH, new Integer(referrals[i].getDepth())) .attribute(RepositoryParser.URL, referrals[i].getUrl()) .end(); } } Resource[] resources = repository.getResources(); for (int i = 0; resources != null && i < resources.length; i++) { toXml(w, resources[i]); } w.end(); } private static void toXml(XmlWriter w, Resource resource) throws IOException { w.element(RepositoryParser.RESOURCE) .attribute(Resource.ID, resource.getId()) .attribute(Resource.SYMBOLIC_NAME, resource.getSymbolicName()) .attribute(Resource.PRESENTATION_NAME, resource.getPresentationName()) .attribute(Resource.URI, getRelativeUri(resource, Resource.URI)) .attribute(Resource.VERSION, resource.getVersion().toString()); w.textElement(Resource.DESCRIPTION, resource.getProperties().get(Resource.DESCRIPTION)) .textElement(Resource.SIZE, resource.getProperties().get(Resource.SIZE)) .textElement(Resource.DOCUMENTATION_URI, getRelativeUri(resource, Resource.DOCUMENTATION_URI)) .textElement(Resource.SOURCE_URI, getRelativeUri(resource, Resource.SOURCE_URI)) .textElement(Resource.JAVADOC_URI, getRelativeUri(resource, Resource.JAVADOC_URI)) .textElement(Resource.LICENSE_URI, getRelativeUri(resource, Resource.LICENSE_URI)); String[] categories = resource.getCategories(); for (int i = 0; categories != null && i < categories.length; i++) { w.element(RepositoryParser.CATEGORY) .attribute(RepositoryParser.ID, categories[i]) .end(); } Capability[] capabilities = resource.getCapabilities(); for (int i = 0; capabilities != null && i < capabilities.length; i++) { toXml(w, capabilities[i]); } Requirement[] requirements = resource.getRequirements(); for (int i = 0; requirements != null && i < requirements.length; i++) { toXml(w, requirements[i]); } w.end(); } private static String getRelativeUri(Resource resource, String name) { String uri = (String) resource.getProperties().get(name); if (resource instanceof ResourceImpl) { try { uri = URI.create(((ResourceImpl) resource).getRepository().getURI()).relativize(URI.create(uri)).toASCIIString(); } catch (Throwable t) { } } return uri; } private static void toXml(XmlWriter w, Capability capability) throws IOException { w.element(RepositoryParser.CAPABILITY) .attribute(RepositoryParser.NAME, capability.getName()); Property[] props = capability.getProperties(); for (int j = 0; props != null && j < props.length; j++) { toXml(w, props[j]); } w.end(); } private static void toXml(XmlWriter w, Property property) throws IOException { w.element(RepositoryParser.P) .attribute(RepositoryParser.N, property.getName()) .attribute(RepositoryParser.T, property.getType()) .attribute(RepositoryParser.V, property.getValue()) .end(); } private static void toXml(XmlWriter w, Requirement requirement) throws IOException { w.element(RepositoryParser.REQUIRE) .attribute(RepositoryParser.NAME, requirement.getName()) .attribute(RepositoryParser.FILTER, requirement.getFilter()) .attribute(RepositoryParser.EXTEND, Boolean.toString(requirement.isExtend())) .attribute(RepositoryParser.MULTIPLE, Boolean.toString(requirement.isMultiple())) .attribute(RepositoryParser.OPTIONAL, Boolean.toString(requirement.isOptional())) .text(requirement.getComment().trim()) .end(); } public Resource createResource(final Bundle bundle) { final Dictionary dict = bundle.getHeaders(); return createResource(new Headers() { public String getHeader(String name) { return (String) dict.get(name); } }); } public Resource createResource(final URL bundleUrl) throws IOException { ResourceImpl resource = createResource(new Headers() { private final Manifest manifest; private Properties localization; { // Do not use a JarInputStream so that we can read the manifest even if it's not // the first entry in the JAR. byte[] man = loadEntry(JarFile.MANIFEST_NAME); if (man == null) { throw new IllegalArgumentException("The specified url is not a valid jar (can't read manifest): " + bundleUrl); } manifest = new Manifest(new ByteArrayInputStream(man)); } public String getHeader(String name) { String value = manifest.getMainAttributes().getValue(name); if (value != null && value.startsWith("%")) { if (localization == null) { try { localization = new Properties(); String path = manifest.getMainAttributes().getValue(Constants.BUNDLE_LOCALIZATION); if (path == null) { path = Constants.BUNDLE_LOCALIZATION_DEFAULT_BASENAME; } path += ".properties"; byte[] loc = loadEntry(path); if (loc != null) { localization.load(new ByteArrayInputStream(loc)); } } catch (IOException e) { // TODO: ? } } value = value.substring(1); value = localization.getProperty(value, value); } return value; } private byte[] loadEntry(String name) throws IOException { ZipInputStream zis = new ZipInputStream(FileUtil.openURL(bundleUrl)); try { for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) { if (name.equalsIgnoreCase(e.getName())) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n; while ((n = zis.read(buf, 0, buf.length)) > 0) { baos.write(buf, 0, n); } return baos.toByteArray(); } } } finally { zis.close(); } return null; } }); if (resource != null) { if ("file".equals(bundleUrl.getProtocol())) { try { File f = new File(bundleUrl.toURI()); resource.put(Resource.SIZE, Long.toString(f.length()), null); } catch (URISyntaxException e) { throw new RuntimeException(e); } } resource.put(Resource.URI, bundleUrl.toExternalForm(), null); } return resource; } public Resource createResource(final Attributes attributes) { return createResource(new Headers() { public String getHeader(String name) { return attributes.getValue(name); } }); } public ResourceImpl createResource(Headers headers) { String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); if (bsn == null) { return null; } ResourceImpl resource = new ResourceImpl(); populate(headers, resource); return resource; } static void populate(Headers headers, ResourceImpl resource) { String bsn = getSymbolicName(headers); String v = getVersion(headers); resource.put(Resource.ID, bsn + "/" + v); resource.put(Resource.SYMBOLIC_NAME, bsn); resource.put(Resource.VERSION, v); if (headers.getHeader(Constants.BUNDLE_NAME) != null) { resource.put(Resource.PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); } if (headers.getHeader(Constants.BUNDLE_DESCRIPTION) != null) { resource.put(Resource.DESCRIPTION, headers.getHeader(Constants.BUNDLE_DESCRIPTION)); } if (headers.getHeader(BUNDLE_LICENSE) != null) { resource.put(Resource.LICENSE_URI, headers.getHeader(BUNDLE_LICENSE)); } if (headers.getHeader(Constants.BUNDLE_COPYRIGHT) != null) { resource.put(Resource.COPYRIGHT, headers.getHeader(Constants.BUNDLE_COPYRIGHT)); } if (headers.getHeader(Constants.BUNDLE_DOCURL) != null) { resource.put(Resource.DOCUMENTATION_URI, headers.getHeader(Constants.BUNDLE_DOCURL)); } if (headers.getHeader(BUNDLE_SOURCE) != null) { resource.put(Resource.SOURCE_URI, headers.getHeader(BUNDLE_SOURCE)); } doCategories(resource, headers); doBundle(resource, headers); doImportExportServices(resource, headers); doFragment(resource, headers); doRequires(resource, headers); doExports(resource, headers); doImports(resource, headers); doExecutionEnvironment(resource, headers); doProvides(resource, headers); } private static void doCategories(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_CATEGORY)); for (int i = 0; clauses != null && i < clauses.length; i++) { resource.addCategory(clauses[i].getName()); } } private static void doImportExportServices(ResourceImpl resource, Headers headers) { Clause[] imports = Parser.parseHeader(headers.getHeader(Constants.IMPORT_SERVICE)); for (int i = 0; imports != null && i < imports.length; i++) { RequirementImpl ri = new RequirementImpl(Capability.SERVICE); ri.setFilter(createServiceFilter(imports[i])); ri.addText("Import Service " + imports[i].getName()); String avail = imports[i].getDirective("availability"); String mult = imports[i].getDirective("multiple"); ri.setOptional("optional".equalsIgnoreCase(avail)); ri.setMultiple(!"false".equalsIgnoreCase(mult)); resource.addRequire(ri); } Clause[] exports = Parser.parseHeader(headers.getHeader(Constants.EXPORT_SERVICE)); for (int i = 0; exports != null && i < exports.length; i++) { CapabilityImpl cap = createServiceCapability(exports[i]); resource.addCapability(cap); } } private static String createServiceFilter(Clause clause) { String f = clause.getAttribute("filter"); StringBuffer filter = new StringBuffer(); if (f != null) { filter.append("(&"); } filter.append("("); filter.append(Capability.SERVICE); filter.append("="); filter.append(clause.getName()); filter.append(")"); if (f != null) { if (!f.startsWith("(")) { filter.append("(").append(f).append(")"); } else { filter.append(f); } filter.append(")"); } return filter.toString(); } private static CapabilityImpl createServiceCapability(Clause clause) { CapabilityImpl capability = new CapabilityImpl(Capability.SERVICE); capability.addProperty(Capability.SERVICE, clause.getName()); Attribute[] attributes = clause.getAttributes(); for (int i = 0; attributes != null && i < attributes.length; i++) { capability.addProperty(attributes[i].getName(), attributes[i].getValue()); } return capability; } private static void doFragment(ResourceImpl resource, Headers headers) { // Check if we are a fragment Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.FRAGMENT_HOST)); if (clauses != null && clauses.length == 1) { // We are a fragment, create a requirement // to our host. RequirementImpl r = new RequirementImpl(Capability.BUNDLE); StringBuffer sb = new StringBuffer(); sb.append("(&(symbolicname="); sb.append(clauses[0].getName()); sb.append(")"); appendVersion(sb, VersionRange.parseVersionRange(clauses[0].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE))); sb.append(")"); r.setFilter(sb.toString()); r.addText("Required Host " + clauses[0].getName()); r.setExtend(true); r.setOptional(false); r.setMultiple(false); resource.addRequire(r); // And insert a capability that we are available // as a fragment. ### Do we need that with extend? CapabilityImpl capability = new CapabilityImpl(Capability.FRAGMENT); capability.addProperty("host", clauses[0].getName()); capability.addProperty("version", Property.VERSION, getVersion(clauses[0])); resource.addCapability(capability); } } private static void doRequires(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.REQUIRE_BUNDLE)); for (int i = 0; clauses != null && i < clauses.length; i++) { RequirementImpl r = new RequirementImpl(Capability.BUNDLE); VersionRange v = VersionRange.parseVersionRange(clauses[i].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE)); StringBuffer sb = new StringBuffer(); sb.append("(&(symbolicname="); sb.append(clauses[i].getName()); sb.append(")"); appendVersion(sb, v); sb.append(")"); r.setFilter(sb.toString()); r.addText("Require Bundle " + clauses[i].getName() + "; " + v); r.setOptional(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE))); resource.addRequire(r); } } private static void doBundle(ResourceImpl resource, Headers headers) { CapabilityImpl capability = new CapabilityImpl(Capability.BUNDLE); capability.addProperty(Resource.SYMBOLIC_NAME, getSymbolicName(headers)); if (headers.getHeader(Constants.BUNDLE_NAME) != null) { capability.addProperty(Resource.PRESENTATION_NAME, headers.getHeader(Constants.BUNDLE_NAME)); } capability.addProperty(Resource.VERSION, Property.VERSION, getVersion(headers)); capability.addProperty(Resource.MANIFEST_VERSION, getManifestVersion(headers)); resource.addCapability(capability); } private static void doExports(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.EXPORT_PACKAGE)); for (int i = 0; clauses != null && i < clauses.length; i++) { CapabilityImpl capability = createCapability(Capability.PACKAGE, clauses[i]); resource.addCapability(capability); } } private static void doProvides(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.PROVIDE_CAPABILITY)); if (clauses != null) { for (Clause clause : clauses) { CapabilityImpl capability = createCapability(clause.getName(), clause); resource.addCapability(capability); } } } private static CapabilityImpl createCapability(String name, Clause clause) { CapabilityImpl capability = new CapabilityImpl(NamespaceTranslator.getFelixNamespace(name)); capability.addProperty(name, clause.getName()); capability.addProperty(Resource.VERSION, Property.VERSION, getVersion(clause)); Attribute[] attributes = clause.getAttributes(); for (int i = 0; attributes != null && i < attributes.length; i++) { String key = attributes[i].getName(); if (key.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) || key.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE) || key.equalsIgnoreCase("version:Version")) { continue; } else { String value = attributes[i].getValue(); capability.addProperty(key, value); } } Directive[] directives = clause.getDirectives(); for (int i = 0; directives != null && i < directives.length; i++) { String key = directives[i].getName(); String value = directives[i].getValue(); capability.addProperty(key + ":", value); } return capability; } private static void doImports(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.IMPORT_PACKAGE)); for (int i = 0; clauses != null && i < clauses.length; i++) { RequirementImpl requirement = new RequirementImpl(Capability.PACKAGE); createImportFilter(requirement, Capability.PACKAGE, clauses[i]); requirement.addText("Import package " + clauses[i]); requirement.setOptional(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(clauses[i].getDirective(Constants.RESOLUTION_DIRECTIVE))); resource.addRequire(requirement); } } private static void createImportFilter(RequirementImpl requirement, String name, Clause clause) { StringBuffer filter = new StringBuffer(); filter.append("(&("); filter.append(name); filter.append("="); filter.append(clause.getName()); filter.append(")"); appendVersion(filter, getVersionRange(clause)); Attribute[] attributes = clause.getAttributes(); Set attrs = doImportPackageAttributes(requirement, filter, attributes); // The next code is using the subset operator // to check mandatory attributes, it seems to be // impossible to rewrite. It must assert that whateber // is in mandatory: must be in any of the attributes. // This is a fundamental shortcoming of the filter language. if (attrs.size() > 0) { String del = ""; filter.append("(mandatory:<*"); for (Iterator i = attrs.iterator(); i.hasNext();) { filter.append(del); filter.append(i.next()); del = ", "; } filter.append(")"); } filter.append(")"); requirement.setFilter(filter.toString()); } private static Set doImportPackageAttributes(RequirementImpl requirement, StringBuffer filter, Attribute[] attributes) { HashSet set = new HashSet(); for (int i = 0; attributes != null && i < attributes.length; i++) { String name = attributes[i].getName(); String value = attributes[i].getValue(); if (name.equalsIgnoreCase(Constants.PACKAGE_SPECIFICATION_VERSION) || name.equalsIgnoreCase(Constants.VERSION_ATTRIBUTE)) { continue; } else if (name.equalsIgnoreCase(Constants.RESOLUTION_DIRECTIVE + ":")) { requirement.setOptional(Constants.RESOLUTION_OPTIONAL.equalsIgnoreCase(value)); } if (name.endsWith(":")) { // Ignore } else { filter.append("("); filter.append(name); filter.append("="); filter.append(value); filter.append(")"); set.add(name); } } return set; } private static void doExecutionEnvironment(ResourceImpl resource, Headers headers) { Clause[] clauses = Parser.parseHeader(headers.getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT)); if (clauses != null && clauses.length > 0) { StringBuffer sb = new StringBuffer(); sb.append("(|"); for (int i = 0; i < clauses.length; i++) { sb.append("("); sb.append(Capability.EXECUTIONENVIRONMENT); sb.append("="); sb.append(clauses[i].getName()); sb.append(")"); } sb.append(")"); RequirementImpl req = new RequirementImpl(Capability.EXECUTIONENVIRONMENT); req.setFilter(sb.toString()); req.addText("Execution Environment " + sb.toString()); resource.addRequire(req); } } private static String getVersion(Clause clause) { String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE); if (v == null) { v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); } if (v == null) { v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE); } if (v == null) { v = clause.getAttribute("version:Version"); } return VersionCleaner.clean(v); } private static VersionRange getVersionRange(Clause clause) { String v = clause.getAttribute(Constants.VERSION_ATTRIBUTE); if (v == null) { v = clause.getAttribute(Constants.PACKAGE_SPECIFICATION_VERSION); } if (v == null) { v = clause.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE); } return VersionRange.parseVersionRange(v); } private static String getSymbolicName(Headers headers) { String bsn = headers.getHeader(Constants.BUNDLE_SYMBOLICNAME); if (bsn == null) { bsn = headers.getHeader(Constants.BUNDLE_NAME); if (bsn == null) { bsn = "Untitled-" + headers.hashCode(); } } Clause[] clauses = Parser.parseHeader(bsn); return clauses[0].getName(); } private static String getVersion(Headers headers) { String v = headers.getHeader(Constants.BUNDLE_VERSION); return VersionCleaner.clean(v); } private static String getManifestVersion(Headers headers) { String v = headers.getHeader(Constants.BUNDLE_MANIFESTVERSION); if (v == null) { v = "1"; } return v; } private static void appendVersion(StringBuffer filter, VersionRange version) { if (version != null) { if ( !version.isOpenFloor() ) { if ( !Version.emptyVersion.equals(version.getFloor()) ) { filter.append("("); filter.append(Constants.VERSION_ATTRIBUTE); filter.append(">="); filter.append(version.getFloor()); filter.append(")"); } } else { filter.append("(!("); filter.append(Constants.VERSION_ATTRIBUTE); filter.append("<="); filter.append(version.getFloor()); filter.append("))"); } if (!VersionRange.INFINITE_VERSION.equals(version.getCeiling())) { if ( !version.isOpenCeiling() ) { filter.append("("); filter.append(Constants.VERSION_ATTRIBUTE); filter.append("<="); filter.append(version.getCeiling()); filter.append(")"); } else { filter.append("(!("); filter.append(Constants.VERSION_ATTRIBUTE); filter.append(">="); filter.append(version.getCeiling()); filter.append("))"); } } } } interface Headers { String getHeader(String name); } public Repository readRepository(String xml) throws Exception { try { return readRepository(new StringReader(xml)); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public Repository readRepository(Reader reader) throws Exception { return RepositoryParser.getParser().parseRepository(reader); } public Resource readResource(String xml) throws Exception { try { return readResource(new StringReader(xml)); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public Resource readResource(Reader reader) throws Exception { return RepositoryParser.getParser().parseResource(reader); } public Capability readCapability(String xml) throws Exception { try { return readCapability(new StringReader(xml)); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public Capability readCapability(Reader reader) throws Exception { return RepositoryParser.getParser().parseCapability(reader); } public Requirement readRequirement(String xml) throws Exception { try { return readRequirement(new StringReader(xml)); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public Requirement readRequirement(Reader reader) throws Exception { return RepositoryParser.getParser().parseRequirement(reader); } public Property readProperty(String xml) throws Exception { try { return readProperty(new StringReader(xml)); } catch (IOException e) { IllegalStateException ex = new IllegalStateException(e); ex.initCause(e); throw ex; } } public Property readProperty(Reader reader) throws Exception { return RepositoryParser.getParser().parseProperty(reader); } }
apache/hadoop-common
37,605
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.http.server; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileChecksum; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.GlobFilter; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.hadoop.fs.XAttrCodec; import org.apache.hadoop.fs.XAttrSetFlag; import org.apache.hadoop.fs.http.client.HttpFSFileSystem; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclStatus; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.protocol.AclException; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.lib.service.FileSystemAccess; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * FileSystem operation executors used by {@link HttpFSServer}. */ @InterfaceAudience.Private public class FSOperations { /** * This class is used to group a FileStatus and an AclStatus together. * It's needed for the GETFILESTATUS and LISTSTATUS calls, which take * most info from the FileStatus and a wee bit from the AclStatus. */ private static class StatusPair { private FileStatus fileStatus; private AclStatus aclStatus; /** * Simple constructor * @param fileStatus Existing FileStatus object * @param aclStatus Existing AclStatus object */ public StatusPair(FileStatus fileStatus, AclStatus aclStatus) { this.fileStatus = fileStatus; this.aclStatus = aclStatus; } /** * Create one StatusPair by performing the underlying calls to * fs.getFileStatus and fs.getAclStatus * @param fs The FileSystem where 'path' lives * @param path The file/directory to query * @throws IOException */ public StatusPair(FileSystem fs, Path path) throws IOException { fileStatus = fs.getFileStatus(path); aclStatus = null; try { aclStatus = fs.getAclStatus(path); } catch (AclException e) { /* * The cause is almost certainly an "ACLS aren't enabled" * exception, so leave aclStatus at null and carry on. */ } catch (UnsupportedOperationException e) { /* Ditto above - this is the case for a local file system */ } } /** * Return a Map suitable for conversion into JSON format * @return The JSONish Map */ public Map<String,Object> toJson() { Map<String,Object> json = new LinkedHashMap<String,Object>(); json.put(HttpFSFileSystem.FILE_STATUS_JSON, toJsonInner(true)); return json; } /** * Return in inner part of the JSON for the status - used by both the * GETFILESTATUS and LISTSTATUS calls. * @param emptyPathSuffix Whether or not to include PATH_SUFFIX_JSON * @return The JSONish Map */ public Map<String,Object> toJsonInner(boolean emptyPathSuffix) { Map<String,Object> json = new LinkedHashMap<String,Object>(); json.put(HttpFSFileSystem.PATH_SUFFIX_JSON, (emptyPathSuffix) ? "" : fileStatus.getPath().getName()); json.put(HttpFSFileSystem.TYPE_JSON, HttpFSFileSystem.FILE_TYPE.getType(fileStatus).toString()); json.put(HttpFSFileSystem.LENGTH_JSON, fileStatus.getLen()); json.put(HttpFSFileSystem.OWNER_JSON, fileStatus.getOwner()); json.put(HttpFSFileSystem.GROUP_JSON, fileStatus.getGroup()); json.put(HttpFSFileSystem.PERMISSION_JSON, HttpFSFileSystem.permissionToString(fileStatus.getPermission())); json.put(HttpFSFileSystem.ACCESS_TIME_JSON, fileStatus.getAccessTime()); json.put(HttpFSFileSystem.MODIFICATION_TIME_JSON, fileStatus.getModificationTime()); json.put(HttpFSFileSystem.BLOCK_SIZE_JSON, fileStatus.getBlockSize()); json.put(HttpFSFileSystem.REPLICATION_JSON, fileStatus.getReplication()); if ( (aclStatus != null) && !(aclStatus.getEntries().isEmpty()) ) { json.put(HttpFSFileSystem.ACL_BIT_JSON,true); } return json; } } /** * Simple class used to contain and operate upon a list of StatusPair * objects. Used by LISTSTATUS. */ private static class StatusPairs { private StatusPair[] statusPairs; /** * Construct a list of StatusPair objects * @param fs The FileSystem where 'path' lives * @param path The directory to query * @param filter A possible filter for entries in the directory * @throws IOException */ public StatusPairs(FileSystem fs, Path path, PathFilter filter) throws IOException { /* Grab all the file statuses at once in an array */ FileStatus[] fileStatuses = fs.listStatus(path, filter); /* We'll have an array of StatusPairs of the same length */ AclStatus aclStatus = null; statusPairs = new StatusPair[fileStatuses.length]; /* * For each FileStatus, attempt to acquire an AclStatus. If the * getAclStatus throws an exception, we assume that ACLs are turned * off entirely and abandon the attempt. */ boolean useAcls = true; // Assume ACLs work until proven otherwise for (int i = 0; i < fileStatuses.length; i++) { if (useAcls) { try { aclStatus = fs.getAclStatus(fileStatuses[i].getPath()); } catch (AclException e) { /* Almost certainly due to an "ACLs not enabled" exception */ aclStatus = null; useAcls = false; } catch (UnsupportedOperationException e) { /* Ditto above - this is the case for a local file system */ aclStatus = null; useAcls = false; } } statusPairs[i] = new StatusPair(fileStatuses[i], aclStatus); } } /** * Return a Map suitable for conversion into JSON. * @return A JSONish Map */ @SuppressWarnings({"unchecked"}) public Map<String,Object> toJson() { Map<String,Object> json = new LinkedHashMap<String,Object>(); Map<String,Object> inner = new LinkedHashMap<String,Object>(); JSONArray statuses = new JSONArray(); for (StatusPair s : statusPairs) { statuses.add(s.toJsonInner(false)); } inner.put(HttpFSFileSystem.FILE_STATUS_JSON, statuses); json.put(HttpFSFileSystem.FILE_STATUSES_JSON, inner); return json; } } /** Converts an <code>AclStatus</code> object into a JSON object. * * @param aclStatus AclStatus object * * @return The JSON representation of the ACLs for the file */ @SuppressWarnings({"unchecked"}) private static Map<String,Object> aclStatusToJSON(AclStatus aclStatus) { Map<String,Object> json = new LinkedHashMap<String,Object>(); Map<String,Object> inner = new LinkedHashMap<String,Object>(); JSONArray entriesArray = new JSONArray(); inner.put(HttpFSFileSystem.OWNER_JSON, aclStatus.getOwner()); inner.put(HttpFSFileSystem.GROUP_JSON, aclStatus.getGroup()); inner.put(HttpFSFileSystem.ACL_STICKY_BIT_JSON, aclStatus.isStickyBit()); for ( AclEntry e : aclStatus.getEntries() ) { entriesArray.add(e.toString()); } inner.put(HttpFSFileSystem.ACL_ENTRIES_JSON, entriesArray); json.put(HttpFSFileSystem.ACL_STATUS_JSON, inner); return json; } /** * Converts a <code>FileChecksum</code> object into a JSON array * object. * * @param checksum file checksum. * * @return The JSON representation of the file checksum. */ @SuppressWarnings({"unchecked"}) private static Map fileChecksumToJSON(FileChecksum checksum) { Map json = new LinkedHashMap(); json.put(HttpFSFileSystem.CHECKSUM_ALGORITHM_JSON, checksum.getAlgorithmName()); json.put(HttpFSFileSystem.CHECKSUM_BYTES_JSON, org.apache.hadoop.util.StringUtils.byteToHexString(checksum.getBytes())); json.put(HttpFSFileSystem.CHECKSUM_LENGTH_JSON, checksum.getLength()); Map response = new LinkedHashMap(); response.put(HttpFSFileSystem.FILE_CHECKSUM_JSON, json); return response; } /** * Converts xAttrs to a JSON object. * * @param xAttrs file xAttrs. * @param encoding format of xattr values. * * @return The JSON representation of the xAttrs. * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes"}) private static Map xAttrsToJSON(Map<String, byte[]> xAttrs, XAttrCodec encoding) throws IOException { Map jsonMap = new LinkedHashMap(); JSONArray jsonArray = new JSONArray(); if (xAttrs != null) { for (Entry<String, byte[]> e : xAttrs.entrySet()) { Map json = new LinkedHashMap(); json.put(HttpFSFileSystem.XATTR_NAME_JSON, e.getKey()); if (e.getValue() != null) { json.put(HttpFSFileSystem.XATTR_VALUE_JSON, XAttrCodec.encodeValue(e.getValue(), encoding)); } jsonArray.add(json); } } jsonMap.put(HttpFSFileSystem.XATTRS_JSON, jsonArray); return jsonMap; } /** * Converts xAttr names to a JSON object. * * @param names file xAttr names. * * @return The JSON representation of the xAttr names. * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes"}) private static Map xAttrNamesToJSON(List<String> names) throws IOException { Map jsonMap = new LinkedHashMap(); jsonMap.put(HttpFSFileSystem.XATTRNAMES_JSON, JSONArray.toJSONString(names)); return jsonMap; } /** * Converts a <code>ContentSummary</code> object into a JSON array * object. * * @param contentSummary the content summary * * @return The JSON representation of the content summary. */ @SuppressWarnings({"unchecked"}) private static Map contentSummaryToJSON(ContentSummary contentSummary) { Map json = new LinkedHashMap(); json.put(HttpFSFileSystem.CONTENT_SUMMARY_DIRECTORY_COUNT_JSON, contentSummary.getDirectoryCount()); json.put(HttpFSFileSystem.CONTENT_SUMMARY_FILE_COUNT_JSON, contentSummary.getFileCount()); json.put(HttpFSFileSystem.CONTENT_SUMMARY_LENGTH_JSON, contentSummary.getLength()); json.put(HttpFSFileSystem.CONTENT_SUMMARY_QUOTA_JSON, contentSummary.getQuota()); json.put(HttpFSFileSystem.CONTENT_SUMMARY_SPACE_CONSUMED_JSON, contentSummary.getSpaceConsumed()); json.put(HttpFSFileSystem.CONTENT_SUMMARY_SPACE_QUOTA_JSON, contentSummary.getSpaceQuota()); Map response = new LinkedHashMap(); response.put(HttpFSFileSystem.CONTENT_SUMMARY_JSON, json); return response; } /** * Converts an object into a Json Map with with one key-value entry. * <p/> * It assumes the given value is either a JSON primitive type or a * <code>JsonAware</code> instance. * * @param name name for the key of the entry. * @param value for the value of the entry. * * @return the JSON representation of the key-value pair. */ @SuppressWarnings("unchecked") private static JSONObject toJSON(String name, Object value) { JSONObject json = new JSONObject(); json.put(name, value); return json; } /** * Executor that performs an append FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSAppend implements FileSystemAccess.FileSystemExecutor<Void> { private InputStream is; private Path path; /** * Creates an Append executor. * * @param is input stream to append. * @param path path of the file to append. */ public FSAppend(InputStream is, String path) { this.is = is; this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occured. */ @Override public Void execute(FileSystem fs) throws IOException { int bufferSize = fs.getConf().getInt("httpfs.buffer.size", 4096); OutputStream os = fs.append(path, bufferSize); IOUtils.copyBytes(is, os, bufferSize, true); os.close(); return null; } } /** * Executor that performs an append FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSConcat implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private Path[] sources; /** * Creates a Concat executor. * * @param path target path to concat to. * @param sources comma seperated absolute paths to use as sources. */ public FSConcat(String path, String[] sources) { this.sources = new Path[sources.length]; for(int i = 0; i < sources.length; i++) { this.sources[i] = new Path(sources[i]); } this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occured. */ @Override public Void execute(FileSystem fs) throws IOException { fs.concat(path, sources); return null; } } /** * Executor that performs a content-summary FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSContentSummary implements FileSystemAccess.FileSystemExecutor<Map> { private Path path; /** * Creates a content-summary executor. * * @param path the path to retrieve the content-summary. */ public FSContentSummary(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return a Map object (JSON friendly) with the content-summary. * * @throws IOException thrown if an IO error occured. */ @Override public Map execute(FileSystem fs) throws IOException { ContentSummary contentSummary = fs.getContentSummary(path); return contentSummaryToJSON(contentSummary); } } /** * Executor that performs a create FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSCreate implements FileSystemAccess.FileSystemExecutor<Void> { private InputStream is; private Path path; private short permission; private boolean override; private short replication; private long blockSize; /** * Creates a Create executor. * * @param is input stream to for the file to create. * @param path path of the file to create. * @param perm permission for the file. * @param override if the file should be overriden if it already exist. * @param repl the replication factor for the file. * @param blockSize the block size for the file. */ public FSCreate(InputStream is, String path, short perm, boolean override, short repl, long blockSize) { this.is = is; this.path = new Path(path); this.permission = perm; this.override = override; this.replication = repl; this.blockSize = blockSize; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return The URI of the created file. * * @throws IOException thrown if an IO error occured. */ @Override public Void execute(FileSystem fs) throws IOException { if (replication == -1) { replication = fs.getDefaultReplication(path); } if (blockSize == -1) { blockSize = fs.getDefaultBlockSize(path); } FsPermission fsPermission = new FsPermission(permission); int bufferSize = fs.getConf().getInt("httpfs.buffer.size", 4096); OutputStream os = fs.create(path, fsPermission, override, bufferSize, replication, blockSize, null); IOUtils.copyBytes(is, os, bufferSize, true); os.close(); return null; } } /** * Executor that performs a delete FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSDelete implements FileSystemAccess.FileSystemExecutor<JSONObject> { private Path path; private boolean recursive; /** * Creates a Delete executor. * * @param path path to delete. * @param recursive if the delete should be recursive or not. */ public FSDelete(String path, boolean recursive) { this.path = new Path(path); this.recursive = recursive; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return <code>true</code> if the delete operation was successful, * <code>false</code> otherwise. * * @throws IOException thrown if an IO error occured. */ @Override public JSONObject execute(FileSystem fs) throws IOException { boolean deleted = fs.delete(path, recursive); return toJSON(HttpFSFileSystem.DELETE_JSON.toLowerCase(), deleted); } } /** * Executor that performs a file-checksum FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSFileChecksum implements FileSystemAccess.FileSystemExecutor<Map> { private Path path; /** * Creates a file-checksum executor. * * @param path the path to retrieve the checksum. */ public FSFileChecksum(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return a Map object (JSON friendly) with the file checksum. * * @throws IOException thrown if an IO error occured. */ @Override public Map execute(FileSystem fs) throws IOException { FileChecksum checksum = fs.getFileChecksum(path); return fileChecksumToJSON(checksum); } } /** * Executor that performs a file-status FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSFileStatus implements FileSystemAccess.FileSystemExecutor<Map> { private Path path; /** * Creates a file-status executor. * * @param path the path to retrieve the status. */ public FSFileStatus(String path) { this.path = new Path(path); } /** * Executes the filesystem getFileStatus operation and returns the * result in a JSONish Map. * * @param fs filesystem instance to use. * * @return a Map object (JSON friendly) with the file status. * * @throws IOException thrown if an IO error occurred. */ @Override public Map execute(FileSystem fs) throws IOException { StatusPair sp = new StatusPair(fs, path); return sp.toJson(); } } /** * Executor that performs a home-dir FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSHomeDir implements FileSystemAccess.FileSystemExecutor<JSONObject> { /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return a JSON object with the user home directory. * * @throws IOException thrown if an IO error occured. */ @Override @SuppressWarnings("unchecked") public JSONObject execute(FileSystem fs) throws IOException { Path homeDir = fs.getHomeDirectory(); JSONObject json = new JSONObject(); json.put(HttpFSFileSystem.HOME_DIR_JSON, homeDir.toUri().getPath()); return json; } } /** * Executor that performs a list-status FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSListStatus implements FileSystemAccess.FileSystemExecutor<Map>, PathFilter { private Path path; private PathFilter filter; /** * Creates a list-status executor. * * @param path the directory to retrieve the status of its contents. * @param filter glob filter to use. * * @throws IOException thrown if the filter expression is incorrect. */ public FSListStatus(String path, String filter) throws IOException { this.path = new Path(path); this.filter = (filter == null) ? this : new GlobFilter(filter); } /** * Returns data for a JSON Map containing the information for * the set of files in 'path' that match 'filter'. * * @param fs filesystem instance to use. * * @return a Map with the file status of the directory * contents that match the filter * * @throws IOException thrown if an IO error occurred. */ @Override public Map execute(FileSystem fs) throws IOException { StatusPairs sp = new StatusPairs(fs, path, filter); return sp.toJson(); } @Override public boolean accept(Path path) { return true; } } /** * Executor that performs a mkdirs FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSMkdirs implements FileSystemAccess.FileSystemExecutor<JSONObject> { private Path path; private short permission; /** * Creates a mkdirs executor. * * @param path directory path to create. * @param permission permission to use. */ public FSMkdirs(String path, short permission) { this.path = new Path(path); this.permission = permission; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return <code>true</code> if the mkdirs operation was successful, * <code>false</code> otherwise. * * @throws IOException thrown if an IO error occured. */ @Override public JSONObject execute(FileSystem fs) throws IOException { FsPermission fsPermission = new FsPermission(permission); boolean mkdirs = fs.mkdirs(path, fsPermission); return toJSON(HttpFSFileSystem.MKDIRS_JSON, mkdirs); } } /** * Executor that performs a open FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSOpen implements FileSystemAccess.FileSystemExecutor<InputStream> { private Path path; /** * Creates a open executor. * * @param path file to open. */ public FSOpen(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return The inputstream of the file. * * @throws IOException thrown if an IO error occured. */ @Override public InputStream execute(FileSystem fs) throws IOException { int bufferSize = HttpFSServerWebApp.get().getConfig().getInt("httpfs.buffer.size", 4096); return fs.open(path, bufferSize); } } /** * Executor that performs a rename FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSRename implements FileSystemAccess.FileSystemExecutor<JSONObject> { private Path path; private Path toPath; /** * Creates a rename executor. * * @param path path to rename. * @param toPath new name. */ public FSRename(String path, String toPath) { this.path = new Path(path); this.toPath = new Path(toPath); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return <code>true</code> if the rename operation was successful, * <code>false</code> otherwise. * * @throws IOException thrown if an IO error occured. */ @Override public JSONObject execute(FileSystem fs) throws IOException { boolean renamed = fs.rename(path, toPath); return toJSON(HttpFSFileSystem.RENAME_JSON, renamed); } } /** * Executor that performs a set-owner FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSSetOwner implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private String owner; private String group; /** * Creates a set-owner executor. * * @param path the path to set the owner. * @param owner owner to set. * @param group group to set. */ public FSSetOwner(String path, String owner, String group) { this.path = new Path(path); this.owner = owner; this.group = group; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occured. */ @Override public Void execute(FileSystem fs) throws IOException { fs.setOwner(path, owner, group); return null; } } /** * Executor that performs a set-permission FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSSetPermission implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private short permission; /** * Creates a set-permission executor. * * @param path path to set the permission. * @param permission permission to set. */ public FSSetPermission(String path, short permission) { this.path = new Path(path); this.permission = permission; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occured. */ @Override public Void execute(FileSystem fs) throws IOException { FsPermission fsPermission = new FsPermission(permission); fs.setPermission(path, fsPermission); return null; } } /** * Executor that sets the acl for a file in a FileSystem */ @InterfaceAudience.Private public static class FSSetAcl implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private List<AclEntry> aclEntries; /** * Creates a set-acl executor. * * @param path path to set the acl. * @param aclSpec acl to set. */ public FSSetAcl(String path, String aclSpec) { this.path = new Path(path); this.aclEntries = AclEntry.parseAclSpec(aclSpec, true); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occurred. */ @Override public Void execute(FileSystem fs) throws IOException { fs.setAcl(path, aclEntries); return null; } } /** * Executor that removes all acls from a file in a FileSystem */ @InterfaceAudience.Private public static class FSRemoveAcl implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; /** * Creates a remove-acl executor. * * @param path path from which to remove the acl. */ public FSRemoveAcl(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occurred. */ @Override public Void execute(FileSystem fs) throws IOException { fs.removeAcl(path); return null; } } /** * Executor that modifies acl entries for a file in a FileSystem */ @InterfaceAudience.Private public static class FSModifyAclEntries implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private List<AclEntry> aclEntries; /** * Creates a modify-acl executor. * * @param path path to set the acl. * @param aclSpec acl to set. */ public FSModifyAclEntries(String path, String aclSpec) { this.path = new Path(path); this.aclEntries = AclEntry.parseAclSpec(aclSpec, true); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occurred. */ @Override public Void execute(FileSystem fs) throws IOException { fs.modifyAclEntries(path, aclEntries); return null; } } /** * Executor that removes acl entries from a file in a FileSystem */ @InterfaceAudience.Private public static class FSRemoveAclEntries implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private List<AclEntry> aclEntries; /** * Creates a remove acl entry executor. * * @param path path to set the acl. * @param aclSpec acl parts to remove. */ public FSRemoveAclEntries(String path, String aclSpec) { this.path = new Path(path); this.aclEntries = AclEntry.parseAclSpec(aclSpec, true); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occurred. */ @Override public Void execute(FileSystem fs) throws IOException { fs.removeAclEntries(path, aclEntries); return null; } } /** * Executor that removes the default acl from a directory in a FileSystem */ @InterfaceAudience.Private public static class FSRemoveDefaultAcl implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; /** * Creates an executor for removing the default acl. * * @param path path to set the acl. */ public FSRemoveDefaultAcl(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occurred. */ @Override public Void execute(FileSystem fs) throws IOException { fs.removeDefaultAcl(path); return null; } } /** * Executor that gets the ACL information for a given file. */ @InterfaceAudience.Private public static class FSAclStatus implements FileSystemAccess.FileSystemExecutor<Map> { private Path path; /** * Creates an executor for getting the ACLs for a file. * * @param path the path to retrieve the ACLs. */ public FSAclStatus(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return a Map object (JSON friendly) with the file status. * * @throws IOException thrown if an IO error occurred. */ @Override public Map execute(FileSystem fs) throws IOException { AclStatus status = fs.getAclStatus(path); return aclStatusToJSON(status); } } /** * Executor that performs a set-replication FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSSetReplication implements FileSystemAccess.FileSystemExecutor<JSONObject> { private Path path; private short replication; /** * Creates a set-replication executor. * * @param path path to set the replication factor. * @param replication replication factor to set. */ public FSSetReplication(String path, short replication) { this.path = new Path(path); this.replication = replication; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return <code>true</code> if the replication value was set, * <code>false</code> otherwise. * * @throws IOException thrown if an IO error occured. */ @Override @SuppressWarnings("unchecked") public JSONObject execute(FileSystem fs) throws IOException { boolean ret = fs.setReplication(path, replication); JSONObject json = new JSONObject(); json.put(HttpFSFileSystem.SET_REPLICATION_JSON, ret); return json; } } /** * Executor that performs a set-times FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSSetTimes implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private long mTime; private long aTime; /** * Creates a set-times executor. * * @param path path to set the times. * @param mTime modified time to set. * @param aTime access time to set. */ public FSSetTimes(String path, long mTime, long aTime) { this.path = new Path(path); this.mTime = mTime; this.aTime = aTime; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return void. * * @throws IOException thrown if an IO error occured. */ @Override public Void execute(FileSystem fs) throws IOException { fs.setTimes(path, mTime, aTime); return null; } } /** * Executor that performs a setxattr FileSystemAccess files system operation. */ @InterfaceAudience.Private public static class FSSetXAttr implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private String name; private byte[] value; private EnumSet<XAttrSetFlag> flag; public FSSetXAttr(String path, String name, String encodedValue, EnumSet<XAttrSetFlag> flag) throws IOException { this.path = new Path(path); this.name = name; this.value = XAttrCodec.decodeValue(encodedValue); this.flag = flag; } @Override public Void execute(FileSystem fs) throws IOException { fs.setXAttr(path, name, value, flag); return null; } } /** * Executor that performs a removexattr FileSystemAccess files system * operation. */ @InterfaceAudience.Private public static class FSRemoveXAttr implements FileSystemAccess.FileSystemExecutor<Void> { private Path path; private String name; public FSRemoveXAttr(String path, String name) { this.path = new Path(path); this.name = name; } @Override public Void execute(FileSystem fs) throws IOException { fs.removeXAttr(path, name); return null; } } /** * Executor that performs listing xattrs FileSystemAccess files system * operation. */ @SuppressWarnings("rawtypes") @InterfaceAudience.Private public static class FSListXAttrs implements FileSystemAccess.FileSystemExecutor<Map> { private Path path; /** * Creates listing xattrs executor. * * @param path the path to retrieve the xattrs. */ public FSListXAttrs(String path) { this.path = new Path(path); } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return Map a map object (JSON friendly) with the xattr names. * * @throws IOException thrown if an IO error occured. */ @Override public Map execute(FileSystem fs) throws IOException { List<String> names = fs.listXAttrs(path); return xAttrNamesToJSON(names); } } /** * Executor that performs getting xattrs FileSystemAccess files system * operation. */ @SuppressWarnings("rawtypes") @InterfaceAudience.Private public static class FSGetXAttrs implements FileSystemAccess.FileSystemExecutor<Map> { private Path path; private List<String> names; private XAttrCodec encoding; /** * Creates getting xattrs executor. * * @param path the path to retrieve the xattrs. */ public FSGetXAttrs(String path, List<String> names, XAttrCodec encoding) { this.path = new Path(path); this.names = names; this.encoding = encoding; } /** * Executes the filesystem operation. * * @param fs filesystem instance to use. * * @return Map a map object (JSON friendly) with the xattrs. * * @throws IOException thrown if an IO error occured. */ @Override public Map execute(FileSystem fs) throws IOException { Map<String, byte[]> xattrs = null; if (names != null && !names.isEmpty()) { xattrs = fs.getXAttrs(path, names); } else { xattrs = fs.getXAttrs(path); } return xAttrsToJSON(xattrs, encoding); } } }
apache/kafka
37,036
tools/src/test/java/org/apache/kafka/tools/consumer/ConsoleConsumerOptionsTest.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.tools.consumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.requests.ListOffsetsRequest; import org.apache.kafka.common.utils.Exit; import org.apache.kafka.test.MockDeserializer; import org.apache.kafka.tools.ToolsTestUtils; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; public class ConsoleConsumerOptionsTest { @Test public void shouldParseValidConsumerValidConfig() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--from-beginning" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertTrue(config.fromBeginning()); assertFalse(config.enableSystestEventsLogging()); assertFalse(config.skipMessageOnError()); assertEquals(-1, config.maxMessages()); assertEquals(Long.MAX_VALUE, config.timeoutMs()); } @Test public void shouldParseIncludeArgument() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--include", "includeTest*", "--from-beginning" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("includeTest*", config.includedTopicsArg().orElse("")); assertTrue(config.fromBeginning()); } @Test public void shouldParseValidSimpleConsumerValidConfigWithNumericOffset() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--offset", "3" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertTrue(config.partitionArg().isPresent()); assertEquals(0, config.partitionArg().getAsInt()); assertEquals(3, config.offsetArg()); assertFalse(config.fromBeginning()); } @Test public void shouldExitOnUnrecognizedNewConsumerOption() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--new-consumer", "--bootstrap-server", "localhost:9092", "--topic", "test", "--from-beginning" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldExitIfPartitionButNoTopic() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--include", "test.*", "--partition", "0" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldExitIfFromBeginningAndOffset() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--from-beginning", "--offset", "123" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldParseValidSimpleConsumerValidConfigWithStringOffsetDeprecated() throws Exception { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--offset", "LatEst", "--property", "print.value=false" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertTrue(config.partitionArg().isPresent()); assertEquals(0, config.partitionArg().getAsInt()); assertEquals(-1, config.offsetArg()); assertFalse(config.fromBeginning()); assertFalse(((DefaultMessageFormatter) config.formatter()).printValue()); } @Test public void shouldParseValidSimpleConsumerValidConfigWithStringOffset() throws Exception { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--offset", "LatEst", "--formatter-property", "print.value=false" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertTrue(config.partitionArg().isPresent()); assertEquals(0, config.partitionArg().getAsInt()); assertEquals(-1, config.offsetArg()); assertFalse(config.fromBeginning()); assertFalse(((DefaultMessageFormatter) config.formatter()).printValue()); } @Test public void shouldParseValidConsumerConfigWithAutoOffsetResetLatestDeprecated() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer-property", "auto.offset.reset=latest" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertFalse(config.fromBeginning()); assertEquals("latest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldParseValidConsumerConfigWithAutoOffsetResetEarliestDeprecated() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer-property", "auto.offset.reset=earliest" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertFalse(config.fromBeginning()); assertEquals("earliest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldParseValidConsumerConfigWithAutoOffsetResetAndMatchingFromBeginningDeprecated() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer-property", "auto.offset.reset=earliest", "--from-beginning" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertTrue(config.fromBeginning()); assertEquals("earliest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldParseValidConsumerConfigWithNoOffsetReset() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertFalse(config.fromBeginning()); assertEquals("latest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldExitOnInvalidConfigWithAutoOffsetResetAndConflictingFromBeginningDeprecated() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer-property", "auto.offset.reset=latest", "--from-beginning" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldParseConfigsFromFileDeprecated() throws IOException { Map<String, String> configs = new HashMap<>(); configs.put("request.timeout.ms", "1000"); configs.put("group.id", "group1"); File propsFile = ToolsTestUtils.tempPropertiesFile(configs); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer.config", propsFile.getAbsolutePath() }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("1000", config.consumerProps().get("request.timeout.ms")); assertEquals("group1", config.consumerProps().get("group.id")); } @Test public void groupIdsProvidedInDifferentPlacesMustMatchDeprecated() throws IOException { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); try { // different in all three places File propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "group-from-file")); final String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments", "--consumer-property", "group.id=group-from-properties", "--consumer.config", propsFile.getAbsolutePath() }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); // the same in all three places propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "test-group")); final String[] args1 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "test-group", "--consumer-property", "group.id=test-group", "--consumer.config", propsFile.getAbsolutePath() }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args1); Properties props = config.consumerProps(); assertEquals("test-group", props.getProperty("group.id")); // different via --consumer-property and --consumer.config propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "group-from-file")); final String[] args2 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer-property", "group.id=group-from-properties", "--consumer.config", propsFile.getAbsolutePath() }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args2)); // different via --consumer-property and --group final String[] args3 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments", "--consumer-property", "group.id=group-from-properties" }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args3)); // different via --group and --consumer.config propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "group-from-file")); final String[] args4 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments", "--consumer.config", propsFile.getAbsolutePath() }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args4)); // via --group only final String[] args5 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments" }; config = new ConsoleConsumerOptions(args5); props = config.consumerProps(); assertEquals("group-from-arguments", props.getProperty("group.id")); } finally { Exit.resetExitProcedure(); } } @Test public void testCustomPropertyShouldBePassedToConfigureMethodDeprecated() throws Exception { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--property", "print.key=true", "--property", "key.deserializer=org.apache.kafka.test.MockDeserializer", "--property", "key.deserializer.my-props=abc" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertInstanceOf(DefaultMessageFormatter.class, config.formatter()); assertTrue(config.formatterArgs().containsKey("key.deserializer.my-props")); DefaultMessageFormatter formatter = (DefaultMessageFormatter) config.formatter(); assertTrue(formatter.keyDeserializer().isPresent()); assertInstanceOf(MockDeserializer.class, formatter.keyDeserializer().get()); MockDeserializer keyDeserializer = (MockDeserializer) formatter.keyDeserializer().get(); assertEquals(1, keyDeserializer.configs.size()); assertEquals("abc", keyDeserializer.configs.get("my-props")); assertTrue(keyDeserializer.isKey); } @Test public void testCustomPropertyShouldBePassedToConfigureMethod() throws Exception { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--formatter-property", "print.key=true", "--formatter-property", "key.deserializer=org.apache.kafka.test.MockDeserializer", "--formatter-property", "key.deserializer.my-props=abc" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertInstanceOf(DefaultMessageFormatter.class, config.formatter()); assertTrue(config.formatterArgs().containsKey("key.deserializer.my-props")); DefaultMessageFormatter formatter = (DefaultMessageFormatter) config.formatter(); assertTrue(formatter.keyDeserializer().isPresent()); assertInstanceOf(MockDeserializer.class, formatter.keyDeserializer().get()); MockDeserializer keyDeserializer = (MockDeserializer) formatter.keyDeserializer().get(); assertEquals(1, keyDeserializer.configs.size()); assertEquals("abc", keyDeserializer.configs.get("my-props")); assertTrue(keyDeserializer.isKey); } @Test public void testCustomConfigShouldBePassedToConfigureMethodDeprecated() throws Exception { Map<String, String> configs = new HashMap<>(); configs.put("key.deserializer.my-props", "abc"); configs.put("print.key", "false"); File propsFile = ToolsTestUtils.tempPropertiesFile(configs); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--property", "print.key=true", "--property", "key.deserializer=org.apache.kafka.test.MockDeserializer", "--formatter-config", propsFile.getAbsolutePath() }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertInstanceOf(DefaultMessageFormatter.class, config.formatter()); assertTrue(config.formatterArgs().containsKey("key.deserializer.my-props")); DefaultMessageFormatter formatter = (DefaultMessageFormatter) config.formatter(); assertTrue(formatter.keyDeserializer().isPresent()); assertInstanceOf(MockDeserializer.class, formatter.keyDeserializer().get()); MockDeserializer keyDeserializer = (MockDeserializer) formatter.keyDeserializer().get(); assertEquals(1, keyDeserializer.configs.size()); assertEquals("abc", keyDeserializer.configs.get("my-props")); assertTrue(keyDeserializer.isKey); } @Test public void testCustomConfigShouldBePassedToConfigureMethod() throws Exception { Map<String, String> configs = new HashMap<>(); configs.put("key.deserializer.my-props", "abc"); configs.put("print.key", "false"); File propsFile = ToolsTestUtils.tempPropertiesFile(configs); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--formatter-property", "print.key=true", "--formatter-property", "key.deserializer=org.apache.kafka.test.MockDeserializer", "--formatter-config", propsFile.getAbsolutePath() }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertInstanceOf(DefaultMessageFormatter.class, config.formatter()); assertTrue(config.formatterArgs().containsKey("key.deserializer.my-props")); DefaultMessageFormatter formatter = (DefaultMessageFormatter) config.formatter(); assertTrue(formatter.keyDeserializer().isPresent()); assertInstanceOf(MockDeserializer.class, formatter.keyDeserializer().get()); MockDeserializer keyDeserializer = (MockDeserializer) formatter.keyDeserializer().get(); assertEquals(1, keyDeserializer.configs.size()); assertEquals("abc", keyDeserializer.configs.get("my-props")); assertTrue(keyDeserializer.isKey); } @Test public void shouldParseGroupIdFromBeginningGivenTogether() throws IOException { // Start from earliest String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "test-group", "--from-beginning" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertEquals(-2, config.offsetArg()); assertTrue(config.fromBeginning()); // Start from latest args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "test-group" }; config = new ConsoleConsumerOptions(args); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertEquals(-1, config.offsetArg()); assertFalse(config.fromBeginning()); } @Test public void shouldExitOnGroupIdAndPartitionGivenTogether() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "test-group", "--partition", "0" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldExitOnOffsetWithoutPartition() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--offset", "10" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldExitIfNoTopicOrFilterSpecified() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldExitIfTopicAndIncludeSpecified() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--include", "includeTest*" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void testClientIdOverrideDeprecated() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--from-beginning", "--consumer-property", "client.id=consumer-1" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("consumer-1", consumerProperties.getProperty(ConsumerConfig.CLIENT_ID_CONFIG)); } @Test public void testDefaultClientId() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--from-beginning" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("console-consumer", consumerProperties.getProperty(ConsumerConfig.CLIENT_ID_CONFIG)); } @Test public void testParseOffset() throws Exception { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); try { final String[] badOffset = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--offset", "bad" }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(badOffset)); final String[] negativeOffset = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--offset", "-100" }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(negativeOffset)); final String[] earliestOffset = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--offset", "earliest" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(earliestOffset); assertEquals(ListOffsetsRequest.EARLIEST_TIMESTAMP, config.offsetArg()); } finally { Exit.resetExitProcedure(); } } @Test public void testParseTimeoutMs() throws Exception { String[] withoutTimeoutMs = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0" }; assertEquals(Long.MAX_VALUE, new ConsoleConsumerOptions(withoutTimeoutMs).timeoutMs()); String[] negativeTimeoutMs = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--timeout-ms", "-100" }; assertEquals(Long.MAX_VALUE, new ConsoleConsumerOptions(negativeTimeoutMs).timeoutMs()); String[] validTimeoutMs = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--timeout-ms", "100" }; assertEquals(100, new ConsoleConsumerOptions(validTimeoutMs).timeoutMs()); } @Test public void testParseFormatter() throws Exception { String[] defaultMessageFormatter = generateArgsForFormatter("org.apache.kafka.tools.consumer.DefaultMessageFormatter"); assertInstanceOf(DefaultMessageFormatter.class, new ConsoleConsumerOptions(defaultMessageFormatter).formatter()); String[] loggingMessageFormatter = generateArgsForFormatter("org.apache.kafka.tools.consumer.LoggingMessageFormatter"); assertInstanceOf(LoggingMessageFormatter.class, new ConsoleConsumerOptions(loggingMessageFormatter).formatter()); String[] noOpMessageFormatter = generateArgsForFormatter("org.apache.kafka.tools.consumer.NoOpMessageFormatter"); assertInstanceOf(NoOpMessageFormatter.class, new ConsoleConsumerOptions(noOpMessageFormatter).formatter()); } private String[] generateArgsForFormatter(String formatter) { return new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--partition", "0", "--formatter", formatter, }; } @Test public void shouldExitOnBothConsumerPropertyAndCommandProperty() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer-property", "auto.offset.reset=latest", "--command-property", "session.timeout.ms=10000" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldExitOnBothConsumerConfigAndCommandConfig() throws IOException { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); Map<String, String> configs = new HashMap<>(); configs.put("request.timeout.ms", "1000"); File propsFile = ToolsTestUtils.tempPropertiesFile(configs); Map<String, String> configs2 = new HashMap<>(); configs2.put("session.timeout.ms", "10000"); File propsFile2 = ToolsTestUtils.tempPropertiesFile(configs2); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--consumer.config", propsFile.getAbsolutePath(), "--command-config", propsFile2.getAbsolutePath() }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldParseValidConsumerConfigWithAutoOffsetResetLatestUsingCommandProperty() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--command-property", "auto.offset.reset=latest" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertFalse(config.fromBeginning()); assertEquals("latest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldParseValidConsumerConfigWithAutoOffsetResetEarliestUsingCommandProperty() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--command-property", "auto.offset.reset=earliest" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertFalse(config.fromBeginning()); assertEquals("earliest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldParseValidConsumerConfigWithAutoOffsetResetAndMatchingFromBeginningUsingCommandProperty() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--command-property", "auto.offset.reset=earliest", "--from-beginning" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("localhost:9092", config.bootstrapServer()); assertEquals("test", config.topicArg().orElse("")); assertTrue(config.fromBeginning()); assertEquals("earliest", consumerProperties.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)); } @Test public void shouldExitOnInvalidConfigWithAutoOffsetResetAndConflictingFromBeginningUsingCommandProperty() { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--command-property", "auto.offset.reset=latest", "--from-beginning" }; try { assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); } finally { Exit.resetExitProcedure(); } } @Test public void shouldParseConfigsFromFileUsingCommandConfig() throws IOException { Map<String, String> configs = new HashMap<>(); configs.put("request.timeout.ms", "1000"); configs.put("group.id", "group1"); File propsFile = ToolsTestUtils.tempPropertiesFile(configs); String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--command-config", propsFile.getAbsolutePath() }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); assertEquals("1000", config.consumerProps().get("request.timeout.ms")); assertEquals("group1", config.consumerProps().get("group.id")); } @Test public void groupIdsProvidedInDifferentPlacesMustMatchUsingCommandConfig() throws IOException { Exit.setExitProcedure((code, message) -> { throw new IllegalArgumentException(message); }); try { // different in all three places File propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "group-from-file")); final String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments", "--command-property", "group.id=group-from-properties", "--command-config", propsFile.getAbsolutePath() }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args)); // the same in all three places propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "test-group")); final String[] args1 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "test-group", "--command-property", "group.id=test-group", "--command-config", propsFile.getAbsolutePath() }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args1); Properties props = config.consumerProps(); assertEquals("test-group", props.getProperty("group.id")); // different via --command-property and --command-config propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "group-from-file")); final String[] args2 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--command-property", "group.id=group-from-properties", "--command-config", propsFile.getAbsolutePath() }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args2)); // different via --command-property and --group final String[] args3 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments", "--command-property", "group.id=group-from-properties" }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args3)); // different via --group and --command-config propsFile = ToolsTestUtils.tempPropertiesFile(Map.of("group.id", "group-from-file")); final String[] args4 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments", "--command-config", propsFile.getAbsolutePath() }; assertThrows(IllegalArgumentException.class, () -> new ConsoleConsumerOptions(args4)); // via --group only final String[] args5 = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--group", "group-from-arguments" }; config = new ConsoleConsumerOptions(args5); props = config.consumerProps(); assertEquals("group-from-arguments", props.getProperty("group.id")); } finally { Exit.resetExitProcedure(); } } @Test public void testClientIdOverrideUsingCommandProperty() throws IOException { String[] args = new String[]{ "--bootstrap-server", "localhost:9092", "--topic", "test", "--from-beginning", "--command-property", "client.id=consumer-1" }; ConsoleConsumerOptions config = new ConsoleConsumerOptions(args); Properties consumerProperties = config.consumerProps(); assertEquals("consumer-1", consumerProperties.getProperty(ConsumerConfig.CLIENT_ID_CONFIG)); } }
googleads/google-ads-java
37,882
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/MutateCustomerSkAdNetworkConversionValueSchemaRequest.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/services/customer_sk_ad_network_conversion_value_schema_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.services; /** * <pre> * Request message for * [CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema][google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema]. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest} */ public final class MutateCustomerSkAdNetworkConversionValueSchemaRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) MutateCustomerSkAdNetworkConversionValueSchemaRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MutateCustomerSkAdNetworkConversionValueSchemaRequest.newBuilder() to construct. private MutateCustomerSkAdNetworkConversionValueSchemaRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateCustomerSkAdNetworkConversionValueSchemaRequest() { customerId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateCustomerSkAdNetworkConversionValueSchemaRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.class, com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.Builder.class); } private int bitField0_; public static final int CUSTOMER_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object customerId_ = ""; /** * <pre> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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.CustomerSkAdNetworkConversionValueSchemaOperation operation_; /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return Whether the operation field is set. */ @java.lang.Override public boolean hasOperation() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return The operation. */ @java.lang.Override public com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation getOperation() { return operation_ == null ? com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder getOperationOrBuilder() { return operation_ == null ? com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; 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 = 3;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } public static final int ENABLE_WARNINGS_FIELD_NUMBER = 4; private boolean enableWarnings_ = false; /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enableWarnings. */ @java.lang.Override public boolean getEnableWarnings() { return enableWarnings_; } 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 (validateOnly_ != false) { output.writeBool(3, validateOnly_); } if (enableWarnings_ != false) { output.writeBool(4, enableWarnings_); } 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 (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, validateOnly_); } if (enableWarnings_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, enableWarnings_); } 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest)) { return super.equals(obj); } com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest other = (com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (hasOperation() != other.hasOperation()) return false; if (hasOperation()) { if (!getOperation() .equals(other.getOperation())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (getEnableWarnings() != other.getEnableWarnings()) 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) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (37 * hash) + ENABLE_WARNINGS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEnableWarnings()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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 * [CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema][google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema]. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.class, com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.Builder.class); } // Construct using com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.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; } validateOnly_ = false; enableWarnings_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v19_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest build() { com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest buildPartial() { com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest result = new com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.validateOnly_ = validateOnly_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.enableWarnings_ = enableWarnings_; } 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest) { return mergeFrom((com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest other) { if (other == com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasOperation()) { mergeOperation(other.getOperation()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } if (other.getEnableWarnings() != false) { setEnableWarnings(other.getEnableWarnings()); } 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: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { enableWarnings_ = 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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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.CustomerSkAdNetworkConversionValueSchemaOperation operation_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder> operationBuilder_; /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return Whether the operation field is set. */ public boolean hasOperation() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return The operation. */ public com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation getOperation() { if (operationBuilder_ == null) { return operation_ == null ? com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } else { return operationBuilder_.getMessage(); } } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder setOperation(com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation value) { if (operationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; } else { operationBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder setOperation( com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder builderForValue) { if (operationBuilder_ == null) { operation_ = builderForValue.build(); } else { operationBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder mergeOperation(com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation value) { if (operationBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && operation_ != null && operation_ != com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance()) { getOperationBuilder().mergeFrom(value); } else { operation_ = value; } } else { operationBuilder_.mergeFrom(value); } if (operation_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder clearOperation() { bitField0_ = (bitField0_ & ~0x00000002); operation_ = null; if (operationBuilder_ != null) { operationBuilder_.dispose(); operationBuilder_ = null; } onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder getOperationBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOperationFieldBuilder().getBuilder(); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder getOperationOrBuilder() { if (operationBuilder_ != null) { return operationBuilder_.getMessageOrBuilder(); } else { return operation_ == null ? com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder> getOperationFieldBuilder() { if (operationBuilder_ == null) { operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v19.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder>( getOperation(), getParentForChildren(), isClean()); operation_ = null; } return operationBuilder_; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</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 = 3;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } private boolean enableWarnings_ ; /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enableWarnings. */ @java.lang.Override public boolean getEnableWarnings() { return enableWarnings_; } /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The enableWarnings to set. * @return This builder for chaining. */ public Builder setEnableWarnings(boolean value) { enableWarnings_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearEnableWarnings() { bitField0_ = (bitField0_ & ~0x00000008); enableWarnings_ = 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) private static final com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest(); } public static com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateCustomerSkAdNetworkConversionValueSchemaRequest> PARSER = new com.google.protobuf.AbstractParser<MutateCustomerSkAdNetworkConversionValueSchemaRequest>() { @java.lang.Override public MutateCustomerSkAdNetworkConversionValueSchemaRequest 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<MutateCustomerSkAdNetworkConversionValueSchemaRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateCustomerSkAdNetworkConversionValueSchemaRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,882
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/MutateCustomerSkAdNetworkConversionValueSchemaRequest.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/services/customer_sk_ad_network_conversion_value_schema_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.services; /** * <pre> * Request message for * [CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema][google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema]. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest} */ public final class MutateCustomerSkAdNetworkConversionValueSchemaRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) MutateCustomerSkAdNetworkConversionValueSchemaRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MutateCustomerSkAdNetworkConversionValueSchemaRequest.newBuilder() to construct. private MutateCustomerSkAdNetworkConversionValueSchemaRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateCustomerSkAdNetworkConversionValueSchemaRequest() { customerId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateCustomerSkAdNetworkConversionValueSchemaRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.class, com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.Builder.class); } private int bitField0_; public static final int CUSTOMER_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object customerId_ = ""; /** * <pre> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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.CustomerSkAdNetworkConversionValueSchemaOperation operation_; /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return Whether the operation field is set. */ @java.lang.Override public boolean hasOperation() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return The operation. */ @java.lang.Override public com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation getOperation() { return operation_ == null ? com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder getOperationOrBuilder() { return operation_ == null ? com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; 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 = 3;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } public static final int ENABLE_WARNINGS_FIELD_NUMBER = 4; private boolean enableWarnings_ = false; /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enableWarnings. */ @java.lang.Override public boolean getEnableWarnings() { return enableWarnings_; } 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 (validateOnly_ != false) { output.writeBool(3, validateOnly_); } if (enableWarnings_ != false) { output.writeBool(4, enableWarnings_); } 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 (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, validateOnly_); } if (enableWarnings_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, enableWarnings_); } 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest)) { return super.equals(obj); } com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest other = (com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (hasOperation() != other.hasOperation()) return false; if (hasOperation()) { if (!getOperation() .equals(other.getOperation())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (getEnableWarnings() != other.getEnableWarnings()) 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) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (37 * hash) + ENABLE_WARNINGS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEnableWarnings()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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 * [CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema][google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema]. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.class, com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.Builder.class); } // Construct using com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.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; } validateOnly_ = false; enableWarnings_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v20_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest build() { com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest buildPartial() { com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest result = new com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.validateOnly_ = validateOnly_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.enableWarnings_ = enableWarnings_; } 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest) { return mergeFrom((com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest other) { if (other == com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasOperation()) { mergeOperation(other.getOperation()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } if (other.getEnableWarnings() != false) { setEnableWarnings(other.getEnableWarnings()); } 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: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { enableWarnings_ = 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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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.CustomerSkAdNetworkConversionValueSchemaOperation operation_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder> operationBuilder_; /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return Whether the operation field is set. */ public boolean hasOperation() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return The operation. */ public com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation getOperation() { if (operationBuilder_ == null) { return operation_ == null ? com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } else { return operationBuilder_.getMessage(); } } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder setOperation(com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation value) { if (operationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; } else { operationBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder setOperation( com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder builderForValue) { if (operationBuilder_ == null) { operation_ = builderForValue.build(); } else { operationBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder mergeOperation(com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation value) { if (operationBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && operation_ != null && operation_ != com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance()) { getOperationBuilder().mergeFrom(value); } else { operation_ = value; } } else { operationBuilder_.mergeFrom(value); } if (operation_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder clearOperation() { bitField0_ = (bitField0_ & ~0x00000002); operation_ = null; if (operationBuilder_ != null) { operationBuilder_.dispose(); operationBuilder_ = null; } onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder getOperationBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOperationFieldBuilder().getBuilder(); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder getOperationOrBuilder() { if (operationBuilder_ != null) { return operationBuilder_.getMessageOrBuilder(); } else { return operation_ == null ? com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder> getOperationFieldBuilder() { if (operationBuilder_ == null) { operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v20.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder>( getOperation(), getParentForChildren(), isClean()); operation_ = null; } return operationBuilder_; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</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 = 3;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } private boolean enableWarnings_ ; /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enableWarnings. */ @java.lang.Override public boolean getEnableWarnings() { return enableWarnings_; } /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The enableWarnings to set. * @return This builder for chaining. */ public Builder setEnableWarnings(boolean value) { enableWarnings_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearEnableWarnings() { bitField0_ = (bitField0_ & ~0x00000008); enableWarnings_ = 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) private static final com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest(); } public static com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateCustomerSkAdNetworkConversionValueSchemaRequest> PARSER = new com.google.protobuf.AbstractParser<MutateCustomerSkAdNetworkConversionValueSchemaRequest>() { @java.lang.Override public MutateCustomerSkAdNetworkConversionValueSchemaRequest 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<MutateCustomerSkAdNetworkConversionValueSchemaRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateCustomerSkAdNetworkConversionValueSchemaRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
37,882
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/MutateCustomerSkAdNetworkConversionValueSchemaRequest.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/customer_sk_ad_network_conversion_value_schema_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; /** * <pre> * Request message for * [CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema][google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema]. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest} */ public final class MutateCustomerSkAdNetworkConversionValueSchemaRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) MutateCustomerSkAdNetworkConversionValueSchemaRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MutateCustomerSkAdNetworkConversionValueSchemaRequest.newBuilder() to construct. private MutateCustomerSkAdNetworkConversionValueSchemaRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MutateCustomerSkAdNetworkConversionValueSchemaRequest() { customerId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MutateCustomerSkAdNetworkConversionValueSchemaRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.class, com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.Builder.class); } private int bitField0_; public static final int CUSTOMER_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object customerId_ = ""; /** * <pre> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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.CustomerSkAdNetworkConversionValueSchemaOperation operation_; /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return Whether the operation field is set. */ @java.lang.Override public boolean hasOperation() { return ((bitField0_ & 0x00000001) != 0); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return The operation. */ @java.lang.Override public com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation getOperation() { return operation_ == null ? com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder getOperationOrBuilder() { return operation_ == null ? com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; 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 = 3;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } public static final int ENABLE_WARNINGS_FIELD_NUMBER = 4; private boolean enableWarnings_ = false; /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enableWarnings. */ @java.lang.Override public boolean getEnableWarnings() { return enableWarnings_; } 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 (validateOnly_ != false) { output.writeBool(3, validateOnly_); } if (enableWarnings_ != false) { output.writeBool(4, enableWarnings_); } 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 (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(3, validateOnly_); } if (enableWarnings_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, enableWarnings_); } 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest)) { return super.equals(obj); } com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest other = (com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (hasOperation() != other.hasOperation()) return false; if (hasOperation()) { if (!getOperation() .equals(other.getOperation())) return false; } if (getValidateOnly() != other.getValidateOnly()) return false; if (getEnableWarnings() != other.getEnableWarnings()) 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) + VALIDATE_ONLY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getValidateOnly()); hash = (37 * hash) + ENABLE_WARNINGS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getEnableWarnings()); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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 * [CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema][google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaService.MutateCustomerSkAdNetworkConversionValueSchema]. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.class, com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.Builder.class); } // Construct using com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.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; } validateOnly_ = false; enableWarnings_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaServiceProto.internal_static_google_ads_googleads_v21_services_MutateCustomerSkAdNetworkConversionValueSchemaRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest build() { com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest buildPartial() { com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest result = new com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest 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.validateOnly_ = validateOnly_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.enableWarnings_ = enableWarnings_; } 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest) { return mergeFrom((com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest other) { if (other == com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasOperation()) { mergeOperation(other.getOperation()); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } if (other.getEnableWarnings() != false) { setEnableWarnings(other.getEnableWarnings()); } 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: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 case 32: { enableWarnings_ = 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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The ID of the customer whose shared sets are being modified. * </pre> * * <code>string customer_id = 1;</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.CustomerSkAdNetworkConversionValueSchemaOperation operation_; private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder> operationBuilder_; /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return Whether the operation field is set. */ public boolean hasOperation() { return ((bitField0_ & 0x00000002) != 0); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> * @return The operation. */ public com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation getOperation() { if (operationBuilder_ == null) { return operation_ == null ? com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } else { return operationBuilder_.getMessage(); } } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder setOperation(com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation value) { if (operationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } operation_ = value; } else { operationBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder setOperation( com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder builderForValue) { if (operationBuilder_ == null) { operation_ = builderForValue.build(); } else { operationBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder mergeOperation(com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation value) { if (operationBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && operation_ != null && operation_ != com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance()) { getOperationBuilder().mergeFrom(value); } else { operation_ = value; } } else { operationBuilder_.mergeFrom(value); } if (operation_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public Builder clearOperation() { bitField0_ = (bitField0_ & ~0x00000002); operation_ = null; if (operationBuilder_ != null) { operationBuilder_.dispose(); operationBuilder_ = null; } onChanged(); return this; } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder getOperationBuilder() { bitField0_ |= 0x00000002; onChanged(); return getOperationFieldBuilder().getBuilder(); } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ public com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder getOperationOrBuilder() { if (operationBuilder_ != null) { return operationBuilder_.getMessageOrBuilder(); } else { return operation_ == null ? com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.getDefaultInstance() : operation_; } } /** * <pre> * The operation to perform. * </pre> * * <code>.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation operation = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder> getOperationFieldBuilder() { if (operationBuilder_ == null) { operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation, com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperation.Builder, com.google.ads.googleads.v21.services.CustomerSkAdNetworkConversionValueSchemaOperationOrBuilder>( getOperation(), getParentForChildren(), isClean()); operation_ = null; } return operationBuilder_; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</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 = 3;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 3;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000004); validateOnly_ = false; onChanged(); return this; } private boolean enableWarnings_ ; /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return The enableWarnings. */ @java.lang.Override public boolean getEnableWarnings() { return enableWarnings_; } /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @param value The enableWarnings to set. * @return This builder for chaining. */ public Builder setEnableWarnings(boolean value) { enableWarnings_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * Optional. If true, enables returning warnings. Warnings return error * messages and error codes without blocking the execution of the mutate * operation. * </pre> * * <code>bool enable_warnings = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * @return This builder for chaining. */ public Builder clearEnableWarnings() { bitField0_ = (bitField0_ & ~0x00000008); enableWarnings_ = 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.MutateCustomerSkAdNetworkConversionValueSchemaRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest) private static final com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest(); } public static com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MutateCustomerSkAdNetworkConversionValueSchemaRequest> PARSER = new com.google.protobuf.AbstractParser<MutateCustomerSkAdNetworkConversionValueSchemaRequest>() { @java.lang.Override public MutateCustomerSkAdNetworkConversionValueSchemaRequest 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<MutateCustomerSkAdNetworkConversionValueSchemaRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MutateCustomerSkAdNetworkConversionValueSchemaRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.services.MutateCustomerSkAdNetworkConversionValueSchemaRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
37,934
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/TargetPoolsAddInstanceRequest.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.TargetPoolsAddInstanceRequest} */ public final class TargetPoolsAddInstanceRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.TargetPoolsAddInstanceRequest) TargetPoolsAddInstanceRequestOrBuilder { private static final long serialVersionUID = 0L; // Use TargetPoolsAddInstanceRequest.newBuilder() to construct. private TargetPoolsAddInstanceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TargetPoolsAddInstanceRequest() { instances_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new TargetPoolsAddInstanceRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_TargetPoolsAddInstanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_TargetPoolsAddInstanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.class, com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.Builder.class); } public static final int INSTANCES_FIELD_NUMBER = 29097598; @SuppressWarnings("serial") private java.util.List<com.google.cloud.compute.v1.InstanceReference> instances_; /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ @java.lang.Override public java.util.List<com.google.cloud.compute.v1.InstanceReference> getInstancesList() { return instances_; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.compute.v1.InstanceReferenceOrBuilder> getInstancesOrBuilderList() { return instances_; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ @java.lang.Override public int getInstancesCount() { return instances_.size(); } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ @java.lang.Override public com.google.cloud.compute.v1.InstanceReference getInstances(int index) { return instances_.get(index); } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ @java.lang.Override public com.google.cloud.compute.v1.InstanceReferenceOrBuilder getInstancesOrBuilder(int index) { return instances_.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 < instances_.size(); i++) { output.writeMessage(29097598, instances_.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 < instances_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(29097598, instances_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest)) { return super.equals(obj); } com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest other = (com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest) obj; if (!getInstancesList().equals(other.getInstancesList())) 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 (getInstancesCount() > 0) { hash = (37 * hash) + INSTANCES_FIELD_NUMBER; hash = (53 * hash) + getInstancesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest 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.TargetPoolsAddInstanceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.TargetPoolsAddInstanceRequest) com.google.cloud.compute.v1.TargetPoolsAddInstanceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_TargetPoolsAddInstanceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_TargetPoolsAddInstanceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.class, com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.Builder.class); } // Construct using com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (instancesBuilder_ == null) { instances_ = java.util.Collections.emptyList(); } else { instances_ = null; instancesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); 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_TargetPoolsAddInstanceRequest_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest getDefaultInstanceForType() { return com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest build() { com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest buildPartial() { com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest result = new com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest result) { if (instancesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { instances_ = java.util.Collections.unmodifiableList(instances_); bitField0_ = (bitField0_ & ~0x00000001); } result.instances_ = instances_; } else { result.instances_ = instancesBuilder_.build(); } } private void buildPartial0(com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest 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.compute.v1.TargetPoolsAddInstanceRequest) { return mergeFrom((com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest other) { if (other == com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest.getDefaultInstance()) return this; if (instancesBuilder_ == null) { if (!other.instances_.isEmpty()) { if (instances_.isEmpty()) { instances_ = other.instances_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureInstancesIsMutable(); instances_.addAll(other.instances_); } onChanged(); } } else { if (!other.instances_.isEmpty()) { if (instancesBuilder_.isEmpty()) { instancesBuilder_.dispose(); instancesBuilder_ = null; instances_ = other.instances_; bitField0_ = (bitField0_ & ~0x00000001); instancesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getInstancesFieldBuilder() : null; } else { instancesBuilder_.addAllMessages(other.instances_); } } } 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 232780786: { com.google.cloud.compute.v1.InstanceReference m = input.readMessage( com.google.cloud.compute.v1.InstanceReference.parser(), extensionRegistry); if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.add(m); } else { instancesBuilder_.addMessage(m); } break; } // case 232780786 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.compute.v1.InstanceReference> instances_ = java.util.Collections.emptyList(); private void ensureInstancesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { instances_ = new java.util.ArrayList<com.google.cloud.compute.v1.InstanceReference>(instances_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.InstanceReference, com.google.cloud.compute.v1.InstanceReference.Builder, com.google.cloud.compute.v1.InstanceReferenceOrBuilder> instancesBuilder_; /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public java.util.List<com.google.cloud.compute.v1.InstanceReference> getInstancesList() { if (instancesBuilder_ == null) { return java.util.Collections.unmodifiableList(instances_); } else { return instancesBuilder_.getMessageList(); } } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public int getInstancesCount() { if (instancesBuilder_ == null) { return instances_.size(); } else { return instancesBuilder_.getCount(); } } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public com.google.cloud.compute.v1.InstanceReference getInstances(int index) { if (instancesBuilder_ == null) { return instances_.get(index); } else { return instancesBuilder_.getMessage(index); } } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder setInstances(int index, com.google.cloud.compute.v1.InstanceReference value) { if (instancesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstancesIsMutable(); instances_.set(index, value); onChanged(); } else { instancesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder setInstances( int index, com.google.cloud.compute.v1.InstanceReference.Builder builderForValue) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.set(index, builderForValue.build()); onChanged(); } else { instancesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder addInstances(com.google.cloud.compute.v1.InstanceReference value) { if (instancesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstancesIsMutable(); instances_.add(value); onChanged(); } else { instancesBuilder_.addMessage(value); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder addInstances(int index, com.google.cloud.compute.v1.InstanceReference value) { if (instancesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureInstancesIsMutable(); instances_.add(index, value); onChanged(); } else { instancesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder addInstances( com.google.cloud.compute.v1.InstanceReference.Builder builderForValue) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.add(builderForValue.build()); onChanged(); } else { instancesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder addInstances( int index, com.google.cloud.compute.v1.InstanceReference.Builder builderForValue) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.add(index, builderForValue.build()); onChanged(); } else { instancesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder addAllInstances( java.lang.Iterable<? extends com.google.cloud.compute.v1.InstanceReference> values) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, instances_); onChanged(); } else { instancesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder clearInstances() { if (instancesBuilder_ == null) { instances_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { instancesBuilder_.clear(); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public Builder removeInstances(int index) { if (instancesBuilder_ == null) { ensureInstancesIsMutable(); instances_.remove(index); onChanged(); } else { instancesBuilder_.remove(index); } return this; } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public com.google.cloud.compute.v1.InstanceReference.Builder getInstancesBuilder(int index) { return getInstancesFieldBuilder().getBuilder(index); } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public com.google.cloud.compute.v1.InstanceReferenceOrBuilder getInstancesOrBuilder(int index) { if (instancesBuilder_ == null) { return instances_.get(index); } else { return instancesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public java.util.List<? extends com.google.cloud.compute.v1.InstanceReferenceOrBuilder> getInstancesOrBuilderList() { if (instancesBuilder_ != null) { return instancesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(instances_); } } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public com.google.cloud.compute.v1.InstanceReference.Builder addInstancesBuilder() { return getInstancesFieldBuilder() .addBuilder(com.google.cloud.compute.v1.InstanceReference.getDefaultInstance()); } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public com.google.cloud.compute.v1.InstanceReference.Builder addInstancesBuilder(int index) { return getInstancesFieldBuilder() .addBuilder(index, com.google.cloud.compute.v1.InstanceReference.getDefaultInstance()); } /** * * * <pre> * A full or partial URL to an instance to add to this target pool. This can be a full or partial URL. For example, the following are valid URLs: - https://www.googleapis.com/compute/v1/projects/project-id/zones/zone /instances/instance-name - projects/project-id/zones/zone/instances/instance-name - zones/zone/instances/instance-name * </pre> * * <code>repeated .google.cloud.compute.v1.InstanceReference instances = 29097598;</code> */ public java.util.List<com.google.cloud.compute.v1.InstanceReference.Builder> getInstancesBuilderList() { return getInstancesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.InstanceReference, com.google.cloud.compute.v1.InstanceReference.Builder, com.google.cloud.compute.v1.InstanceReferenceOrBuilder> getInstancesFieldBuilder() { if (instancesBuilder_ == null) { instancesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.compute.v1.InstanceReference, com.google.cloud.compute.v1.InstanceReference.Builder, com.google.cloud.compute.v1.InstanceReferenceOrBuilder>( instances_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); instances_ = null; } return instancesBuilder_; } @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.TargetPoolsAddInstanceRequest) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.TargetPoolsAddInstanceRequest) private static final com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest(); } public static com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TargetPoolsAddInstanceRequest> PARSER = new com.google.protobuf.AbstractParser<TargetPoolsAddInstanceRequest>() { @java.lang.Override public TargetPoolsAddInstanceRequest 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<TargetPoolsAddInstanceRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TargetPoolsAddInstanceRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.TargetPoolsAddInstanceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hive
37,840
ql/src/java/org/apache/hadoop/hive/ql/parse/type/RexNodeExprFactory.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.hive.ql.parse.type; import com.google.common.collect.ImmutableList; import java.math.BigDecimal; import java.nio.charset.Charset; import java.time.Instant; import java.time.ZoneId; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.calcite.avatica.util.TimeUnit; import org.apache.calcite.plan.RelOptCluster; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexInputRef; import org.apache.calcite.rex.RexLiteral; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexSubQuery; import org.apache.calcite.rex.RexUtil; import org.apache.calcite.sql.SqlCollation; import org.apache.calcite.sql.SqlFunction; import org.apache.calcite.sql.SqlFunctionCategory; import org.apache.calcite.sql.SqlIntervalQualifier; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.fun.SqlQuantifyOperator; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.sql.type.SqlTypeFamily; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.calcite.sql.type.ArraySqlType; import org.apache.calcite.util.ConversionUtil; import org.apache.calcite.util.DateString; import org.apache.calcite.util.NlsString; import org.apache.calcite.util.TimestampString; import org.apache.commons.lang3.math.NumberUtils; import org.apache.hadoop.hive.common.type.Date; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.common.type.HiveIntervalDayTime; import org.apache.hadoop.hive.common.type.HiveIntervalYearMonth; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.common.type.Timestamp; import org.apache.hadoop.hive.common.type.TimestampTZ; import org.apache.hadoop.hive.common.type.TimestampTZUtil; import org.apache.hadoop.hive.ql.ErrorMsg; import org.apache.hadoop.hive.ql.exec.ColumnInfo; import org.apache.hadoop.hive.ql.exec.FunctionInfo; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException.UnsupportedFeature; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSubquerySemanticException; import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil; import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveRexExprList; import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveComponentAccess; import org.apache.hadoop.hive.ql.optimizer.calcite.translator.TypeConverter; import org.apache.hadoop.hive.ql.parse.ASTNode; import org.apache.hadoop.hive.ql.parse.HiveParser; import org.apache.hadoop.hive.ql.parse.QBSubQueryParseInfo; import org.apache.hadoop.hive.ql.parse.RowResolver; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.plan.SubqueryType; import org.apache.hadoop.hive.serde.serdeConstants; import org.apache.hadoop.hive.serde2.objectinspector.ConstantObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils.PrimitiveTypeEntry; import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.StructTypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory; import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils; import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Expression factory for Calcite {@link RexNode}. */ public class RexNodeExprFactory extends ExprFactory<RexNode> { private static final Logger LOG = LoggerFactory.getLogger(RexNodeExprFactory.class); private final RexBuilder rexBuilder; private final FunctionHelper functionHelper; public RexNodeExprFactory(RexBuilder rexBuilder) { this.rexBuilder = rexBuilder; this.functionHelper = new HiveFunctionHelper(rexBuilder); } /** * {@inheritDoc} */ @Override protected boolean isExprInstance(Object o) { return o instanceof RexNode; } /** * {@inheritDoc} */ @Override protected RexNode toExpr(ColumnInfo colInfo, RowResolver rowResolver, int offset) throws CalciteSemanticException { ObjectInspector inspector = colInfo.getObjectInspector(); if (inspector instanceof ConstantObjectInspector && inspector instanceof PrimitiveObjectInspector) { return toPrimitiveConstDesc(colInfo, inspector, rexBuilder); } int index = rowResolver.getPosition(colInfo.getInternalName()); if (index < 0) { throw new CalciteSemanticException("Unexpected error: Cannot find column"); } return rexBuilder.makeInputRef( TypeConverter.convert(colInfo.getType(), colInfo.isNullable(), rexBuilder.getTypeFactory()), index + offset); } private static RexNode toPrimitiveConstDesc( ColumnInfo colInfo, ObjectInspector inspector, RexBuilder rexBuilder) throws CalciteSemanticException { Object constant = ((ConstantObjectInspector) inspector).getWritableConstantValue(); return rexBuilder.makeLiteral(constant, TypeConverter.convert(colInfo.getType(), rexBuilder.getTypeFactory()), false); } /** * {@inheritDoc} */ @Override protected RexNode createColumnRefExpr(ColumnInfo colInfo, RowResolver rowResolver, int offset) throws CalciteSemanticException { int index = rowResolver.getPosition(colInfo.getInternalName()); return rexBuilder.makeInputRef( TypeConverter.convert(colInfo.getType(), rexBuilder.getTypeFactory()), index + offset); } /** * {@inheritDoc} */ @Override protected RexNode createColumnRefExpr(ColumnInfo colInfo, List<RowResolver> rowResolverList) throws SemanticException { int index = getPosition(colInfo, rowResolverList); return rexBuilder.makeInputRef( TypeConverter.convert(colInfo.getType(), rexBuilder.getTypeFactory()), index); } private int getPosition(ColumnInfo colInfo, List<RowResolver> rowResolverList) throws SemanticException { int position = 0; for (RowResolver rr: rowResolverList) { ColumnInfo tmp = rr.get(colInfo.getTabAlias(), colInfo.getAlias()); if (tmp == null) { // if column is not present in the RR, increment position by size of RR position += rr.getColumnInfos().size(); } else { // if column is present, increment position by the position of the column in RR // and return early. position += rr.getPosition(tmp.getInternalName()); return position; } } // If we are out of the for loop, then the column is not present in any RR throw new CalciteSemanticException("Could not resolve column name"); } /** * {@inheritDoc} */ @Override protected RexNode createNullConstantExpr() { return rexBuilder.makeNullLiteral( rexBuilder.getTypeFactory().createSqlType(SqlTypeName.NULL)); } /** * {@inheritDoc} */ @Override protected RexNode createDynamicParamExpr(int index) { return rexBuilder.makeDynamicParam( rexBuilder.getTypeFactory().createSqlType(SqlTypeName.NULL), index); } /** * {@inheritDoc} */ @Override protected RexNode createBooleanConstantExpr(String value) { Boolean b = value != null ? Boolean.valueOf(value) : null; return rexBuilder.makeLiteral(b, rexBuilder.getTypeFactory().createSqlType(SqlTypeName.BOOLEAN), false); } /** * {@inheritDoc} */ @Override protected RexNode createBigintConstantExpr(String value) { return rexBuilder.makeLiteral( new BigDecimal(Long.valueOf(value)), rexBuilder.getTypeFactory().createSqlType(SqlTypeName.BIGINT), false); } /** * {@inheritDoc} */ @Override protected RexNode createIntConstantExpr(String value) { return rexBuilder.makeLiteral( new BigDecimal(Integer.valueOf(value)), rexBuilder.getTypeFactory().createSqlType(SqlTypeName.INTEGER), false); } /** * {@inheritDoc} */ @Override protected RexNode createSmallintConstantExpr(String value) { return rexBuilder.makeLiteral( new BigDecimal(Short.valueOf(value)), rexBuilder.getTypeFactory().createSqlType(SqlTypeName.SMALLINT), false); } /** * {@inheritDoc} */ @Override protected RexNode createTinyintConstantExpr(String value) { return rexBuilder.makeLiteral( new BigDecimal(Byte.valueOf(value)), rexBuilder.getTypeFactory().createSqlType(SqlTypeName.TINYINT), false); } /** * {@inheritDoc} */ @Override protected RexNode createFloatConstantExpr(String value) { Float f = Float.valueOf(value); return rexBuilder.makeApproxLiteral( new BigDecimal(Float.toString(f)), rexBuilder.getTypeFactory().createSqlType(SqlTypeName.FLOAT)); } /** * {@inheritDoc} */ @Override protected RexNode createDoubleConstantExpr(String value) throws SemanticException { Double d = Double.valueOf(value); // TODO: The best solution is to support NaN in expression reduction. if (Double.isNaN(d)) { throw new CalciteSemanticException("NaN", UnsupportedFeature.Invalid_decimal); } return rexBuilder.makeApproxLiteral( new BigDecimal(Double.toString(d)), rexBuilder.getTypeFactory().createSqlType(SqlTypeName.DOUBLE)); } /** * {@inheritDoc} */ @Override protected RexNode createDecimalConstantExpr(String value, boolean allowNullValueConstantExpr) { HiveDecimal hd = HiveDecimal.create(value); if (!allowNullValueConstantExpr && hd == null) { return null; } BigDecimal bd = hd != null ? hd.bigDecimalValue() : null; DecimalTypeInfo type = adjustType(bd); return rexBuilder.makeExactLiteral( bd, TypeConverter.convert(type, rexBuilder.getTypeFactory())); } @Override protected TypeInfo adjustConstantType(PrimitiveTypeInfo targetType, Object constantValue) { if (PrimitiveObjectInspectorUtils.decimalTypeEntry.equals(targetType.getPrimitiveTypeEntry())) { return adjustType((BigDecimal) constantValue); } return targetType; } private DecimalTypeInfo adjustType(BigDecimal bd) { int prec = 1; int scale = 0; if (bd != null) { prec = bd.precision(); scale = bd.scale(); if (prec < scale) { // This can happen for numbers less than 0.1 // For 0.001234: prec=4, scale=6 // In this case, we'll set the type to have the same precision as the scale. prec = scale; } } return TypeInfoFactory.getDecimalTypeInfo(prec, scale); } /** * {@inheritDoc} */ @Override protected Object interpretConstantAsPrimitive(PrimitiveTypeInfo targetType, Object constantValue, PrimitiveTypeInfo sourceType, boolean isEqual) { // Extract string value if necessary Object constantToInterpret = constantValue; if (constantValue instanceof NlsString) { constantToInterpret = ((NlsString) constantValue).getValue(); } if (constantToInterpret instanceof Number || constantToInterpret instanceof String) { try { PrimitiveTypeEntry primitiveTypeEntry = targetType.getPrimitiveTypeEntry(); if (PrimitiveObjectInspectorUtils.intTypeEntry.equals(primitiveTypeEntry)) { return toBigDecimal(constantToInterpret.toString()).intValueExact(); } else if (PrimitiveObjectInspectorUtils.longTypeEntry.equals(primitiveTypeEntry)) { return toBigDecimal(constantToInterpret.toString()).longValueExact(); } else if (PrimitiveObjectInspectorUtils.doubleTypeEntry.equals(primitiveTypeEntry)) { return toBigDecimal(constantToInterpret.toString()); } else if (PrimitiveObjectInspectorUtils.floatTypeEntry.equals(primitiveTypeEntry)) { return toBigDecimal(constantToInterpret.toString()); } else if (PrimitiveObjectInspectorUtils.byteTypeEntry.equals(primitiveTypeEntry)) { return toBigDecimal(constantToInterpret.toString()).byteValueExact(); } else if (PrimitiveObjectInspectorUtils.shortTypeEntry.equals(primitiveTypeEntry)) { return toBigDecimal(constantToInterpret.toString()).shortValueExact(); } else if (PrimitiveObjectInspectorUtils.decimalTypeEntry.equals(primitiveTypeEntry)) { HiveDecimal decimal = HiveDecimal.create(constantToInterpret.toString()); return decimal != null ? decimal.bigDecimalValue() : null; } } catch (NumberFormatException | ArithmeticException nfe) { if (!isEqual && (constantToInterpret instanceof Number || NumberUtils.isNumber(constantToInterpret.toString()))) { // The target is a number, if constantToInterpret can be interpreted as a number, // return the constantToInterpret directly, GenericUDFBaseCompare will do // type conversion for us. return constantToInterpret; } LOG.trace("Failed to narrow type of constant", nfe); return null; } } if (constantToInterpret instanceof BigDecimal) { return constantToInterpret; } String constTypeInfoName = sourceType.getTypeName(); if (constTypeInfoName.equalsIgnoreCase(serdeConstants.STRING_TYPE_NAME)) { // because a comparison against a "string" will happen in "string" type. // to avoid unintentional comparisons in "string" // constants which are representing char/varchar values must be converted to the // appropriate type. if (targetType instanceof CharTypeInfo) { final String constValue = constantToInterpret.toString(); final int length = TypeInfoUtils.getCharacterLengthForType(targetType); HiveChar newValue = new HiveChar(constValue, length); HiveChar maxCharConst = new HiveChar(constValue, HiveChar.MAX_CHAR_LENGTH); if (maxCharConst.equals(newValue)) { return makeHiveUnicodeString(newValue.getValue()); } else { return null; } } if (targetType instanceof VarcharTypeInfo) { final String constValue = constantToInterpret.toString(); final int length = TypeInfoUtils.getCharacterLengthForType(targetType); HiveVarchar newValue = new HiveVarchar(constValue, length); HiveVarchar maxCharConst = new HiveVarchar(constValue, HiveVarchar.MAX_VARCHAR_LENGTH); if (maxCharConst.equals(newValue)) { return makeHiveUnicodeString(newValue.getValue()); } else { return null; } } } return constantValue; } private BigDecimal toBigDecimal(String val) { if (!NumberUtils.isNumber(val)) { throw new NumberFormatException("The given string is not a valid number: " + val); } return new BigDecimal(val.replaceAll("[dDfFlL]$", "")); } /** * {@inheritDoc} */ @Override protected RexLiteral createStringConstantExpr(String value) { RelDataType stringType = rexBuilder.getTypeFactory().createTypeWithCharsetAndCollation( rexBuilder.getTypeFactory().createSqlType(SqlTypeName.VARCHAR, Integer.MAX_VALUE), Charset.forName(ConversionUtil.NATIVE_UTF16_CHARSET_NAME), SqlCollation.IMPLICIT); // Note. Though we pass allowCast=true as parameter, this method will return a // VARCHAR literal without a CAST. return (RexLiteral) rexBuilder.makeLiteral( makeHiveUnicodeString(value), stringType, true); } /** * {@inheritDoc} */ @Override protected RexLiteral createDateConstantExpr(String value) { Date d = Date.valueOf(value); return rexBuilder.makeDateLiteral( DateString.fromDaysSinceEpoch(d.toEpochDay())); } /** * {@inheritDoc} */ @Override protected RexLiteral createTimestampConstantExpr(String value) { Timestamp t = Timestamp.valueOf(value); return (RexLiteral) rexBuilder.makeLiteral( TimestampString.fromMillisSinceEpoch(t.toEpochMilli()).withNanos(t.getNanos()), rexBuilder.getTypeFactory().createSqlType( SqlTypeName.TIMESTAMP, rexBuilder.getTypeFactory().getTypeSystem().getDefaultPrecision(SqlTypeName.TIMESTAMP)), false); } /** * {@inheritDoc} */ @Override protected RexLiteral createTimestampLocalTimeZoneConstantExpr(String value, ZoneId zoneId) { TimestampTZ t = TimestampTZUtil.parse(value); final TimestampString tsLocalTZString; if (value == null) { tsLocalTZString = null; } else { Instant i = t.getZonedDateTime().toInstant(); tsLocalTZString = TimestampString .fromMillisSinceEpoch(i.toEpochMilli()) .withNanos(i.getNano()); } return rexBuilder.makeTimestampWithLocalTimeZoneLiteral( tsLocalTZString, rexBuilder.getTypeFactory().getTypeSystem().getDefaultPrecision(SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE)); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalYearMonthConstantExpr(String value) { BigDecimal totalMonths = BigDecimal.valueOf(HiveIntervalYearMonth.valueOf(value).getTotalMonths()); return rexBuilder.makeIntervalLiteral(totalMonths, new SqlIntervalQualifier(TimeUnit.YEAR, TimeUnit.MONTH, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalDayTimeConstantExpr(String value) { HiveIntervalDayTime v = HiveIntervalDayTime.valueOf(value); BigDecimal secsValueBd = BigDecimal .valueOf(v.getTotalSeconds() * 1000); BigDecimal nanosValueBd = BigDecimal.valueOf((v).getNanos(), 6); return rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd), new SqlIntervalQualifier(TimeUnit.MILLISECOND, null, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalYearConstantExpr(String value) { HiveIntervalYearMonth v = new HiveIntervalYearMonth(Integer.parseInt(value), 0); BigDecimal totalMonths = BigDecimal.valueOf(v.getTotalMonths()); return rexBuilder.makeIntervalLiteral(totalMonths, new SqlIntervalQualifier(TimeUnit.YEAR, TimeUnit.MONTH, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalMonthConstantExpr(String value) { BigDecimal totalMonths = BigDecimal.valueOf(Integer.parseInt(value)); return rexBuilder.makeIntervalLiteral(totalMonths, new SqlIntervalQualifier(TimeUnit.YEAR, TimeUnit.MONTH, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalDayConstantExpr(String value) { HiveIntervalDayTime v = new HiveIntervalDayTime(Integer.parseInt(value), 0, 0, 0, 0); BigDecimal secsValueBd = BigDecimal .valueOf(v.getTotalSeconds() * 1000); BigDecimal nanosValueBd = BigDecimal.valueOf((v).getNanos(), 6); return rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd), new SqlIntervalQualifier(TimeUnit.MILLISECOND, null, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalHourConstantExpr(String value) { HiveIntervalDayTime v = new HiveIntervalDayTime(0, Integer.parseInt(value), 0, 0, 0); BigDecimal secsValueBd = BigDecimal .valueOf(v.getTotalSeconds() * 1000); BigDecimal nanosValueBd = BigDecimal.valueOf((v).getNanos(), 6); return rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd), new SqlIntervalQualifier(TimeUnit.MILLISECOND, null, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalMinuteConstantExpr(String value) { HiveIntervalDayTime v = new HiveIntervalDayTime(0, 0, Integer.parseInt(value), 0, 0); BigDecimal secsValueBd = BigDecimal .valueOf(v.getTotalSeconds() * 1000); BigDecimal nanosValueBd = BigDecimal.valueOf((v).getNanos(), 6); return rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd), new SqlIntervalQualifier(TimeUnit.MILLISECOND, null, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexLiteral createIntervalSecondConstantExpr(String value) { BigDecimal bd = new BigDecimal(value); BigDecimal bdSeconds = new BigDecimal(bd.toBigInteger()); BigDecimal bdNanos = bd.subtract(bdSeconds); HiveIntervalDayTime v = new HiveIntervalDayTime(0, 0, 0, bdSeconds.intValueExact(), bdNanos.multiply(NANOS_PER_SEC_BD).intValue()); BigDecimal secsValueBd = BigDecimal .valueOf(v.getTotalSeconds() * 1000); BigDecimal nanosValueBd = BigDecimal.valueOf((v).getNanos(), 6); return rexBuilder.makeIntervalLiteral(secsValueBd.add(nanosValueBd), new SqlIntervalQualifier(TimeUnit.MILLISECOND, null, new SqlParserPos(1, 1))); } /** * {@inheritDoc} */ @Override protected RexNode createStructExpr(TypeInfo typeInfo, List<RexNode> operands) throws CalciteSemanticException { assert typeInfo instanceof StructTypeInfo; return rexBuilder.makeCall( TypeConverter.convert(typeInfo, rexBuilder.getTypeFactory()), SqlStdOperatorTable.ROW, operands); } /** * {@inheritDoc} */ @Override protected RexNode createConstantExpr(TypeInfo typeInfo, Object constantValue) throws CalciteSemanticException { if (typeInfo instanceof StructTypeInfo) { List<TypeInfo> typeList = ((StructTypeInfo) typeInfo).getAllStructFieldTypeInfos(); List<Object> objectList = (List<Object>) constantValue; List<RexNode> operands = new ArrayList<>(); for (int i = 0; i < typeList.size(); i++) { operands.add( rexBuilder.makeLiteral( objectList.get(i), TypeConverter.convert(typeList.get(i), rexBuilder.getTypeFactory()), false)); } return rexBuilder.makeCall( TypeConverter.convert(typeInfo, rexBuilder.getTypeFactory()), SqlStdOperatorTable.ROW, operands); } RelDataType finalType = TypeConverter.convert(typeInfo, rexBuilder.getTypeFactory()); boolean allowCast = finalType.getFamily() == SqlTypeFamily.CHARACTER; return rexBuilder.makeLiteral(constantValue, finalType, allowCast); } /** * {@inheritDoc} */ @Override protected RexNode createNestedColumnRefExpr( TypeInfo typeInfo, RexNode expr, String fieldName, Boolean isList) throws CalciteSemanticException { if (expr.getType().isStruct()) { // regular case of accessing nested field in a column return rexBuilder.makeFieldAccess(expr, fieldName, true); } else if (expr.getType().getComponentType() != null) { RexNode wrap = rexBuilder.makeCall(expr.getType().getComponentType(), HiveComponentAccess.COMPONENT_ACCESS, Collections.singletonList(expr)); return createNestedColumnRefExpr(typeInfo, wrap, fieldName, expr.getType().getComponentType() instanceof ArraySqlType); } else { throw new CalciteSemanticException("Unexpected rexnode : " + expr.getClass().getCanonicalName()); } } /** * {@inheritDoc} */ @Override protected RexNode createFuncCallExpr(TypeInfo typeInfo, FunctionInfo functionInfo, String funcText, List<RexNode> inputs) throws SemanticException { // 2) Compute return type RelDataType returnType; if (typeInfo != null) { returnType = TypeConverter.convert(typeInfo, rexBuilder.getTypeFactory()); } else { returnType = functionHelper.getReturnType(functionInfo, inputs); } // 3) Convert inputs (if necessary) List<RexNode> newInputs = functionHelper.convertInputs( functionInfo, inputs, returnType); // 4) Return Calcite function return functionHelper.getExpression( funcText, functionInfo, newInputs, returnType); } /** * {@inheritDoc} */ @Override protected RexNode createExprsListExpr() { return new HiveRexExprList(); } /** * {@inheritDoc} */ @Override protected void addExprToExprsList(RexNode columnList, RexNode expr) { HiveRexExprList l = (HiveRexExprList) columnList; l.addExpression(expr); } /** * {@inheritDoc} */ @Override protected boolean isConstantExpr(Object o) { return o instanceof RexLiteral; } /** * {@inheritDoc} */ @Override protected boolean isFuncCallExpr(Object o) { return o instanceof RexCall; } /** * {@inheritDoc} */ @Override protected Object getConstantValue(RexNode expr) { if (expr.getType().getSqlTypeName() == SqlTypeName.ROW) { List<Object> res = new ArrayList<>(); for (RexNode node : ((RexCall) expr).getOperands()) { res.add(((RexLiteral) node).getValue4()); } return res; } return ((RexLiteral) expr).getValue4(); } /** * {@inheritDoc} */ @Override protected String getConstantValueAsString(RexNode expr) { return ((RexLiteral) expr).getValueAs(String.class); } /** * {@inheritDoc} */ @Override protected boolean isColumnRefExpr(Object o) { return o instanceof RexNode && RexUtil.isReferenceOrAccess((RexNode) o, true); } /** * {@inheritDoc} */ @Override protected String getColumnName(RexNode expr, RowResolver rowResolver) { int index = ((RexInputRef) expr).getIndex(); return rowResolver.getColumnInfos().get(index).getInternalName(); } /** * {@inheritDoc} */ @Override protected boolean isExprsListExpr(Object o) { return o instanceof HiveRexExprList; } /** * {@inheritDoc} */ @Override protected List<RexNode> getExprChildren(RexNode expr) { if (expr instanceof RexCall) { return ((RexCall) expr).getOperands(); } else if (expr instanceof HiveRexExprList) { return ((HiveRexExprList) expr).getExpressions(); } return new ArrayList<>(); } /** * {@inheritDoc} */ @Override protected TypeInfo getTypeInfo(RexNode expr) { return expr.isA(SqlKind.LITERAL) ? TypeConverter.convertLiteralType((RexLiteral) expr) : TypeConverter.convert(expr.getType()); } /** * {@inheritDoc} */ @Override protected List<TypeInfo> getStructTypeInfoList(RexNode expr) { StructTypeInfo structTypeInfo = (StructTypeInfo) TypeConverter.convert(expr.getType()); return structTypeInfo.getAllStructFieldTypeInfos(); } /** * {@inheritDoc} */ @Override protected List<String> getStructNameList(RexNode expr) { StructTypeInfo structTypeInfo = (StructTypeInfo) TypeConverter.convert(expr.getType()); return structTypeInfo.getAllStructFieldNames(); } /** * {@inheritDoc} */ @Override protected boolean isORFuncCallExpr(RexNode expr) { return expr.isA(SqlKind.OR); } /** * {@inheritDoc} */ @Override protected boolean isANDFuncCallExpr(RexNode expr) { return expr.isA(SqlKind.AND); } /** * {@inheritDoc} */ @Override protected boolean isConsistentWithinQuery(FunctionInfo fi) { return functionHelper.isConsistentWithinQuery(fi); } /** * {@inheritDoc} */ @Override protected boolean isStateful(FunctionInfo fi) { return functionHelper.isStateful(fi); } /** * {@inheritDoc} */ @Override protected boolean isPOSITIVEFuncCallExpr(RexNode expr) { return expr.isA(SqlKind.PLUS_PREFIX); } /** * {@inheritDoc} */ @Override protected boolean isNEGATIVEFuncCallExpr(RexNode expr) { return expr.isA(SqlKind.MINUS_PREFIX); } /** * {@inheritDoc} */ @Override protected RexNode setTypeInfo(RexNode expr, TypeInfo type) throws CalciteSemanticException { RelDataType t = TypeConverter.convert(type, rexBuilder.getTypeFactory()); if (expr instanceof RexCall) { RexCall call = (RexCall) expr; return rexBuilder.makeCall(t, call.getOperator(), call.getOperands()); } else if (expr instanceof RexInputRef) { RexInputRef inputRef = (RexInputRef) expr; return rexBuilder.makeInputRef(t, inputRef.getIndex()); } else if (expr instanceof RexLiteral) { RexLiteral literal = (RexLiteral) expr; return rexBuilder.makeLiteral(RexLiteral.value(literal), t, false); } throw new RuntimeException("Unsupported expression type: " + expr.getClass().getCanonicalName()); } /** * {@inheritDoc} */ @Override protected boolean convertCASEIntoCOALESCEFuncCallExpr(FunctionInfo fi, List<RexNode> inputs) { return false; } /** * {@inheritDoc} */ @Override protected RexNode foldExpr(RexNode expr) { return functionHelper.foldExpression(expr); } /** * {@inheritDoc} */ @Override protected boolean isSTRUCTFuncCallExpr(RexNode expr) { return expr instanceof RexCall && ((RexCall) expr).getOperator() == SqlStdOperatorTable.ROW; } /** * {@inheritDoc} */ @Override protected boolean isAndFunction(FunctionInfo fi) { return functionHelper.isAndFunction(fi); } /** * {@inheritDoc} */ @Override protected boolean isOrFunction(FunctionInfo fi) { return functionHelper.isOrFunction(fi); } /** * {@inheritDoc} */ @Override protected boolean isInFunction(FunctionInfo fi) { return functionHelper.isInFunction(fi); } /** * {@inheritDoc} */ @Override protected boolean isCompareFunction(FunctionInfo fi) { return functionHelper.isCompareFunction(fi); } /** * {@inheritDoc} */ @Override protected boolean isEqualFunction(FunctionInfo fi) { return functionHelper.isEqualFunction(fi); } @Override protected boolean isNSCompareFunction(FunctionInfo fi) { return functionHelper.isNSCompareFunction(fi); } /** * {@inheritDoc} */ @Override protected boolean isConstantStruct(RexNode expr) { return expr.getType().getSqlTypeName() == SqlTypeName.ROW && HiveCalciteUtil.isLiteral(expr); } /** * {@inheritDoc} */ @Override protected RexNode createSubqueryExpr(TypeCheckCtx ctx, ASTNode expr, SubqueryType subqueryType, Object[] inputs) throws SemanticException { // subqueryToRelNode might be null if subquery expression anywhere other than // as expected in filter (where/having). We should throw an appropriate error // message Map<ASTNode, QBSubQueryParseInfo> subqueryToRelNode = ctx.getSubqueryToRelNode(); if (subqueryToRelNode == null) { throw new CalciteSubquerySemanticException(ErrorMsg.UNSUPPORTED_SUBQUERY_EXPRESSION.getMsg( " Currently SubQuery expressions are only allowed as " + "Where and Having Clause predicates")); } ASTNode subqueryOp = (ASTNode) expr.getChild(0); RelNode subqueryRel = subqueryToRelNode.get(expr).getSubQueryRelNode(); // For now because subquery is only supported in filter // we will create subquery expression of boolean type switch (subqueryType) { case EXISTS: { if (subqueryToRelNode.get(expr).hasFullAggregate()) { return createConstantExpr(TypeInfoFactory.booleanTypeInfo, true); } return RexSubQuery.exists(subqueryRel); } case IN: { assert (inputs[2] != null); /* * Check.5.h :: For In and Not In the SubQuery must implicitly or * explicitly only contain one select item. */ if(subqueryRel.getRowType().getFieldCount() > 1) { throw new CalciteSubquerySemanticException(ErrorMsg.INVALID_SUBQUERY_EXPRESSION.getMsg( "SubQuery can contain only 1 item in Select List.")); } //create RexNode for LHS RexNode lhs = (RexNode) inputs[2]; //create RexSubQuery node return RexSubQuery.in(subqueryRel, ImmutableList.<RexNode>of(lhs)); } case SCALAR: { // only single subquery expr is supported if (subqueryRel.getRowType().getFieldCount() != 1) { throw new CalciteSubquerySemanticException(ErrorMsg.INVALID_SUBQUERY_EXPRESSION.getMsg( "More than one column expression in subquery")); } if(subqueryRel.getRowType().getFieldCount() > 1) { throw new CalciteSubquerySemanticException(ErrorMsg.INVALID_SUBQUERY_EXPRESSION.getMsg( "SubQuery can contain only 1 item in Select List.")); } //create RexSubQuery node return RexSubQuery.scalar(subqueryRel); } case SOME: case ALL: { assert (inputs[2] != null); //create RexNode for LHS RexNode lhs = (RexNode) inputs[2]; return convertSubquerySomeAll(subqueryRel.getCluster(), (ASTNode) subqueryOp.getChild(1), subqueryType, subqueryRel, lhs); } default: return null; } } /** * {@inheritDoc} */ @Override protected FunctionInfo getFunctionInfo(String funcName) throws SemanticException { return functionHelper.getFunctionInfo(funcName); } @Override protected RexNode replaceFieldNamesInStruct(RexNode expr, List<String> newFieldNames) { if (newFieldNames.isEmpty()) { return expr; } RexCall structCall = (RexCall) expr; List<RelDataType> newTypes = structCall.operands.stream().map(RexNode::getType).collect(Collectors.toList()); RelDataType newType = rexBuilder.getTypeFactory().createStructType(newTypes, newFieldNames); return rexBuilder.makeCall(newType, structCall.op, structCall.operands); } private static void throwInvalidSubqueryError(final ASTNode comparisonOp) throws SemanticException { throw new CalciteSubquerySemanticException(ErrorMsg.INVALID_SUBQUERY_EXPRESSION.getMsg( "Invalid operator:" + comparisonOp.toString())); } public static RexNode convertSubquerySomeAll(final RelOptCluster cluster, final ASTNode comparisonOp, final SubqueryType subqueryType, final RelNode subqueryRel, final RexNode rexNodeLhs) throws SemanticException { SqlQuantifyOperator quantifyOperator = null; switch (comparisonOp.getType()) { case HiveParser.EQUAL: if(subqueryType == SubqueryType.ALL) { throwInvalidSubqueryError(comparisonOp); } quantifyOperator = SqlStdOperatorTable.SOME_EQ; break; case HiveParser.LESSTHAN: quantifyOperator = SqlStdOperatorTable.SOME_LT; break; case HiveParser.LESSTHANOREQUALTO: quantifyOperator = SqlStdOperatorTable.SOME_LE; break; case HiveParser.GREATERTHAN: quantifyOperator = SqlStdOperatorTable.SOME_GT; break; case HiveParser.GREATERTHANOREQUALTO: quantifyOperator = SqlStdOperatorTable.SOME_GE; break; case HiveParser.NOTEQUAL: if(subqueryType == SubqueryType.SOME) { throwInvalidSubqueryError(comparisonOp); } quantifyOperator = SqlStdOperatorTable.SOME_NE; break; default: throw new CalciteSubquerySemanticException(ErrorMsg.INVALID_SUBQUERY_EXPRESSION.getMsg( "Invalid operator:" + comparisonOp.toString())); } if(subqueryType == SubqueryType.ALL) { quantifyOperator = SqlStdOperatorTable.some(quantifyOperator.comparisonKind.negateNullSafe()); } RexNode someQuery = getSomeSubquery(cluster, subqueryRel, rexNodeLhs, quantifyOperator); if(subqueryType == SubqueryType.ALL) { return cluster.getRexBuilder().makeCall(SqlStdOperatorTable.NOT, someQuery); } return someQuery; } private static RexNode getSomeSubquery(final RelOptCluster cluster, final RelNode subqueryRel, final RexNode lhs, final SqlQuantifyOperator quantifyOperator) { if(quantifyOperator == SqlStdOperatorTable.SOME_EQ) { return RexSubQuery.in(subqueryRel, ImmutableList.<RexNode>of(lhs)); } else if (quantifyOperator == SqlStdOperatorTable.SOME_NE) { RexSubQuery subQuery = RexSubQuery.in(subqueryRel, ImmutableList.<RexNode>of(lhs)); return cluster.getRexBuilder().makeCall(SqlStdOperatorTable.NOT, subQuery); } else { return RexSubQuery.some(subqueryRel, ImmutableList.of(lhs), quantifyOperator); } } public static NlsString makeHiveUnicodeString(String text) { return new NlsString(text, ConversionUtil.NATIVE_UTF16_CHARSET_NAME, SqlCollation.IMPLICIT); } }
google/schemaorg-java
37,769
src/main/java/com/google/schemaorg/core/VideoGame.java
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.schemaorg.core; import com.google.common.collect.ImmutableList; import com.google.schemaorg.JsonLdContext; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.core.datatype.Date; import com.google.schemaorg.core.datatype.DateTime; import com.google.schemaorg.core.datatype.Integer; import com.google.schemaorg.core.datatype.Number; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.PopularityScoreSpecification; import javax.annotation.Nullable; /** Interface of <a href="http://schema.org/VideoGame}">http://schema.org/VideoGame}</a>. */ public interface VideoGame extends Game, SoftwareApplication { /** * Builder interface of <a href="http://schema.org/VideoGame}">http://schema.org/VideoGame}</a>. */ public interface Builder extends Game.Builder, SoftwareApplication.Builder { @Override Builder addJsonLdContext(@Nullable JsonLdContext context); @Override Builder addJsonLdContext(@Nullable JsonLdContext.Builder context); @Override Builder setJsonLdId(@Nullable String value); @Override Builder setJsonLdReverse(String property, Thing obj); @Override Builder setJsonLdReverse(String property, Thing.Builder builder); /** Add a value to property about. */ Builder addAbout(Thing value); /** Add a value to property about. */ Builder addAbout(Thing.Builder value); /** Add a value to property about. */ Builder addAbout(String value); /** Add a value to property accessibilityAPI. */ Builder addAccessibilityAPI(Text value); /** Add a value to property accessibilityAPI. */ Builder addAccessibilityAPI(String value); /** Add a value to property accessibilityControl. */ Builder addAccessibilityControl(Text value); /** Add a value to property accessibilityControl. */ Builder addAccessibilityControl(String value); /** Add a value to property accessibilityFeature. */ Builder addAccessibilityFeature(Text value); /** Add a value to property accessibilityFeature. */ Builder addAccessibilityFeature(String value); /** Add a value to property accessibilityHazard. */ Builder addAccessibilityHazard(Text value); /** Add a value to property accessibilityHazard. */ Builder addAccessibilityHazard(String value); /** Add a value to property accountablePerson. */ Builder addAccountablePerson(Person value); /** Add a value to property accountablePerson. */ Builder addAccountablePerson(Person.Builder value); /** Add a value to property accountablePerson. */ Builder addAccountablePerson(String value); /** Add a value to property actor. */ Builder addActor(Person value); /** Add a value to property actor. */ Builder addActor(Person.Builder value); /** Add a value to property actor. */ Builder addActor(String value); /** Add a value to property actors. */ Builder addActors(Person value); /** Add a value to property actors. */ Builder addActors(Person.Builder value); /** Add a value to property actors. */ Builder addActors(String value); /** Add a value to property additionalType. */ Builder addAdditionalType(URL value); /** Add a value to property additionalType. */ Builder addAdditionalType(String value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(AggregateRating value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(AggregateRating.Builder value); /** Add a value to property aggregateRating. */ Builder addAggregateRating(String value); /** Add a value to property alternateName. */ Builder addAlternateName(Text value); /** Add a value to property alternateName. */ Builder addAlternateName(String value); /** Add a value to property alternativeHeadline. */ Builder addAlternativeHeadline(Text value); /** Add a value to property alternativeHeadline. */ Builder addAlternativeHeadline(String value); /** Add a value to property applicationCategory. */ Builder addApplicationCategory(Text value); /** Add a value to property applicationCategory. */ Builder addApplicationCategory(URL value); /** Add a value to property applicationCategory. */ Builder addApplicationCategory(String value); /** Add a value to property applicationSubCategory. */ Builder addApplicationSubCategory(Text value); /** Add a value to property applicationSubCategory. */ Builder addApplicationSubCategory(URL value); /** Add a value to property applicationSubCategory. */ Builder addApplicationSubCategory(String value); /** Add a value to property applicationSuite. */ Builder addApplicationSuite(Text value); /** Add a value to property applicationSuite. */ Builder addApplicationSuite(String value); /** Add a value to property associatedMedia. */ Builder addAssociatedMedia(MediaObject value); /** Add a value to property associatedMedia. */ Builder addAssociatedMedia(MediaObject.Builder value); /** Add a value to property associatedMedia. */ Builder addAssociatedMedia(String value); /** Add a value to property audience. */ Builder addAudience(Audience value); /** Add a value to property audience. */ Builder addAudience(Audience.Builder value); /** Add a value to property audience. */ Builder addAudience(String value); /** Add a value to property audio. */ Builder addAudio(AudioObject value); /** Add a value to property audio. */ Builder addAudio(AudioObject.Builder value); /** Add a value to property audio. */ Builder addAudio(String value); /** Add a value to property author. */ Builder addAuthor(Organization value); /** Add a value to property author. */ Builder addAuthor(Organization.Builder value); /** Add a value to property author. */ Builder addAuthor(Person value); /** Add a value to property author. */ Builder addAuthor(Person.Builder value); /** Add a value to property author. */ Builder addAuthor(String value); /** Add a value to property availableOnDevice. */ Builder addAvailableOnDevice(Text value); /** Add a value to property availableOnDevice. */ Builder addAvailableOnDevice(String value); /** Add a value to property award. */ Builder addAward(Text value); /** Add a value to property award. */ Builder addAward(String value); /** Add a value to property awards. */ Builder addAwards(Text value); /** Add a value to property awards. */ Builder addAwards(String value); /** Add a value to property character. */ Builder addCharacter(Person value); /** Add a value to property character. */ Builder addCharacter(Person.Builder value); /** Add a value to property character. */ Builder addCharacter(String value); /** Add a value to property characterAttribute. */ Builder addCharacterAttribute(Thing value); /** Add a value to property characterAttribute. */ Builder addCharacterAttribute(Thing.Builder value); /** Add a value to property characterAttribute. */ Builder addCharacterAttribute(String value); /** Add a value to property cheatCode. */ Builder addCheatCode(CreativeWork value); /** Add a value to property cheatCode. */ Builder addCheatCode(CreativeWork.Builder value); /** Add a value to property cheatCode. */ Builder addCheatCode(String value); /** Add a value to property citation. */ Builder addCitation(CreativeWork value); /** Add a value to property citation. */ Builder addCitation(CreativeWork.Builder value); /** Add a value to property citation. */ Builder addCitation(Text value); /** Add a value to property citation. */ Builder addCitation(String value); /** Add a value to property comment. */ Builder addComment(Comment value); /** Add a value to property comment. */ Builder addComment(Comment.Builder value); /** Add a value to property comment. */ Builder addComment(String value); /** Add a value to property commentCount. */ Builder addCommentCount(Integer value); /** Add a value to property commentCount. */ Builder addCommentCount(String value); /** Add a value to property contentLocation. */ Builder addContentLocation(Place value); /** Add a value to property contentLocation. */ Builder addContentLocation(Place.Builder value); /** Add a value to property contentLocation. */ Builder addContentLocation(String value); /** Add a value to property contentRating. */ Builder addContentRating(Text value); /** Add a value to property contentRating. */ Builder addContentRating(String value); /** Add a value to property contributor. */ Builder addContributor(Organization value); /** Add a value to property contributor. */ Builder addContributor(Organization.Builder value); /** Add a value to property contributor. */ Builder addContributor(Person value); /** Add a value to property contributor. */ Builder addContributor(Person.Builder value); /** Add a value to property contributor. */ Builder addContributor(String value); /** Add a value to property copyrightHolder. */ Builder addCopyrightHolder(Organization value); /** Add a value to property copyrightHolder. */ Builder addCopyrightHolder(Organization.Builder value); /** Add a value to property copyrightHolder. */ Builder addCopyrightHolder(Person value); /** Add a value to property copyrightHolder. */ Builder addCopyrightHolder(Person.Builder value); /** Add a value to property copyrightHolder. */ Builder addCopyrightHolder(String value); /** Add a value to property copyrightYear. */ Builder addCopyrightYear(Number value); /** Add a value to property copyrightYear. */ Builder addCopyrightYear(String value); /** Add a value to property countriesNotSupported. */ Builder addCountriesNotSupported(Text value); /** Add a value to property countriesNotSupported. */ Builder addCountriesNotSupported(String value); /** Add a value to property countriesSupported. */ Builder addCountriesSupported(Text value); /** Add a value to property countriesSupported. */ Builder addCountriesSupported(String value); /** Add a value to property creator. */ Builder addCreator(Organization value); /** Add a value to property creator. */ Builder addCreator(Organization.Builder value); /** Add a value to property creator. */ Builder addCreator(Person value); /** Add a value to property creator. */ Builder addCreator(Person.Builder value); /** Add a value to property creator. */ Builder addCreator(String value); /** Add a value to property dateCreated. */ Builder addDateCreated(Date value); /** Add a value to property dateCreated. */ Builder addDateCreated(DateTime value); /** Add a value to property dateCreated. */ Builder addDateCreated(String value); /** Add a value to property dateModified. */ Builder addDateModified(Date value); /** Add a value to property dateModified. */ Builder addDateModified(DateTime value); /** Add a value to property dateModified. */ Builder addDateModified(String value); /** Add a value to property datePublished. */ Builder addDatePublished(Date value); /** Add a value to property datePublished. */ Builder addDatePublished(String value); /** Add a value to property description. */ Builder addDescription(Text value); /** Add a value to property description. */ Builder addDescription(String value); /** Add a value to property device. */ Builder addDevice(Text value); /** Add a value to property device. */ Builder addDevice(String value); /** Add a value to property director. */ Builder addDirector(Person value); /** Add a value to property director. */ Builder addDirector(Person.Builder value); /** Add a value to property director. */ Builder addDirector(String value); /** Add a value to property directors. */ Builder addDirectors(Person value); /** Add a value to property directors. */ Builder addDirectors(Person.Builder value); /** Add a value to property directors. */ Builder addDirectors(String value); /** Add a value to property discussionUrl. */ Builder addDiscussionUrl(URL value); /** Add a value to property discussionUrl. */ Builder addDiscussionUrl(String value); /** Add a value to property downloadUrl. */ Builder addDownloadUrl(URL value); /** Add a value to property downloadUrl. */ Builder addDownloadUrl(String value); /** Add a value to property editor. */ Builder addEditor(Person value); /** Add a value to property editor. */ Builder addEditor(Person.Builder value); /** Add a value to property editor. */ Builder addEditor(String value); /** Add a value to property educationalAlignment. */ Builder addEducationalAlignment(AlignmentObject value); /** Add a value to property educationalAlignment. */ Builder addEducationalAlignment(AlignmentObject.Builder value); /** Add a value to property educationalAlignment. */ Builder addEducationalAlignment(String value); /** Add a value to property educationalUse. */ Builder addEducationalUse(Text value); /** Add a value to property educationalUse. */ Builder addEducationalUse(String value); /** Add a value to property encoding. */ Builder addEncoding(MediaObject value); /** Add a value to property encoding. */ Builder addEncoding(MediaObject.Builder value); /** Add a value to property encoding. */ Builder addEncoding(String value); /** Add a value to property encodings. */ Builder addEncodings(MediaObject value); /** Add a value to property encodings. */ Builder addEncodings(MediaObject.Builder value); /** Add a value to property encodings. */ Builder addEncodings(String value); /** Add a value to property exampleOfWork. */ Builder addExampleOfWork(CreativeWork value); /** Add a value to property exampleOfWork. */ Builder addExampleOfWork(CreativeWork.Builder value); /** Add a value to property exampleOfWork. */ Builder addExampleOfWork(String value); /** Add a value to property featureList. */ Builder addFeatureList(Text value); /** Add a value to property featureList. */ Builder addFeatureList(URL value); /** Add a value to property featureList. */ Builder addFeatureList(String value); /** Add a value to property fileFormat. */ Builder addFileFormat(Text value); /** Add a value to property fileFormat. */ Builder addFileFormat(String value); /** Add a value to property fileSize. */ Builder addFileSize(Text value); /** Add a value to property fileSize. */ Builder addFileSize(String value); /** Add a value to property gameItem. */ Builder addGameItem(Thing value); /** Add a value to property gameItem. */ Builder addGameItem(Thing.Builder value); /** Add a value to property gameItem. */ Builder addGameItem(String value); /** Add a value to property gameLocation. */ Builder addGameLocation(Place value); /** Add a value to property gameLocation. */ Builder addGameLocation(Place.Builder value); /** Add a value to property gameLocation. */ Builder addGameLocation(PostalAddress value); /** Add a value to property gameLocation. */ Builder addGameLocation(PostalAddress.Builder value); /** Add a value to property gameLocation. */ Builder addGameLocation(URL value); /** Add a value to property gameLocation. */ Builder addGameLocation(String value); /** Add a value to property gamePlatform. */ Builder addGamePlatform(Text value); /** Add a value to property gamePlatform. */ Builder addGamePlatform(Thing value); /** Add a value to property gamePlatform. */ Builder addGamePlatform(Thing.Builder value); /** Add a value to property gamePlatform. */ Builder addGamePlatform(URL value); /** Add a value to property gamePlatform. */ Builder addGamePlatform(String value); /** Add a value to property gameServer. */ Builder addGameServer(GameServer value); /** Add a value to property gameServer. */ Builder addGameServer(GameServer.Builder value); /** Add a value to property gameServer. */ Builder addGameServer(String value); /** Add a value to property gameTip. */ Builder addGameTip(CreativeWork value); /** Add a value to property gameTip. */ Builder addGameTip(CreativeWork.Builder value); /** Add a value to property gameTip. */ Builder addGameTip(String value); /** Add a value to property genre. */ Builder addGenre(Text value); /** Add a value to property genre. */ Builder addGenre(URL value); /** Add a value to property genre. */ Builder addGenre(String value); /** Add a value to property hasPart. */ Builder addHasPart(CreativeWork value); /** Add a value to property hasPart. */ Builder addHasPart(CreativeWork.Builder value); /** Add a value to property hasPart. */ Builder addHasPart(String value); /** Add a value to property headline. */ Builder addHeadline(Text value); /** Add a value to property headline. */ Builder addHeadline(String value); /** Add a value to property image. */ Builder addImage(ImageObject value); /** Add a value to property image. */ Builder addImage(ImageObject.Builder value); /** Add a value to property image. */ Builder addImage(URL value); /** Add a value to property image. */ Builder addImage(String value); /** Add a value to property inLanguage. */ Builder addInLanguage(Language value); /** Add a value to property inLanguage. */ Builder addInLanguage(Language.Builder value); /** Add a value to property inLanguage. */ Builder addInLanguage(Text value); /** Add a value to property inLanguage. */ Builder addInLanguage(String value); /** Add a value to property installUrl. */ Builder addInstallUrl(URL value); /** Add a value to property installUrl. */ Builder addInstallUrl(String value); /** Add a value to property interactionStatistic. */ Builder addInteractionStatistic(InteractionCounter value); /** Add a value to property interactionStatistic. */ Builder addInteractionStatistic(InteractionCounter.Builder value); /** Add a value to property interactionStatistic. */ Builder addInteractionStatistic(String value); /** Add a value to property interactivityType. */ Builder addInteractivityType(Text value); /** Add a value to property interactivityType. */ Builder addInteractivityType(String value); /** Add a value to property isBasedOnUrl. */ Builder addIsBasedOnUrl(URL value); /** Add a value to property isBasedOnUrl. */ Builder addIsBasedOnUrl(String value); /** Add a value to property isFamilyFriendly. */ Builder addIsFamilyFriendly(Boolean value); /** Add a value to property isFamilyFriendly. */ Builder addIsFamilyFriendly(String value); /** Add a value to property isPartOf. */ Builder addIsPartOf(CreativeWork value); /** Add a value to property isPartOf. */ Builder addIsPartOf(CreativeWork.Builder value); /** Add a value to property isPartOf. */ Builder addIsPartOf(String value); /** Add a value to property keywords. */ Builder addKeywords(Text value); /** Add a value to property keywords. */ Builder addKeywords(String value); /** Add a value to property learningResourceType. */ Builder addLearningResourceType(Text value); /** Add a value to property learningResourceType. */ Builder addLearningResourceType(String value); /** Add a value to property license. */ Builder addLicense(CreativeWork value); /** Add a value to property license. */ Builder addLicense(CreativeWork.Builder value); /** Add a value to property license. */ Builder addLicense(URL value); /** Add a value to property license. */ Builder addLicense(String value); /** Add a value to property locationCreated. */ Builder addLocationCreated(Place value); /** Add a value to property locationCreated. */ Builder addLocationCreated(Place.Builder value); /** Add a value to property locationCreated. */ Builder addLocationCreated(String value); /** Add a value to property mainEntity. */ Builder addMainEntity(Thing value); /** Add a value to property mainEntity. */ Builder addMainEntity(Thing.Builder value); /** Add a value to property mainEntity. */ Builder addMainEntity(String value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(CreativeWork.Builder value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(URL value); /** Add a value to property mainEntityOfPage. */ Builder addMainEntityOfPage(String value); /** Add a value to property memoryRequirements. */ Builder addMemoryRequirements(Text value); /** Add a value to property memoryRequirements. */ Builder addMemoryRequirements(URL value); /** Add a value to property memoryRequirements. */ Builder addMemoryRequirements(String value); /** Add a value to property mentions. */ Builder addMentions(Thing value); /** Add a value to property mentions. */ Builder addMentions(Thing.Builder value); /** Add a value to property mentions. */ Builder addMentions(String value); /** Add a value to property musicBy. */ Builder addMusicBy(MusicGroup value); /** Add a value to property musicBy. */ Builder addMusicBy(MusicGroup.Builder value); /** Add a value to property musicBy. */ Builder addMusicBy(Person value); /** Add a value to property musicBy. */ Builder addMusicBy(Person.Builder value); /** Add a value to property musicBy. */ Builder addMusicBy(String value); /** Add a value to property name. */ Builder addName(Text value); /** Add a value to property name. */ Builder addName(String value); /** Add a value to property numberOfPlayers. */ Builder addNumberOfPlayers(QuantitativeValue value); /** Add a value to property numberOfPlayers. */ Builder addNumberOfPlayers(QuantitativeValue.Builder value); /** Add a value to property numberOfPlayers. */ Builder addNumberOfPlayers(String value); /** Add a value to property offers. */ Builder addOffers(Offer value); /** Add a value to property offers. */ Builder addOffers(Offer.Builder value); /** Add a value to property offers. */ Builder addOffers(String value); /** Add a value to property operatingSystem. */ Builder addOperatingSystem(Text value); /** Add a value to property operatingSystem. */ Builder addOperatingSystem(String value); /** Add a value to property permissions. */ Builder addPermissions(Text value); /** Add a value to property permissions. */ Builder addPermissions(String value); /** Add a value to property playMode. */ Builder addPlayMode(GamePlayMode value); /** Add a value to property playMode. */ Builder addPlayMode(String value); /** Add a value to property position. */ Builder addPosition(Integer value); /** Add a value to property position. */ Builder addPosition(Text value); /** Add a value to property position. */ Builder addPosition(String value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action value); /** Add a value to property potentialAction. */ Builder addPotentialAction(Action.Builder value); /** Add a value to property potentialAction. */ Builder addPotentialAction(String value); /** Add a value to property processorRequirements. */ Builder addProcessorRequirements(Text value); /** Add a value to property processorRequirements. */ Builder addProcessorRequirements(String value); /** Add a value to property producer. */ Builder addProducer(Organization value); /** Add a value to property producer. */ Builder addProducer(Organization.Builder value); /** Add a value to property producer. */ Builder addProducer(Person value); /** Add a value to property producer. */ Builder addProducer(Person.Builder value); /** Add a value to property producer. */ Builder addProducer(String value); /** Add a value to property provider. */ Builder addProvider(Organization value); /** Add a value to property provider. */ Builder addProvider(Organization.Builder value); /** Add a value to property provider. */ Builder addProvider(Person value); /** Add a value to property provider. */ Builder addProvider(Person.Builder value); /** Add a value to property provider. */ Builder addProvider(String value); /** Add a value to property publication. */ Builder addPublication(PublicationEvent value); /** Add a value to property publication. */ Builder addPublication(PublicationEvent.Builder value); /** Add a value to property publication. */ Builder addPublication(String value); /** Add a value to property publisher. */ Builder addPublisher(Organization value); /** Add a value to property publisher. */ Builder addPublisher(Organization.Builder value); /** Add a value to property publisher. */ Builder addPublisher(Person value); /** Add a value to property publisher. */ Builder addPublisher(Person.Builder value); /** Add a value to property publisher. */ Builder addPublisher(String value); /** Add a value to property publishingPrinciples. */ Builder addPublishingPrinciples(URL value); /** Add a value to property publishingPrinciples. */ Builder addPublishingPrinciples(String value); /** Add a value to property quest. */ Builder addQuest(Thing value); /** Add a value to property quest. */ Builder addQuest(Thing.Builder value); /** Add a value to property quest. */ Builder addQuest(String value); /** Add a value to property recordedAt. */ Builder addRecordedAt(Event value); /** Add a value to property recordedAt. */ Builder addRecordedAt(Event.Builder value); /** Add a value to property recordedAt. */ Builder addRecordedAt(String value); /** Add a value to property releasedEvent. */ Builder addReleasedEvent(PublicationEvent value); /** Add a value to property releasedEvent. */ Builder addReleasedEvent(PublicationEvent.Builder value); /** Add a value to property releasedEvent. */ Builder addReleasedEvent(String value); /** Add a value to property releaseNotes. */ Builder addReleaseNotes(Text value); /** Add a value to property releaseNotes. */ Builder addReleaseNotes(URL value); /** Add a value to property releaseNotes. */ Builder addReleaseNotes(String value); /** Add a value to property requirements. */ Builder addRequirements(Text value); /** Add a value to property requirements. */ Builder addRequirements(URL value); /** Add a value to property requirements. */ Builder addRequirements(String value); /** Add a value to property review. */ Builder addReview(Review value); /** Add a value to property review. */ Builder addReview(Review.Builder value); /** Add a value to property review. */ Builder addReview(String value); /** Add a value to property reviews. */ Builder addReviews(Review value); /** Add a value to property reviews. */ Builder addReviews(Review.Builder value); /** Add a value to property reviews. */ Builder addReviews(String value); /** Add a value to property sameAs. */ Builder addSameAs(URL value); /** Add a value to property sameAs. */ Builder addSameAs(String value); /** Add a value to property schemaVersion. */ Builder addSchemaVersion(Text value); /** Add a value to property schemaVersion. */ Builder addSchemaVersion(URL value); /** Add a value to property schemaVersion. */ Builder addSchemaVersion(String value); /** Add a value to property screenshot. */ Builder addScreenshot(ImageObject value); /** Add a value to property screenshot. */ Builder addScreenshot(ImageObject.Builder value); /** Add a value to property screenshot. */ Builder addScreenshot(URL value); /** Add a value to property screenshot. */ Builder addScreenshot(String value); /** Add a value to property softwareAddOn. */ Builder addSoftwareAddOn(SoftwareApplication value); /** Add a value to property softwareAddOn. */ Builder addSoftwareAddOn(SoftwareApplication.Builder value); /** Add a value to property softwareAddOn. */ Builder addSoftwareAddOn(String value); /** Add a value to property softwareHelp. */ Builder addSoftwareHelp(CreativeWork value); /** Add a value to property softwareHelp. */ Builder addSoftwareHelp(CreativeWork.Builder value); /** Add a value to property softwareHelp. */ Builder addSoftwareHelp(String value); /** Add a value to property softwareRequirements. */ Builder addSoftwareRequirements(Text value); /** Add a value to property softwareRequirements. */ Builder addSoftwareRequirements(URL value); /** Add a value to property softwareRequirements. */ Builder addSoftwareRequirements(String value); /** Add a value to property softwareVersion. */ Builder addSoftwareVersion(Text value); /** Add a value to property softwareVersion. */ Builder addSoftwareVersion(String value); /** Add a value to property sourceOrganization. */ Builder addSourceOrganization(Organization value); /** Add a value to property sourceOrganization. */ Builder addSourceOrganization(Organization.Builder value); /** Add a value to property sourceOrganization. */ Builder addSourceOrganization(String value); /** Add a value to property storageRequirements. */ Builder addStorageRequirements(Text value); /** Add a value to property storageRequirements. */ Builder addStorageRequirements(URL value); /** Add a value to property storageRequirements. */ Builder addStorageRequirements(String value); /** Add a value to property supportingData. */ Builder addSupportingData(DataFeed value); /** Add a value to property supportingData. */ Builder addSupportingData(DataFeed.Builder value); /** Add a value to property supportingData. */ Builder addSupportingData(String value); /** Add a value to property text. */ Builder addText(Text value); /** Add a value to property text. */ Builder addText(String value); /** Add a value to property thumbnailUrl. */ Builder addThumbnailUrl(URL value); /** Add a value to property thumbnailUrl. */ Builder addThumbnailUrl(String value); /** Add a value to property timeRequired. */ Builder addTimeRequired(Duration value); /** Add a value to property timeRequired. */ Builder addTimeRequired(Duration.Builder value); /** Add a value to property timeRequired. */ Builder addTimeRequired(String value); /** Add a value to property trailer. */ Builder addTrailer(VideoObject value); /** Add a value to property trailer. */ Builder addTrailer(VideoObject.Builder value); /** Add a value to property trailer. */ Builder addTrailer(String value); /** Add a value to property translator. */ Builder addTranslator(Organization value); /** Add a value to property translator. */ Builder addTranslator(Organization.Builder value); /** Add a value to property translator. */ Builder addTranslator(Person value); /** Add a value to property translator. */ Builder addTranslator(Person.Builder value); /** Add a value to property translator. */ Builder addTranslator(String value); /** Add a value to property typicalAgeRange. */ Builder addTypicalAgeRange(Text value); /** Add a value to property typicalAgeRange. */ Builder addTypicalAgeRange(String value); /** Add a value to property url. */ Builder addUrl(URL value); /** Add a value to property url. */ Builder addUrl(String value); /** Add a value to property version. */ Builder addVersion(Number value); /** Add a value to property version. */ Builder addVersion(String value); /** Add a value to property video. */ Builder addVideo(VideoObject value); /** Add a value to property video. */ Builder addVideo(VideoObject.Builder value); /** Add a value to property video. */ Builder addVideo(String value); /** Add a value to property workExample. */ Builder addWorkExample(CreativeWork value); /** Add a value to property workExample. */ Builder addWorkExample(CreativeWork.Builder value); /** Add a value to property workExample. */ Builder addWorkExample(String value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(Article.Builder value); /** Add a value to property detailedDescription. */ Builder addDetailedDescription(String value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification value); /** Add a value to property popularityScore. */ Builder addPopularityScore(PopularityScoreSpecification.Builder value); /** Add a value to property popularityScore. */ Builder addPopularityScore(String value); /** * Add a value to property. * * @param name The property name. * @param value The value of the property. */ Builder addProperty(String name, SchemaOrgType value); /** * Add a value to property. * * @param name The property name. * @param builder The schema.org object builder for the property value. */ Builder addProperty(String name, Thing.Builder builder); /** * Add a value to property. * * @param name The property name. * @param value The string value of the property. */ Builder addProperty(String name, String value); /** Build a {@link VideoGame} object. */ VideoGame build(); } /** * Returns the value list of property actor. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getActorList(); /** * Returns the value list of property actors. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getActorsList(); /** * Returns the value list of property cheatCode. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getCheatCodeList(); /** * Returns the value list of property director. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getDirectorList(); /** * Returns the value list of property directors. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getDirectorsList(); /** * Returns the value list of property gamePlatform. Empty list is returned if the property not set * in current object. */ ImmutableList<SchemaOrgType> getGamePlatformList(); /** * Returns the value list of property gameServer. Empty list is returned if the property not set * in current object. */ ImmutableList<SchemaOrgType> getGameServerList(); /** * Returns the value list of property gameTip. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getGameTipList(); /** * Returns the value list of property musicBy. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getMusicByList(); /** * Returns the value list of property playMode. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getPlayModeList(); /** * Returns the value list of property trailer. Empty list is returned if the property not set in * current object. */ ImmutableList<SchemaOrgType> getTrailerList(); }
apache/jmeter
37,556
src/jorphan/src/test/java/org/apache/commons/cli/avalon/ClutilTestCase.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.commons.cli.avalon; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import java.util.List; import org.junit.jupiter.api.Test; public final class ClutilTestCase { private static final String[] ARGLIST1 = new String[] { "--you", "are", "--all", "-cler", "kid" }; private static final String[] ARGLIST2 = new String[] { "-Dstupid=idiot", "are", "--all", "here", "-d" }; // duplicates private static final String[] ARGLIST3 = new String[] { "-Dstupid=idiot", "are", "--all", "--all", "here" }; // incompatible (blee/all) private static final String[] ARGLIST4 = new String[] { "-Dstupid", "idiot", "are", "--all", "--blee", "here" }; private static final String[] ARGLIST5 = new String[] { "-f", "myfile.txt" }; private static final int DEFINE_OPT = 'D'; private static final int CASE_CHECK_OPT = 'd'; private static final int YOU_OPT = 'y'; private static final int ALL_OPT = 'a'; private static final int CLEAR1_OPT = 'c'; private static final int CLEAR2_OPT = 'l'; private static final int CLEAR3_OPT = 'e'; private static final int CLEAR5_OPT = 'r'; private static final int BLEE_OPT = 'b'; private static final int FILE_OPT = 'f'; private static final int TAINT_OPT = 'T'; private static final CLOptionDescriptor DEFINE = new CLOptionDescriptor("define", CLOptionDescriptor.ARGUMENTS_REQUIRED_2, DEFINE_OPT, "define"); private static final CLOptionDescriptor DEFINE_MANY = new CLOptionDescriptor("define", CLOptionDescriptor.ARGUMENTS_REQUIRED_2 | CLOptionDescriptor.DUPLICATES_ALLOWED, DEFINE_OPT, "define"); private static final CLOptionDescriptor CASE_CHECK = new CLOptionDescriptor("charCheck", CLOptionDescriptor.ARGUMENT_DISALLOWED, CASE_CHECK_OPT, "check character case sensitivity"); private static final CLOptionDescriptor YOU = new CLOptionDescriptor("you", CLOptionDescriptor.ARGUMENT_DISALLOWED, YOU_OPT, "you"); private static final CLOptionDescriptor CLEAR1 = new CLOptionDescriptor("c", CLOptionDescriptor.ARGUMENT_DISALLOWED, CLEAR1_OPT, "c"); private static final CLOptionDescriptor CLEAR2 = new CLOptionDescriptor("l", CLOptionDescriptor.ARGUMENT_DISALLOWED, CLEAR2_OPT, "l"); private static final CLOptionDescriptor CLEAR3 = new CLOptionDescriptor("e", CLOptionDescriptor.ARGUMENT_DISALLOWED, CLEAR3_OPT, "e"); private static final CLOptionDescriptor CLEAR5 = new CLOptionDescriptor("r", CLOptionDescriptor.ARGUMENT_DISALLOWED, CLEAR5_OPT, "r"); private static final CLOptionDescriptor BLEE = new CLOptionDescriptor("blee", CLOptionDescriptor.ARGUMENT_DISALLOWED, BLEE_OPT, "blee"); private static final CLOptionDescriptor ALL = new CLOptionDescriptor("all", CLOptionDescriptor.ARGUMENT_DISALLOWED, ALL_OPT, "all", new CLOptionDescriptor[] { BLEE }); private static final CLOptionDescriptor FILE = new CLOptionDescriptor("file", CLOptionDescriptor.ARGUMENT_REQUIRED, FILE_OPT, "the build file."); private static final CLOptionDescriptor TAINT = new CLOptionDescriptor("taint", CLOptionDescriptor.ARGUMENT_OPTIONAL, TAINT_OPT, "turn on tainting checks (optional level)."); private static final CLOptionDescriptor [] OPTIONS = new CLOptionDescriptor [] { new CLOptionDescriptor("none", CLOptionDescriptor.ARGUMENT_DISALLOWED | CLOptionDescriptor.DUPLICATES_ALLOWED, '0', "no parameter"), new CLOptionDescriptor("optional", CLOptionDescriptor.ARGUMENT_OPTIONAL | CLOptionDescriptor.DUPLICATES_ALLOWED, '?', "optional parameter"), new CLOptionDescriptor("one", CLOptionDescriptor.ARGUMENT_REQUIRED | CLOptionDescriptor.DUPLICATES_ALLOWED, '1', "one parameter"), new CLOptionDescriptor("two", CLOptionDescriptor.ARGUMENTS_REQUIRED_2 | CLOptionDescriptor.DUPLICATES_ALLOWED, '2', "two parameters") }; @Test public void testOptionalArgWithSpace() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; final String[] args = new String[] { "-T", "param", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(3, size, "Option count"); final CLOption option0 = clOptions.get(0); assertEquals(TAINT_OPT, option0.getDescriptor().getId(), "Option Code: " + option0.getDescriptor().getId()); assertNull(option0.getArgument(0), "Option Arg: " + option0.getArgument(0)); final CLOption option1 = clOptions.get(1); assertEquals(option1.getDescriptor().getId(), CLOption.TEXT_ARGUMENT); assertEquals(option1.getArgument(0), "param"); final CLOption option2 = clOptions.get(2); assertEquals(option2.getDescriptor().getId(), ALL_OPT); assertNull(option2.getArgument(0)); } @Test public void testOptionalArgLong() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; // Check that optional args work woth long options final String[] args = new String[] { "--taint", "param", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(3, size, "Option count"); final CLOption option0 = clOptions.get(0); assertEquals(TAINT_OPT, option0.getDescriptor().getId(), "Option Code: " + option0.getDescriptor().getId()); assertNull(option0.getArgument(0), "Option Arg: " + option0.getArgument(0)); final CLOption option1 = clOptions.get(1); assertEquals(CLOption.TEXT_ARGUMENT, option1.getDescriptor().getId()); assertEquals("param", option1.getArgument(0)); final CLOption option2 = clOptions.get(2); assertEquals(option2.getDescriptor().getId(), ALL_OPT); assertNull(option2.getArgument(0)); } @Test public void testOptionalArgLongEquals() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; // Check that optional args work with long options final String[] args = new String[] { "--taint=param", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(2, size, "Option count"); final CLOption option0 = clOptions.get(0); assertEquals(TAINT_OPT, option0.getDescriptor().getId(), "Option Code: " + option0.getDescriptor().getId()); assertEquals("param", option0.getArgument(0), "Option Arg: " + option0.getArgument(0)); final CLOption option2 = clOptions.get(1); assertEquals(option2.getDescriptor().getId(), ALL_OPT); assertNull(option2.getArgument(0)); } @Test public void testShortOptArgUnenteredBeforeOtherOpt() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; final String[] args = new String[] { "-T", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(2, size, "Option count"); final CLOption option0 = clOptions.get(0); assertEquals(TAINT_OPT, option0.getDescriptor().getId(), "Option Code: " + option0.getDescriptor().getId()); assertNull(option0.getArgument(0), "Option Arg: " + option0.getArgument(0)); final CLOption option1 = clOptions.get(1); assertEquals(option1.getDescriptor().getId(), ALL_OPT); assertNull(option1.getArgument(0)); } @Test public void testOptionalArgsWithArgShortBeforeOtherOpt() { // "-T3","-a" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; final String[] args = new String[] { "-T3", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 2); final CLOption option0 = clOptions.get(0); assertEquals(option0.getDescriptor().getId(), TAINT_OPT); assertEquals(option0.getArgument(0), "3"); final CLOption option1 = clOptions.get(1); assertEquals(ALL_OPT, option1.getDescriptor().getId()); assertNull(option1.getArgument(0)); } @Test public void testOptionalArgsWithArgShortEqualsBeforeOtherOpt() { // "-T3","-a" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; final String[] args = new String[] { "-T=3", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 2); final CLOption option0 = clOptions.get(0); assertEquals(option0.getDescriptor().getId(), TAINT_OPT); assertEquals(option0.getArgument(0), "3"); final CLOption option1 = clOptions.get(1); assertEquals(ALL_OPT, option1.getDescriptor().getId()); assertNull(option1.getArgument(0)); } @Test public void testOptionalArgsNoArgShortBeforeOtherOpt() { // "-T","-a" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { ALL, TAINT }; final String[] args = new String[] { "-T", "-a" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 2); final CLOption option0 = clOptions.get(0); assertEquals(TAINT_OPT, option0.getDescriptor().getId()); assertNull(option0.getArgument(0)); final CLOption option1 = clOptions.get(1); assertEquals(ALL_OPT, option1.getDescriptor().getId()); assertNull(option1.getArgument(0)); } @Test public void testFullParse() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { YOU, ALL, CLEAR1, CLEAR2, CLEAR3, CLEAR5 }; final CLArgsParser parser = new CLArgsParser(ARGLIST1, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 8); assertEquals(clOptions.get(0).getDescriptor().getId(), YOU_OPT); assertEquals(clOptions.get(1).getDescriptor().getId(), 0); assertEquals(clOptions.get(2).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions.get(3).getDescriptor().getId(), CLEAR1_OPT); assertEquals(clOptions.get(4).getDescriptor().getId(), CLEAR2_OPT); assertEquals(clOptions.get(5).getDescriptor().getId(), CLEAR3_OPT); assertEquals(clOptions.get(6).getDescriptor().getId(), CLEAR5_OPT); assertEquals(clOptions.get(7).getDescriptor().getId(), 0); } @Test public void testDuplicateOptions() { // "-Dstupid=idiot","are","--all","--all","here" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE, ALL, CLEAR1 }; final CLArgsParser parser = new CLArgsParser(ARGLIST3, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 5); assertEquals(clOptions.get(0).getDescriptor().getId(), DEFINE_OPT); assertEquals(clOptions.get(1).getDescriptor().getId(), 0); assertEquals(clOptions.get(2).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions.get(3).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions.get(4).getDescriptor().getId(), 0); } @Test public void testIncompatableOptions() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE, ALL, CLEAR1, BLEE }; final CLArgsParser parser = new CLArgsParser(ARGLIST4, options); assertNotNull(parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 5); assertEquals(clOptions.get(0).getDescriptor().getId(), DEFINE_OPT); assertEquals(clOptions.get(1).getDescriptor().getId(), 0); assertEquals(clOptions.get(2).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions.get(3).getDescriptor().getId(), BLEE_OPT); assertEquals(clOptions.get(4).getDescriptor().getId(), 0); } @Test public void testSingleArg() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; final CLArgsParser parser = new CLArgsParser(ARGLIST5, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 1); assertEquals(clOptions.get(0).getDescriptor().getId(), FILE_OPT); assertEquals(clOptions.get(0).getArgument(), "myfile.txt"); } @Test public void testSingleArg2() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; // Check delimiters are allowed final CLArgsParser parser = new CLArgsParser(new String[] { "-f-=,=-" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("-=,=-", clOptions.get(0).getArgument()); } @Test public void testSingleArg3() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; // Check delimiters are allowed final CLArgsParser parser = new CLArgsParser(new String[] { "--file=-=,-" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("-=,-", clOptions.get(0).getArgument()); } @Test public void testSingleArg4() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; final CLArgsParser parser = new CLArgsParser(new String[] { "--file", "myfile.txt" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("myfile.txt", clOptions.get(0).getArgument()); } @Test public void testSingleArg5() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; final CLArgsParser parser = new CLArgsParser(new String[] { "-f", "myfile.txt" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("myfile.txt", clOptions.get(0).getArgument()); } @Test public void testSingleArg6() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; final CLArgsParser parser = new CLArgsParser(new String[] { "-f", "-=-" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("-=-", clOptions.get(0).getArgument()); } @Test public void testSingleArg7() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; final CLArgsParser parser = new CLArgsParser(new String[] { "--file=-=-" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("-=-", clOptions.get(0).getArgument()); } @Test public void testSingleArg8() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { FILE }; final CLArgsParser parser = new CLArgsParser(new String[] { "--file", "-=-" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(FILE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals("-=-", clOptions.get(0).getArgument()); } @Test public void testCombinedArgs1() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { BLEE, TAINT }; final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "rest" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(3, size); assertEquals(BLEE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals(TAINT_OPT, clOptions.get(1).getDescriptor().getId()); assertEquals(0, clOptions.get(2).getDescriptor().getId()); assertEquals("rest", clOptions.get(2).getArgument()); } @Test public void testCombinedArgs2() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { BLEE, TAINT, FILE }; final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "-fa" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(3, size); assertEquals(BLEE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals(TAINT_OPT, clOptions.get(1).getDescriptor().getId()); assertEquals(FILE_OPT, clOptions.get(2).getDescriptor().getId()); assertEquals("a", clOptions.get(2).getArgument()); } @Test public void testCombinedArgs3() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { BLEE, TAINT, FILE }; // Should not detect trailing option final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "--", "-fa" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(3, size); assertEquals(BLEE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals(TAINT_OPT, clOptions.get(1).getDescriptor().getId()); assertEquals(0, clOptions.get(2).getDescriptor().getId()); assertEquals("-fa", clOptions.get(2).getArgument()); } @Test public void testCombinedArgs4() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { BLEE, TAINT, FILE }; // should detect trailing option final CLArgsParser parser = new CLArgsParser(new String[] { "-bT", "rest", "-fa" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(4, size); assertEquals(BLEE_OPT, clOptions.get(0).getDescriptor().getId()); assertEquals(TAINT_OPT, clOptions.get(1).getDescriptor().getId()); assertEquals(0, clOptions.get(2).getDescriptor().getId()); assertEquals("rest", clOptions.get(2).getArgument()); assertEquals(FILE_OPT, clOptions.get(3).getDescriptor().getId()); assertEquals("a", clOptions.get(3).getArgument()); } @Test public void test2ArgsParse() { // "-Dstupid=idiot","are","--all","here" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE, ALL, CLEAR1, CASE_CHECK }; final CLArgsParser parser = new CLArgsParser(ARGLIST2, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 5); assertEquals(clOptions.get(0).getDescriptor().getId(), DEFINE_OPT); assertEquals(clOptions.get(1).getDescriptor().getId(), 0); assertEquals(clOptions.get(2).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions.get(3).getDescriptor().getId(), 0); assertEquals(clOptions.get(4).getDescriptor().getId(), CASE_CHECK_OPT); final CLOption option = clOptions.get(0); assertEquals("stupid", option.getArgument(0)); assertEquals("idiot", option.getArgument(1)); } @Test public void test2ArgsParse2() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE }; // Check "-" is allowed in arg2 final CLArgsParser parser = new CLArgsParser(new String[] { "--define", "a-b,c=d-e,f" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(DEFINE_OPT, clOptions.get(0).getDescriptor().getId()); final CLOption option = clOptions.get(0); assertEquals("a-b,c", option.getArgument(0)); assertEquals("d-e,f", option.getArgument(1)); } @Test public void test2ArgsParse3() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE }; final CLArgsParser parser = new CLArgsParser(new String[] { "-D", "A-b,c", "G-e,f" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(1, size); assertEquals(DEFINE_OPT, clOptions.get(0).getDescriptor().getId()); final CLOption option = clOptions.get(0); assertEquals("A-b,c", option.getArgument(0)); assertEquals("G-e,f", option.getArgument(1)); } @Test public void test2ArgsParse4() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE_MANY }; final CLArgsParser parser = new CLArgsParser(new String[] { "-Dval1=-1", "-D", "val2=-2", "--define=val-3=-3", "--define", "val4-=-4" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(4, size); for (CLOption clOption : clOptions) { assertEquals(DEFINE_OPT, clOption.getDescriptor().getId()); } CLOption option; option = clOptions.get(0); assertEquals("val1", option.getArgument(0)); assertEquals("-1", option.getArgument(1)); option = clOptions.get(1); assertEquals("val2", option.getArgument(0)); assertEquals("-2", option.getArgument(1)); option = clOptions.get(2); assertEquals("val-3", option.getArgument(0)); assertEquals("-3", option.getArgument(1)); option = clOptions.get(3); assertEquals("val4-", option.getArgument(0)); assertEquals("-4", option.getArgument(1)); } @Test public void testPartParse() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { YOU }; final ParserControl control = new AbstractParserControl() { @Override public boolean isFinished(int lastOptionCode) { return lastOptionCode == YOU_OPT; } }; final CLArgsParser parser = new CLArgsParser(ARGLIST1, options, control); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 1); assertEquals(clOptions.get(0).getDescriptor().getId(), YOU_OPT); } @Test public void test2PartParse() { final CLOptionDescriptor[] options1 = new CLOptionDescriptor[] { YOU }; final CLOptionDescriptor[] options2 = new CLOptionDescriptor[] { ALL, CLEAR1, CLEAR2, CLEAR3, CLEAR5 }; final ParserControl control1 = new AbstractParserControl() { @Override public boolean isFinished(int lastOptionCode) { return lastOptionCode == YOU_OPT; } }; final CLArgsParser parser1 = new CLArgsParser(ARGLIST1, options1, control1); assertNull(parser1.getErrorString(), parser1.getErrorString()); final List<CLOption> clOptions1 = parser1.getArguments(); final int size1 = clOptions1.size(); assertEquals(size1, 1); assertEquals(clOptions1.get(0).getDescriptor().getId(), YOU_OPT); final CLArgsParser parser2 = new CLArgsParser(parser1.getUnparsedArgs(), options2); assertNull(parser2.getErrorString(), parser2.getErrorString()); final List<CLOption> clOptions2 = parser2.getArguments(); final int size2 = clOptions2.size(); assertEquals(size2, 7); assertEquals(clOptions2.get(0).getDescriptor().getId(), 0); assertEquals(clOptions2.get(1).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions2.get(2).getDescriptor().getId(), CLEAR1_OPT); assertEquals(clOptions2.get(3).getDescriptor().getId(), CLEAR2_OPT); assertEquals(clOptions2.get(4).getDescriptor().getId(), CLEAR3_OPT); assertEquals(clOptions2.get(5).getDescriptor().getId(), CLEAR5_OPT); assertEquals(clOptions2.get(6).getDescriptor().getId(), 0); } @Test public void test2PartPartialParse() { final CLOptionDescriptor[] options1 = new CLOptionDescriptor[] { YOU, ALL, CLEAR1 }; final CLOptionDescriptor[] options2 = new CLOptionDescriptor[] {}; final ParserControl control1 = new AbstractParserControl() { @Override public boolean isFinished(final int lastOptionCode) { return lastOptionCode == CLEAR1_OPT; } }; final CLArgsParser parser1 = new CLArgsParser(ARGLIST1, options1, control1); assertNull(parser1.getErrorString(), parser1.getErrorString()); final List<CLOption> clOptions1 = parser1.getArguments(); final int size1 = clOptions1.size(); assertEquals(size1, 4); assertEquals(clOptions1.get(0).getDescriptor().getId(), YOU_OPT); assertEquals(clOptions1.get(1).getDescriptor().getId(), 0); assertEquals(clOptions1.get(2).getDescriptor().getId(), ALL_OPT); assertEquals(clOptions1.get(3).getDescriptor().getId(), CLEAR1_OPT); assertEquals("ler", parser1.getUnparsedArgs()[0]); final CLArgsParser parser2 = new CLArgsParser(parser1.getUnparsedArgs(), options2); assertNull(parser2.getErrorString(), parser2.getErrorString()); final List<CLOption> clOptions2 = parser2.getArguments(); final int size2 = clOptions2.size(); assertEquals(size2, 2); assertEquals(clOptions2.get(0).getDescriptor().getId(), 0); assertEquals(clOptions2.get(1).getDescriptor().getId(), 0); } @Test public void testDuplicatesFail() { final CLOptionDescriptor[] options = new CLOptionDescriptor[] { YOU, ALL, CLEAR1, CLEAR2, CLEAR3, CLEAR5 }; final CLArgsParser parser = new CLArgsParser(ARGLIST1, options); assertNull(parser.getErrorString(), parser.getErrorString()); } @Test public void testIncomplete2Args() { // "-Dstupid=" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE }; final CLArgsParser parser = new CLArgsParser(new String[] { "-Dstupid=" }, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 1); final CLOption option = clOptions.get(0); assertEquals(option.getDescriptor().getId(), DEFINE_OPT); assertEquals(option.getArgument(0), "stupid"); assertEquals(option.getArgument(1), ""); } @Test public void testIncomplete2ArgsMixed() { // "-Dstupid=","-c" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE, CLEAR1 }; final String[] args = new String[] { "-Dstupid=", "-c" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 2); assertEquals(clOptions.get(1).getDescriptor().getId(), CLEAR1_OPT); final CLOption option = clOptions.get(0); assertEquals(option.getDescriptor().getId(), DEFINE_OPT); assertEquals(option.getArgument(0), "stupid"); assertEquals(option.getArgument(1), ""); } @Test public void testIncomplete2ArgsMixedNoEq() { // "-Dstupid","-c" final CLOptionDescriptor[] options = new CLOptionDescriptor[] { DEFINE, CLEAR1 }; final String[] args = new String[] { "-DStupid", "-c" }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); assertEquals(size, 2); assertEquals(clOptions.get(1).getDescriptor().getId(), CLEAR1_OPT); final CLOption option = clOptions.get(0); assertEquals(option.getDescriptor().getId(), DEFINE_OPT); assertEquals(option.getArgument(0), "Stupid"); assertEquals(option.getArgument(1), ""); } /** * Test the getArgumentById and getArgumentByName lookup methods. */ @Test public void testArgumentLookup() { final String[] args = { "-f", "testarg" }; final CLOptionDescriptor[] options = { FILE }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); CLOption optionById = parser.getArgumentById(FILE_OPT); assertNotNull(optionById); assertEquals(FILE_OPT, optionById.getDescriptor().getId()); assertEquals("testarg", optionById.getArgument()); CLOption optionByName = parser.getArgumentByName(FILE.getName()); assertNotNull(optionByName); assertEquals(FILE_OPT, optionByName.getDescriptor().getId()); assertEquals("testarg", optionByName.getArgument()); } /** * Test that you can have null long forms. */ @Test public void testNullLongForm() { final CLOptionDescriptor test = new CLOptionDescriptor(null, CLOptionDescriptor.ARGUMENT_DISALLOWED, 'n', "test null long form"); final String[] args = { "-n", "testarg" }; final CLOptionDescriptor[] options = { test }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final CLOption optionByID = parser.getArgumentById('n'); assertNotNull(optionByID); assertEquals('n', optionByID.getDescriptor().getId()); final CLOption optionByName = parser.getArgumentByName(FILE.getName()); assertNull(optionByName, "Looking for non-existent option by name"); } /** * Test that you can have null descriptions. */ @Test public void testNullDescription() { final CLOptionDescriptor test = new CLOptionDescriptor("nulltest", CLOptionDescriptor.ARGUMENT_DISALLOWED, 'n', null); final String[] args = { "-n", "testarg" }; final CLOptionDescriptor[] options = { test }; final CLArgsParser parser = new CLArgsParser(args, options); assertNull(parser.getErrorString(), parser.getErrorString()); final CLOption optionByID = parser.getArgumentById('n'); assertNotNull(optionByID); assertEquals('n', optionByID.getDescriptor().getId()); final StringBuilder sb = CLUtil.describeOptions(options); final String lineSeparator = System.getProperty("line.separator"); assertEquals("\t-n, --nulltest" + lineSeparator, sb.toString(), "Testing display of null description"); } @Test public void testCombinations() throws Exception { check(new String [] {},""); check(new String [] {"--none", "-0" }, "-0 -0"); // Canonical form check(new String [] {"--one=a", "--one","A", "-1b", "-1=c", "-1","d" }, "-1=[a] -1=[A] -1=[b] -1=[c] -1=[d]"); check(new String [] {"-2n=v", "-2","N=V" }, "-2=[n, v] -2=[N, V]"); check(new String [] {"--two=n=v", "--two","N=V" }, "-2=[n, v] -2=[N, V]"); // Test optional arguments check(new String [] {"-?", "A", // Separate argument "-?=B", "-?C", "-?" }, "-? [A] -?=[B] -?=[C] -?"); check(new String [] {"--optional=A", // OK "--optional","B", // should treat B as separate "--optional" // Should have no arg }, "-?=[A] -? [B] -?"); } private void check(String[] args, String canon){ final CLArgsParser parser = new CLArgsParser(args, OPTIONS); assertNull(parser.getErrorString(), parser.getErrorString()); final List<CLOption> clOptions = parser.getArguments(); final int size = clOptions.size(); StringBuilder sb = new StringBuilder(); for (int i=0; i< size; i++){ if (i>0) { sb.append(" "); } sb.append(clOptions.get(i).toShortString()); } assertEquals(canon, sb.toString(), "Canonical form ("+size+")"); } /* * TODO add tests to check for: - name clash - long option abbreviations * (match shortest unique abbreviation) */ }
google/tsunami-security-scanner-plugins
37,438
google/portscan/nmap/src/main/java/com/google/tsunami/plugins/portscan/nmap/client/parser/NmapResultHandler.java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.tsunami.plugins.portscan.nmap.client.parser; import static com.google.common.base.Preconditions.checkNotNull; import com.google.auto.value.AutoValue; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.flogger.GoogleLogger; import com.google.tsunami.plugins.portscan.nmap.client.result.Address; import com.google.tsunami.plugins.portscan.nmap.client.result.Cpe; import com.google.tsunami.plugins.portscan.nmap.client.result.Debugging; import com.google.tsunami.plugins.portscan.nmap.client.result.Distance; import com.google.tsunami.plugins.portscan.nmap.client.result.Elem; import com.google.tsunami.plugins.portscan.nmap.client.result.ExtraPorts; import com.google.tsunami.plugins.portscan.nmap.client.result.ExtraReasons; import com.google.tsunami.plugins.portscan.nmap.client.result.Finished; import com.google.tsunami.plugins.portscan.nmap.client.result.Hop; import com.google.tsunami.plugins.portscan.nmap.client.result.Host; import com.google.tsunami.plugins.portscan.nmap.client.result.HostScript; import com.google.tsunami.plugins.portscan.nmap.client.result.Hostname; import com.google.tsunami.plugins.portscan.nmap.client.result.Hostnames; import com.google.tsunami.plugins.portscan.nmap.client.result.Hosts; import com.google.tsunami.plugins.portscan.nmap.client.result.IpIdSequence; import com.google.tsunami.plugins.portscan.nmap.client.result.NmapRun; import com.google.tsunami.plugins.portscan.nmap.client.result.Os; import com.google.tsunami.plugins.portscan.nmap.client.result.OsClass; import com.google.tsunami.plugins.portscan.nmap.client.result.OsFingerprint; import com.google.tsunami.plugins.portscan.nmap.client.result.OsMatch; import com.google.tsunami.plugins.portscan.nmap.client.result.Output; import com.google.tsunami.plugins.portscan.nmap.client.result.Owner; import com.google.tsunami.plugins.portscan.nmap.client.result.Port; import com.google.tsunami.plugins.portscan.nmap.client.result.PortUsed; import com.google.tsunami.plugins.portscan.nmap.client.result.Ports; import com.google.tsunami.plugins.portscan.nmap.client.result.PostScript; import com.google.tsunami.plugins.portscan.nmap.client.result.PreScript; import com.google.tsunami.plugins.portscan.nmap.client.result.RunStats; import com.google.tsunami.plugins.portscan.nmap.client.result.ScanInfo; import com.google.tsunami.plugins.portscan.nmap.client.result.Script; import com.google.tsunami.plugins.portscan.nmap.client.result.Service; import com.google.tsunami.plugins.portscan.nmap.client.result.Smurf; import com.google.tsunami.plugins.portscan.nmap.client.result.Status; import com.google.tsunami.plugins.portscan.nmap.client.result.Table; import com.google.tsunami.plugins.portscan.nmap.client.result.Target; import com.google.tsunami.plugins.portscan.nmap.client.result.TaskBegin; import com.google.tsunami.plugins.portscan.nmap.client.result.TaskEnd; import com.google.tsunami.plugins.portscan.nmap.client.result.TaskProgress; import com.google.tsunami.plugins.portscan.nmap.client.result.TcpSequence; import com.google.tsunami.plugins.portscan.nmap.client.result.TcpTsSequence; import com.google.tsunami.plugins.portscan.nmap.client.result.Times; import com.google.tsunami.plugins.portscan.nmap.client.result.Trace; import com.google.tsunami.plugins.portscan.nmap.client.result.Uptime; import com.google.tsunami.plugins.portscan.nmap.client.result.Verbose; import java.util.ArrayDeque; import java.util.Arrays; import org.checkerframework.checker.nullness.qual.Nullable; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Concrete implementation for a stack-based SAX {@link DefaultHandler} to parse Nmap XML scan * result. * * <p>The definition of the Nmap result XML can be found using the following link: * https://raw.githubusercontent.com/nmap/nmap/e7e7e9e8c7d83b4ca93a752dea7bb40cbb74df32/docs/nmap.dtd */ @SuppressWarnings("unused") public final class NmapResultHandler extends DefaultHandler { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); private static final ImmutableSet<State> SCRIPT_ANCESTORS = ImmutableSet.of( State.IN_PRE_SCRIPT, State.IN_POST_SCRIPT, State.IN_HOST_SCRIPT, State.IN_PORT); private static final ImmutableSet<State> TABLE_ANCESTORS = ImmutableSet.of(State.IN_SCRIPT, State.IN_TABLE); private static final ImmutableSet<State> ELEM_ANCESTORS = ImmutableSet.of(State.IN_SCRIPT, State.IN_TABLE); private static final ImmutableSet<State> CPE_ANCESTORS = ImmutableSet.of(State.IN_SERVICE, State.IN_OS_CLASS); private static final String NMAP_RUN_ELEM = "nmaprun"; private static final String SCAN_INFO_ELEM = "scaninfo"; private static final String VERBOSE_ELEM = "verbose"; private static final String DEBUGGING_ELEM = "debugging"; private static final String TARGET_ELEM = "target"; private static final String TASK_BEGIN_ELEM = "taskbegin"; private static final String TASK_PROGRESS_ELEM = "taskprogress"; private static final String TASK_END_ELEM = "taskend"; private static final String PRE_SCRIPT_ELEM = "prescript"; private static final String POST_SCRIPT_ELEM = "postscript"; private static final String OUTPUT_ELEM = "output"; private static final String HOST_ELEM = "host"; private static final String RUN_STATS_ELEM = "runstats"; private static final String FINISHED_ELEM = "finished"; private static final String HOSTS_ELEM = "hosts"; private static final String SCRIPT_ELEM = "script"; private static final String CPE_ELEM = "cpe"; private static final String TABLE_ELEM = "table"; private static final String ELEM_ELEM = "elem"; private static final String STATUS_ELEM = "status"; private static final String ADDRESS_ELEM = "address"; private static final String HOSTNAMES_ELEM = "hostnames"; private static final String HOSTNAME_ELEM = "hostname"; private static final String SMURF_ELEM = "smurf"; private static final String PORTS_ELEM = "ports"; private static final String OS_ELEM = "os"; private static final String DISTANCE_ELEM = "distance"; private static final String UPTIME_ELEM = "uptime"; private static final String TCP_SEQUENCE_ELEM = "tcpsequence"; private static final String IP_ID_SEQUENCE_ELEM = "ipidsequence"; private static final String TCP_TS_SEQUENCE_ELEM = "tcptssequence"; private static final String HOST_SCRIPT_ELEM = "hostscript"; private static final String TRACE_ELEM = "trace"; private static final String HOP_ELEM = "hop"; private static final String TIMES_ELEM = "times"; private static final String PORT_USED_ELEM = "portused"; private static final String OS_MATCH_ELEM = "osmatch"; private static final String OS_CLASS_ELEM = "osclass"; private static final String OS_FINGERPRINT_ELEM = "osfingerprint"; private static final String EXTRA_PORTS_ELEM = "extraports"; private static final String EXTRA_REASONS_ELEM = "extrareasons"; private static final String PORT_ELEM = "port"; private static final String STATE_ELEM = "state"; private static final String OWNER_ELEM = "owner"; private static final String SERVICE_ELEM = "service"; /** The stack maintaining the state for this parser. */ private final ArrayDeque<SaxHandlerState> stateStack; private NmapRun.Builder nmapRunBuilder; private ScanInfo.Builder scanInfoBuilder; private Verbose.Builder verboseBuilder; private Debugging.Builder debuggingBuilder; private Target.Builder targetBuilder; private TaskBegin.Builder taskBeginBuilder; private TaskProgress.Builder taskProgressBuilder; private TaskEnd.Builder taskEndBuilder; private PreScript.Builder preScriptBuilder; private PostScript.Builder postScriptBuilder; private Host.Builder hostBuilder; private Output.Builder outputBuilder; private RunStats.Builder runStatsBuilder; private Finished.Builder finishedBuilder; private Hosts.Builder hostsBuilder; private Script.Builder scriptBuilder; private Cpe.Builder cpeBuilder; private ArrayDeque<Table.Builder> tableBuilderStack; private Elem.Builder elemBuilder; private Status.Builder statusBuilder; private Address.Builder addressBuilder; private Hostnames.Builder hostnamesBuilder; private Hostname.Builder hostnameBuilder; private Smurf.Builder smurfBuilder; private Ports.Builder portsBuilder; private Os.Builder osBuilder; private Distance.Builder distanceBuilder; private Uptime.Builder uptimeBuilder; private TcpSequence.Builder tcpSequenceBuilder; private IpIdSequence.Builder ipIdSequenceBuilder; private TcpTsSequence.Builder tcpTsSequenceBuilder; private HostScript.Builder hostScriptBuilder; private Trace.Builder traceBuilder; private Hop.Builder hopBuilder; private Times.Builder timesBuilder; private PortUsed.Builder portUsedBuilder; private OsMatch.Builder osMatchBuilder; private OsClass.Builder osClassBuilder; private OsFingerprint.Builder osFingerprintBuilder; private ExtraPorts.Builder extraPortsBuilder; private ExtraReasons.Builder extraReasonsBuilder; private Port.Builder portBuilder; private com.google.tsunami.plugins.portscan.nmap.client.result.State.Builder stateBuilder; private Owner.Builder ownerBuilder; private Service.Builder serviceBuilder; public NmapResultHandler() { this.stateStack = new ArrayDeque<>(); this.tableBuilderStack = new ArrayDeque<>(); } enum State { INIT, // nmaprun children. IN_NMAP_RUN, IN_SCAN_INFO, IN_VERBOSE, IN_DEBUGGING, IN_TARGET, IN_TASK_BEGIN, IN_TASK_PROGRESS, IN_TASK_END, IN_PRE_SCRIPT, IN_POST_SCRIPT, IN_HOST, IN_OUTPUT, IN_RUN_STATS, // runstats children. IN_FINISHED, IN_HOSTS, // common children. IN_SCRIPT, IN_CPE, // script children. IN_TABLE, IN_ELEM, // host children. IN_STATUS, IN_ADDRESS, IN_HOSTNAMES, IN_HOSTNAME, IN_SMURF, IN_PORTS, IN_OS, IN_DISTANCE, IN_UPTIME, IN_TCP_SEQUENCE, IN_IP_ID_SEQUENCE, IN_TCP_TS_SEQUENCE, IN_HOST_SCRIPT, IN_TRACE, IN_HOP, IN_TIMES, // os children. IN_PORT_USED, IN_OS_MATCH, IN_OS_CLASS, IN_OS_FINGERPRINT, // ports children. IN_EXTRA_PORTS, IN_EXTRA_REASONS, IN_PORT, // port children. IN_STATE, IN_OWNER, IN_SERVICE, UNRECOGNIZED_ELEMENT } public NmapRun getNmapRun() { return nmapRunBuilder.build(); } @Override public void startDocument() { logger.atInfo().log("Start parsing Nmap result document."); pushState(State.INIT); } @Override public void endDocument() throws SAXException { logger.atInfo().log("Finished parsing Nmap result document."); exitState(State.INIT); } @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { XmlAttributes attributes = XmlAttributes.from(attrs); switch (qName) { case NMAP_RUN_ELEM: enterState(State.INIT, State.IN_NMAP_RUN); nmapRunBuilder = NmapRun.builder() .setScanner(attributes.getValue("scanner", "")) .setArgs(attributes.getValue("args", "")) .setStart(attributes.getValue("start", "")) .setStartStr(attributes.getValue("startstr", "")) .setVersion(attributes.getValue("version", "")) .setProfileName(attributes.getValue("profile_name", "")) .setXmlOutputVersion(attributes.getValue("xmloutputversion", "")); break; // nmaprun children. case SCAN_INFO_ELEM: enterState(State.IN_NMAP_RUN, State.IN_SCAN_INFO); scanInfoBuilder = ScanInfo.builder() .setType(attributes.getValue("type", "")) .setScanFlags(attributes.getValue("scanflags", "")) .setProtocol(attributes.getValue("protocol", "")) .setNumServices(attributes.getValue("numservices", "")) .setServices(attributes.getValue("services", "")); break; case VERBOSE_ELEM: enterState(State.IN_NMAP_RUN, State.IN_VERBOSE); verboseBuilder = Verbose.builder().setLevel(attributes.getValue("level", "")); break; case DEBUGGING_ELEM: enterState(State.IN_NMAP_RUN, State.IN_DEBUGGING); debuggingBuilder = Debugging.builder().setLevel(attributes.getValue("level", "")); break; case TARGET_ELEM: enterState(State.IN_NMAP_RUN, State.IN_TARGET); targetBuilder = Target.builder() .setSpecification(attributes.getValue("specification", "")) .setStatus(attributes.getValue("status", "")) .setReason(attributes.getValue("reason", "")); break; case TASK_BEGIN_ELEM: enterState(State.IN_NMAP_RUN, State.IN_TASK_BEGIN); taskBeginBuilder = TaskBegin.builder() .setTask(attributes.getValue("task", "")) .setTime(attributes.getValue("time", "")) .setExtraInfo(attributes.getValue("extrainfo", "")); break; case TASK_PROGRESS_ELEM: enterState(State.IN_NMAP_RUN, State.IN_TASK_PROGRESS); taskProgressBuilder = TaskProgress.builder() .setTask(attributes.getValue("task", "")) .setTime(attributes.getValue("time", "")) .setPercent(attributes.getValue("percent", "")) .setRemaining(attributes.getValue("remaining", "")) .setEtc(attributes.getValue("etc", "")); break; case TASK_END_ELEM: enterState(State.IN_NMAP_RUN, State.IN_TASK_END); taskEndBuilder = TaskEnd.builder() .setTask(attributes.getValue("task", "")) .setTime(attributes.getValue("time", "")) .setExtraInfo(attributes.getValue("extrainfo", "")); break; case PRE_SCRIPT_ELEM: enterState(State.IN_NMAP_RUN, State.IN_PRE_SCRIPT); preScriptBuilder = PreScript.builder(); break; case POST_SCRIPT_ELEM: enterState(State.IN_NMAP_RUN, State.IN_POST_SCRIPT); postScriptBuilder = PostScript.builder(); break; case HOST_ELEM: enterState(State.IN_NMAP_RUN, State.IN_HOST); hostBuilder = Host.builder() .setStartTime(attributes.getValue("starttime", "")) .setEndTime(attributes.getValue("endtime", "")) .setComment(attributes.getValue("comment", "")); break; case OUTPUT_ELEM: enterTextCollectingState(State.IN_NMAP_RUN, State.IN_OUTPUT); outputBuilder = Output.builder().setType(attributes.getValue("type", "")); break; case RUN_STATS_ELEM: enterState(State.IN_NMAP_RUN, State.IN_RUN_STATS); runStatsBuilder = RunStats.builder(); break; // runstats children. case FINISHED_ELEM: enterState(State.IN_RUN_STATS, State.IN_FINISHED); finishedBuilder = Finished.builder() .setTime(attributes.getValue("time", "")) .setTimeStr(attributes.getValue("timestr", "")) .setElapsed(attributes.getValue("elapsed", "")) .setSummary(attributes.getValue("summary", "")) .setExit(attributes.getValue("exit", "")) .setErrorMsg(attributes.getValue("errormsg", "")); break; case HOSTS_ELEM: enterState(State.IN_RUN_STATS, State.IN_HOSTS); hostsBuilder = Hosts.builder() .setUp(attributes.getValue("up", "0")) .setDown(attributes.getValue("down", "0")) .setTotal(attributes.getValue("total", "")); break; // common children. case SCRIPT_ELEM: if (!SCRIPT_ANCESTORS.contains(stateStack.peekFirst().state())) { throw newInvalidStateException(stateStack.peekFirst().state(), SCRIPT_ANCESTORS); } enterTextCollectingState(stateStack.peekFirst().state(), State.IN_SCRIPT); scriptBuilder = Script.builder() .setId(attributes.getValue("id", "")) .setOutput(attributes.getValue("output", "")); break; case CPE_ELEM: if (!CPE_ANCESTORS.contains(stateStack.peekFirst().state())) { throw newInvalidStateException(stateStack.peekFirst().state(), CPE_ANCESTORS); } enterTextCollectingState(stateStack.peekFirst().state(), State.IN_CPE); cpeBuilder = Cpe.builder(); break; // script children. case TABLE_ELEM: if (!TABLE_ANCESTORS.contains(stateStack.peekFirst().state())) { throw newInvalidStateException(stateStack.peekFirst().state(), TABLE_ANCESTORS); } enterState(stateStack.peekFirst().state(), State.IN_TABLE); tableBuilderStack.addFirst(Table.builder().setKey(attributes.getValue("key", ""))); break; case ELEM_ELEM: if (!ELEM_ANCESTORS.contains(stateStack.peekFirst().state())) { throw newInvalidStateException(stateStack.peekFirst().state(), ELEM_ANCESTORS); } enterTextCollectingState(stateStack.peekFirst().state(), State.IN_ELEM); elemBuilder = Elem.builder().setKey(attributes.getValue("key", "")); break; // host children. case STATUS_ELEM: enterState(State.IN_HOST, State.IN_STATUS); statusBuilder = Status.builder() .setState(attributes.getValue("state", "")) .setReason(attributes.getValue("reason", "")) .setReasonTtl(attributes.getValue("reason_ttl", "")); break; case ADDRESS_ELEM: enterState(State.IN_HOST, State.IN_ADDRESS); addressBuilder = Address.builder() .setAddr(attributes.getValue("addr", "")) .setAddrType(attributes.getValue("addrtype", "ipv4")) .setVendor(attributes.getValue("vendor", "")); break; case HOSTNAMES_ELEM: enterState(State.IN_HOST, State.IN_HOSTNAMES); hostnamesBuilder = Hostnames.builder(); break; case HOSTNAME_ELEM: enterState(State.IN_HOSTNAMES, State.IN_HOSTNAME); hostnameBuilder = Hostname.builder() .setName(attributes.getValue("name", "")) .setType(attributes.getValue("type", "")); break; case SMURF_ELEM: enterState(State.IN_HOST, State.IN_SMURF); smurfBuilder = Smurf.builder().setResponses(attributes.getValue("responses", "")); break; case PORTS_ELEM: enterState(State.IN_HOST, State.IN_PORTS); portsBuilder = Ports.builder(); break; case OS_ELEM: enterState(State.IN_HOST, State.IN_OS); osBuilder = Os.builder(); break; case DISTANCE_ELEM: enterState(State.IN_HOST, State.IN_DISTANCE); distanceBuilder = Distance.builder().setValue(attributes.getValue("value", "")); break; case UPTIME_ELEM: enterState(State.IN_HOST, State.IN_UPTIME); uptimeBuilder = Uptime.builder() .setSeconds(attributes.getValue("seconds", "")) .setLastBoot(attributes.getValue("lastboot", "")); break; case TCP_SEQUENCE_ELEM: enterState(State.IN_HOST, State.IN_TCP_SEQUENCE); tcpSequenceBuilder = TcpSequence.builder() .setIndex(attributes.getValue("index", "")) .setDifficulty(attributes.getValue("difficulty", "")) .setValues(attributes.getValue("values", "")); break; case IP_ID_SEQUENCE_ELEM: enterState(State.IN_HOST, State.IN_IP_ID_SEQUENCE); ipIdSequenceBuilder = IpIdSequence.builder() .setClazz(attributes.getValue("class", "")) .setValues(attributes.getValue("values", "")); break; case TCP_TS_SEQUENCE_ELEM: enterState(State.IN_HOST, State.IN_TCP_TS_SEQUENCE); tcpTsSequenceBuilder = TcpTsSequence.builder() .setClazz(attributes.getValue("class", "")) .setValues(attributes.getValue("values", "")); break; case HOST_SCRIPT_ELEM: enterState(State.IN_HOST, State.IN_HOST_SCRIPT); hostScriptBuilder = HostScript.builder(); break; case TRACE_ELEM: enterState(State.IN_HOST, State.IN_TRACE); traceBuilder = Trace.builder() .setProto(attributes.getValue("proto", "")) .setPort(attributes.getValue("port", "")); break; case HOP_ELEM: enterState(State.IN_TRACE, State.IN_HOP); hopBuilder = Hop.builder() .setTtl(attributes.getValue("ttl", "")) .setRtt(attributes.getValue("rtt", "")) .setIpAddr(attributes.getValue("ipaddr", "")) .setHost(attributes.getValue("host", "")); break; case TIMES_ELEM: enterState(State.IN_HOST, State.IN_TIMES); timesBuilder = Times.builder() .setSrtt(attributes.getValue("srtt", "")) .setRttVar(attributes.getValue("rttvar", "")) .setTo(attributes.getValue("to", "")); break; // os children. case PORT_USED_ELEM: enterState(State.IN_OS, State.IN_PORT_USED); portUsedBuilder = PortUsed.builder() .setState(attributes.getValue("state", "")) .setProto(attributes.getValue("proto", "")) .setPortId(attributes.getValue("portid", "")); break; case OS_MATCH_ELEM: enterState(State.IN_OS, State.IN_OS_MATCH); osMatchBuilder = OsMatch.builder() .setName(attributes.getValue("name", "")) .setAccuracy(attributes.getValue("accuracy", "")) .setLine(attributes.getValue("line", "")); break; case OS_CLASS_ELEM: enterState(State.IN_OS_MATCH, State.IN_OS_CLASS); osClassBuilder = OsClass.builder() .setVendor(attributes.getValue("vendor", "")) .setOsGen(attributes.getValue("osgen", "")) .setType(attributes.getValue("type", "")) .setAccuracy(attributes.getValue("accuracy", "")) .setOsFamily(attributes.getValue("osfamily", "")); break; case OS_FINGERPRINT_ELEM: enterState(State.IN_OS, State.IN_OS_FINGERPRINT); osFingerprintBuilder = OsFingerprint.builder().setFingerprint(attributes.getValue("fingerprint", "")); break; // ports children. case EXTRA_PORTS_ELEM: enterState(State.IN_PORTS, State.IN_EXTRA_PORTS); extraPortsBuilder = ExtraPorts.builder() .setState(attributes.getValue("state", "")) .setCount(attributes.getValue("count", "")); break; case EXTRA_REASONS_ELEM: enterState(State.IN_EXTRA_PORTS, State.IN_EXTRA_REASONS); extraReasonsBuilder = ExtraReasons.builder() .setReason(attributes.getValue("reason", "")) .setCount(attributes.getValue("count", "")); break; case PORT_ELEM: enterState(State.IN_PORTS, State.IN_PORT); portBuilder = Port.builder() .setProtocol(attributes.getValue("protocol", "")) .setPortId(attributes.getValue("portid", "")); break; // port children. case STATE_ELEM: enterState(State.IN_PORT, State.IN_STATE); stateBuilder = com.google.tsunami.plugins.portscan.nmap.client.result.State.builder() .setState(attributes.getValue("state", "")) .setReason(attributes.getValue("reason", "")) .setReasonTtl(attributes.getValue("reason_ttl", "")) .setReasonIp(attributes.getValue("reason_ip", "")); break; case OWNER_ELEM: enterState(State.IN_PORT, State.IN_OWNER); ownerBuilder = Owner.builder().setName(attributes.getValue("name", "")); break; case SERVICE_ELEM: enterState(State.IN_PORT, State.IN_SERVICE); serviceBuilder = Service.builder() .setName(attributes.getValue("name", "")) .setConf(attributes.getValue("conf", "")) .setMethod(attributes.getValue("method", "")) .setVersion(attributes.getValue("version", "")) .setProduct(attributes.getValue("product", "")) .setExtraInfo(attributes.getValue("extrainfo", "")) .setTunnel(attributes.getValue("tunnel", "")) .setProto(attributes.getValue("proto", "")) .setRpcNum(attributes.getValue("rpcnum", "")) .setLowVer(attributes.getValue("lowver", "")) .setHighVer(attributes.getValue("highver", "")) .setHostname(attributes.getValue("hostname", "")) .setOsType(attributes.getValue("ostype", "")) .setDeviceType(attributes.getValue("devicetype", "")) .setServiceFp(attributes.getValue("servicefp", "")); break; default: pushState(State.UNRECOGNIZED_ELEMENT); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { switch (qName) { case NMAP_RUN_ELEM: exitState(State.IN_NMAP_RUN); break; // nmaprun children. case SCAN_INFO_ELEM: exitState(State.IN_SCAN_INFO); nmapRunBuilder.addScanInfo(scanInfoBuilder.build()); break; case VERBOSE_ELEM: exitState(State.IN_VERBOSE); nmapRunBuilder.setVerbose(verboseBuilder.build()); break; case DEBUGGING_ELEM: exitState(State.IN_DEBUGGING); nmapRunBuilder.setDebugging(debuggingBuilder.build()); break; case TARGET_ELEM: exitState(State.IN_TARGET); nmapRunBuilder.addValueElement(targetBuilder.build()); break; case TASK_BEGIN_ELEM: exitState(State.IN_TASK_BEGIN); nmapRunBuilder.addValueElement(taskBeginBuilder.build()); break; case TASK_PROGRESS_ELEM: exitState(State.IN_TASK_PROGRESS); nmapRunBuilder.addValueElement(taskProgressBuilder.build()); break; case TASK_END_ELEM: exitState(State.IN_TASK_END); nmapRunBuilder.addValueElement(taskEndBuilder.build()); break; case PRE_SCRIPT_ELEM: exitState(State.IN_PRE_SCRIPT); nmapRunBuilder.addValueElement(preScriptBuilder.build()); break; case POST_SCRIPT_ELEM: exitState(State.IN_POST_SCRIPT); nmapRunBuilder.addValueElement(postScriptBuilder.build()); break; case HOST_ELEM: exitState(State.IN_HOST); nmapRunBuilder.addValueElement(hostBuilder.build()); break; case OUTPUT_ELEM: SaxHandlerState outputState = exitState(State.IN_OUTPUT); nmapRunBuilder.addValueElement( outputBuilder.setValue(outputState.textValueBuilder().toString()).build()); break; case RUN_STATS_ELEM: exitState(State.IN_RUN_STATS); nmapRunBuilder.setRunStats(runStatsBuilder.build()); break; // runstats finished. case FINISHED_ELEM: exitState(State.IN_FINISHED); runStatsBuilder.setFinished(finishedBuilder.build()); break; case HOSTS_ELEM: exitState(State.IN_HOSTS); runStatsBuilder.setHosts(hostsBuilder.build()); break; // common children. case SCRIPT_ELEM: { SaxHandlerState scriptState = exitState(State.IN_SCRIPT); State prevState = stateStack.peekFirst().state(); Script script = scriptBuilder.addValueElement(scriptState.textValueBuilder().toString()).build(); if (prevState.equals(State.IN_PRE_SCRIPT)) { preScriptBuilder.addScript(script); } else if (prevState.equals(State.IN_POST_SCRIPT)) { postScriptBuilder.addScript(script); } else if (prevState.equals(State.IN_HOST_SCRIPT)) { hostScriptBuilder.addScript(script); } else if (prevState.equals(State.IN_PORT)) { portBuilder.addScript(script); } else { throw newInvalidStateException(prevState, SCRIPT_ANCESTORS); } break; } case CPE_ELEM: { SaxHandlerState cpeState = exitState(State.IN_CPE); State prevState = stateStack.peekFirst().state(); Cpe cpe = cpeBuilder.setValue(cpeState.textValueBuilder().toString()).build(); if (prevState.equals(State.IN_OS_CLASS)) { osClassBuilder.addCpe(cpe); } else if (prevState.equals(State.IN_SERVICE)) { serviceBuilder.addCpe(cpe); } else { throw newInvalidStateException(prevState, CPE_ANCESTORS); } break; } // script children. case TABLE_ELEM: { exitState(State.IN_TABLE); State prevState = stateStack.peekFirst().state(); Table table = tableBuilderStack.removeFirst().build(); if (prevState.equals(State.IN_SCRIPT)) { scriptBuilder.addValueElement(table); } else if (prevState.equals(State.IN_TABLE)) { tableBuilderStack.peekFirst().addValueElement(table); } else { throw newInvalidStateException(prevState, TABLE_ANCESTORS); } break; } case ELEM_ELEM: { SaxHandlerState elemState = exitState(State.IN_ELEM); State prevState = stateStack.peekFirst().state(); Elem elem = elemBuilder.setValue(elemState.textValueBuilder().toString()).build(); if (prevState.equals(State.IN_SCRIPT)) { scriptBuilder.addValueElement(elem); } else if (prevState.equals(State.IN_TABLE)) { tableBuilderStack.peekFirst().addValueElement(elem); } else { throw newInvalidStateException(prevState, ELEM_ANCESTORS); } break; } // host children. case STATUS_ELEM: exitState(State.IN_STATUS); hostBuilder.addValueElement(statusBuilder.build()); break; case ADDRESS_ELEM: exitState(State.IN_ADDRESS); hostBuilder.addValueElement(addressBuilder.build()); break; case HOSTNAMES_ELEM: exitState(State.IN_HOSTNAMES); hostBuilder.addValueElement(hostnamesBuilder.build()); break; case HOSTNAME_ELEM: exitState(State.IN_HOSTNAME); hostnamesBuilder.addHostname(hostnameBuilder.build()); break; case SMURF_ELEM: exitState(State.IN_SMURF); hostBuilder.addValueElement(smurfBuilder.build()); break; case PORTS_ELEM: exitState(State.IN_PORTS); hostBuilder.addValueElement(portsBuilder.build()); break; case OS_ELEM: exitState(State.IN_OS); hostBuilder.addValueElement(osBuilder.build()); break; case DISTANCE_ELEM: exitState(State.IN_DISTANCE); hostBuilder.addValueElement(distanceBuilder.build()); break; case UPTIME_ELEM: exitState(State.IN_UPTIME); hostBuilder.addValueElement(uptimeBuilder.build()); break; case TCP_SEQUENCE_ELEM: exitState(State.IN_TCP_SEQUENCE); hostBuilder.addValueElement(tcpSequenceBuilder.build()); break; case IP_ID_SEQUENCE_ELEM: exitState(State.IN_IP_ID_SEQUENCE); hostBuilder.addValueElement(ipIdSequenceBuilder.build()); break; case TCP_TS_SEQUENCE_ELEM: exitState(State.IN_TCP_TS_SEQUENCE); hostBuilder.addValueElement(tcpTsSequenceBuilder.build()); break; case HOST_SCRIPT_ELEM: exitState(State.IN_HOST_SCRIPT); hostBuilder.addValueElement(hostScriptBuilder.build()); break; case TRACE_ELEM: exitState(State.IN_TRACE); hostBuilder.addValueElement(traceBuilder.build()); break; case HOP_ELEM: exitState(State.IN_HOP); traceBuilder.addHop(hopBuilder.build()); break; case TIMES_ELEM: exitState(State.IN_TIMES); hostBuilder.addValueElement(timesBuilder.build()); break; // os children. case PORT_USED_ELEM: exitState(State.IN_PORT_USED); osBuilder.addPortUsed(portUsedBuilder.build()); break; case OS_MATCH_ELEM: exitState(State.IN_OS_MATCH); osBuilder.addOsMatch(osMatchBuilder.build()); break; case OS_CLASS_ELEM: exitState(State.IN_OS_CLASS); osMatchBuilder.addOsClass(osClassBuilder.build()); break; case OS_FINGERPRINT_ELEM: exitState(State.IN_OS_FINGERPRINT); osBuilder.addOsFingerprint(osFingerprintBuilder.build()); break; // ports children. case EXTRA_PORTS_ELEM: exitState(State.IN_EXTRA_PORTS); portsBuilder.addExtraPorts(extraPortsBuilder.build()); break; case EXTRA_REASONS_ELEM: exitState(State.IN_EXTRA_REASONS); extraPortsBuilder.addExtraReasons(extraReasonsBuilder.build()); break; case PORT_ELEM: exitState(State.IN_PORT); portsBuilder.addPort(portBuilder.build()); break; // port children. case STATE_ELEM: exitState(State.IN_STATE); portBuilder.setState(stateBuilder.build()); break; case OWNER_ELEM: exitState(State.IN_OWNER); portBuilder.setOwner(ownerBuilder.build()); break; case SERVICE_ELEM: exitState(State.IN_SERVICE); portBuilder.setService(serviceBuilder.build()); break; default: exitState(State.UNRECOGNIZED_ELEMENT); } } @Override public void characters(char[] ch, int start, int length) { if (stateStack.peekFirst().textValueBuilder() != null) { stateStack.peek().textValueBuilder().append(ch, start, length); } } private void pushState(State newState) { checkNotNull(newState); stateStack.addFirst(SaxHandlerState.create(newState, null)); } private void enterState(State expectedCurrentState, State newState) throws SAXException { enterStateImpl(expectedCurrentState, newState, false); } private void enterTextCollectingState(State expectedCurrentState, State newState) throws SAXException { enterStateImpl(expectedCurrentState, newState, true); } private void enterStateImpl(State expectedCurrentState, State newState, boolean collectText) throws SAXException { SaxHandlerState curParserState = stateStack.peekFirst(); if (!curParserState.state().equals(expectedCurrentState)) { throw newInvalidStateException(curParserState.state(), expectedCurrentState); } stateStack.addFirst(SaxHandlerState.create(newState, collectText ? new StringBuilder() : null)); } private SaxHandlerState exitState(State expectedCurrentState) throws SAXException { SaxHandlerState curParserState = stateStack.peekFirst(); if (!curParserState.state().equals(expectedCurrentState)) { throw newInvalidStateException(curParserState.state(), expectedCurrentState); } return stateStack.removeFirst(); } private static SAXException newInvalidStateException( State currentState, State expectedState, State... otherExpectedStates) { return newInvalidStateException( currentState, ImmutableList.<State>builder() .add(expectedState) .addAll(Arrays.asList(otherExpectedStates)) .build()); } private static SAXException newInvalidStateException( State currentState, Iterable<State> expectedStates) { return new SAXException( String.format( "Invalid parser state: (expected:'one of [%s]', actual:'%s')", Joiner.on(",").join(expectedStates), currentState)); } @AutoValue abstract static class SaxHandlerState { abstract State state(); abstract @Nullable StringBuilder textValueBuilder(); static SaxHandlerState create(State state, @Nullable StringBuilder textValueBuilder) { return new AutoValue_NmapResultHandler_SaxHandlerState(state, textValueBuilder); } } }
googleapis/google-cloud-java
37,693
java-translate/proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/ListAdaptiveMtDatasetsRequest.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/adaptive_mt.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.translate.v3; /** * * * <pre> * Request message for listing all Adaptive MT datasets that the requestor has * access to. * </pre> * * Protobuf type {@code google.cloud.translation.v3.ListAdaptiveMtDatasetsRequest} */ public final class ListAdaptiveMtDatasetsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.translation.v3.ListAdaptiveMtDatasetsRequest) ListAdaptiveMtDatasetsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListAdaptiveMtDatasetsRequest.newBuilder() to construct. private ListAdaptiveMtDatasetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListAdaptiveMtDatasetsRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListAdaptiveMtDatasetsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.translate.v3.AdaptiveMtProto .internal_static_google_cloud_translation_v3_ListAdaptiveMtDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.translate.v3.AdaptiveMtProto .internal_static_google_cloud_translation_v3_ListAdaptiveMtDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.class, com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. Requested page size. The server may return fewer results than * requested. If unspecified, the server picks an appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } 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.cloud.translate.v3.ListAdaptiveMtDatasetsRequest)) { return super.equals(obj); } com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest other = (com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest 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.ListAdaptiveMtDatasetsRequest 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 listing all Adaptive MT datasets that the requestor has * access to. * </pre> * * Protobuf type {@code google.cloud.translation.v3.ListAdaptiveMtDatasetsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.translation.v3.ListAdaptiveMtDatasetsRequest) com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.translate.v3.AdaptiveMtProto .internal_static_google_cloud_translation_v3_ListAdaptiveMtDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.translate.v3.AdaptiveMtProto .internal_static_google_cloud_translation_v3_ListAdaptiveMtDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.class, com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.Builder.class); } // Construct using com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.translate.v3.AdaptiveMtProto .internal_static_google_cloud_translation_v3_ListAdaptiveMtDatasetsRequest_descriptor; } @java.lang.Override public com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest getDefaultInstanceForType() { return com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest build() { com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest buildPartial() { com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest result = new com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } } @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.ListAdaptiveMtDatasetsRequest) { return mergeFrom((com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest other) { if (other == com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The resource name of the project from which to list the Adaptive * MT datasets. `projects/{project-number-or-id}/locations/{location-id}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. Requested page size. The server may return fewer results than * requested. If unspecified, the server picks an appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Optional. Requested page size. The server may return fewer results than * requested. If unspecified, the server picks an appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Requested page size. The server may return fewer results than * requested. If unspecified, the server picks an appropriate default. * </pre> * * <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Optional. A token identifying a page of results the server should return. * Typically, this is the value of * ListAdaptiveMtDatasetsResponse.next_page_token returned from the * previous call to `ListAdaptiveMtDatasets` method. The first page is * returned if `page_token`is empty or missing. * </pre> * * <code>string page_token = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Optional. An expression for filtering the results of the request. * Filter is not supported yet. * </pre> * * <code>string filter = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 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.translation.v3.ListAdaptiveMtDatasetsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.translation.v3.ListAdaptiveMtDatasetsRequest) private static final com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest(); } public static com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListAdaptiveMtDatasetsRequest> PARSER = new com.google.protobuf.AbstractParser<ListAdaptiveMtDatasetsRequest>() { @java.lang.Override public ListAdaptiveMtDatasetsRequest 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<ListAdaptiveMtDatasetsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListAdaptiveMtDatasetsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.translate.v3.ListAdaptiveMtDatasetsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
37,818
jaxp/src/com/sun/org/apache/xpath/internal/objects/XString.java
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ /* * $Id: XString.java,v 1.2.4.1 2005/09/14 20:47:20 jeffsuttor Exp $ */ package com.sun.org.apache.xpath.internal.objects; import java.util.Locale; import com.sun.org.apache.xml.internal.dtm.DTM; import com.sun.org.apache.xml.internal.utils.XMLCharacterRecognizer; import com.sun.org.apache.xml.internal.utils.XMLString; import com.sun.org.apache.xml.internal.utils.XMLStringFactory; import com.sun.org.apache.xpath.internal.ExpressionOwner; import com.sun.org.apache.xpath.internal.XPathContext; import com.sun.org.apache.xpath.internal.XPathVisitor; /** * This class represents an XPath string object, and is capable of * converting the string to other types, such as a number. * @xsl.usage general */ public class XString extends XObject implements XMLString { static final long serialVersionUID = 2020470518395094525L; /** Empty string XString object */ public static final XString EMPTYSTRING = new XString(""); /** * Construct a XString object. This constructor exists for derived classes. * * @param val String object this will wrap. */ protected XString(Object val) { super(val); } /** * Construct a XNodeSet object. * * @param val String object this will wrap. */ public XString(String val) { super(val); } /** * Tell that this is a CLASS_STRING. * * @return type CLASS_STRING */ public int getType() { return CLASS_STRING; } /** * Given a request type, return the equivalent string. * For diagnostic purposes. * * @return type string "#STRING" */ public String getTypeString() { return "#STRING"; } /** * Tell if this object contains a java String object. * * @return true if this XMLString can return a string without creating one. */ public boolean hasString() { return true; } /** * Cast result object to a number. * * @return 0.0 if this string is null, numeric value of this string * or NaN */ public double num() { return toDouble(); } /** * Convert a string to a double -- Allowed input is in fixed * notation ddd.fff. * * @return A double value representation of the string, or return Double.NaN * if the string can not be converted. */ public double toDouble() { /* XMLCharacterRecognizer.isWhiteSpace(char c) methods treats the following * characters as white space characters. * ht - horizontal tab, nl - newline , cr - carriage return and sp - space * trim() methods by default also takes care of these white space characters * So trim() method is used to remove leading and trailing white spaces. */ XMLString s = trim(); double result = Double.NaN; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c != '-' && c != '.' && ( c < 0X30 || c > 0x39)) { // The character is not a '-' or a '.' or a digit // then return NaN because something is wrong. return result; } } try { result = Double.parseDouble(s.toString()); } catch (NumberFormatException e){} return result; } /** * Cast result object to a boolean. * * @return True if the length of this string object is greater * than 0. */ public boolean bool() { return str().length() > 0; } /** * Cast result object to a string. * * @return The string this wraps or the empty string if null */ public XMLString xstr() { return this; } /** * Cast result object to a string. * * @return The string this wraps or the empty string if null */ public String str() { return (null != m_obj) ? ((String) m_obj) : ""; } /** * Cast result object to a result tree fragment. * * @param support Xpath context to use for the conversion * * @return A document fragment with this string as a child node */ public int rtf(XPathContext support) { DTM frag = support.createDocumentFragment(); frag.appendTextChild(str()); return frag.getDocument(); } /** * Directly call the * characters method on the passed ContentHandler for the * string-value. Multiple calls to the * ContentHandler's characters methods may well occur for a single call to * this method. * * @param ch A non-null reference to a ContentHandler. * * @throws org.xml.sax.SAXException */ public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch) throws org.xml.sax.SAXException { String str = str(); ch.characters(str.toCharArray(), 0, str.length()); } /** * Directly call the * comment method on the passed LexicalHandler for the * string-value. * * @param lh A non-null reference to a LexicalHandler. * * @throws org.xml.sax.SAXException */ public void dispatchAsComment(org.xml.sax.ext.LexicalHandler lh) throws org.xml.sax.SAXException { String str = str(); lh.comment(str.toCharArray(), 0, str.length()); } /** * Returns the length of this string. * * @return the length of the sequence of characters represented by this * object. */ public int length() { return str().length(); } /** * Returns the character at the specified index. An index ranges * from <code>0</code> to <code>length() - 1</code>. The first character * of the sequence is at index <code>0</code>, the next at index * <code>1</code>, and so on, as for array indexing. * * @param index the index of the character. * @return the character at the specified index of this string. * The first character is at index <code>0</code>. * @exception IndexOutOfBoundsException if the <code>index</code> * argument is negative or not less than the length of this * string. */ public char charAt(int index) { return str().charAt(index); } /** * Copies characters from this string into the destination character * array. * * @param srcBegin index of the first character in the string * to copy. * @param srcEnd index after the last character in the string * to copy. * @param dst the destination array. * @param dstBegin the start offset in the destination array. * @exception IndexOutOfBoundsException If any of the following * is true: * <ul><li><code>srcBegin</code> is negative. * <li><code>srcBegin</code> is greater than <code>srcEnd</code> * <li><code>srcEnd</code> is greater than the length of this * string * <li><code>dstBegin</code> is negative * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than * <code>dst.length</code></ul> * @exception NullPointerException if <code>dst</code> is <code>null</code> */ public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { str().getChars(srcBegin, srcEnd, dst, dstBegin); } /** * Tell if two objects are functionally equal. * * @param obj2 Object to compare this to * * @return true if the two objects are equal * * @throws javax.xml.transform.TransformerException */ public boolean equals(XObject obj2) { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. int t = obj2.getType(); try { if (XObject.CLASS_NODESET == t) return obj2.equals(this); // If at least one object to be compared is a boolean, then each object // to be compared is converted to a boolean as if by applying the // boolean function. else if(XObject.CLASS_BOOLEAN == t) return obj2.bool() == bool(); // Otherwise, if at least one object to be compared is a number, then each object // to be compared is converted to a number as if by applying the number function. else if(XObject.CLASS_NUMBER == t) return obj2.num() == num(); } catch(javax.xml.transform.TransformerException te) { throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(te); } // Otherwise, both objects to be compared are converted to strings as // if by applying the string function. return xstr().equals(obj2.xstr()); } /** * Compares this string to the specified <code>String</code>. * The result is <code>true</code> if and only if the argument is not * <code>null</code> and is a <code>String</code> object that represents * the same sequence of characters as this object. * * @param obj2 the object to compare this <code>String</code> against. * @return <code>true</code> if the <code>String</code>s are equal; * <code>false</code> otherwise. * @see java.lang.String#compareTo(java.lang.String) * @see java.lang.String#equalsIgnoreCase(java.lang.String) */ public boolean equals(String obj2) { return str().equals(obj2); } /** * Compares this string to the specified object. * The result is <code>true</code> if and only if the argument is not * <code>null</code> and is a <code>String</code> object that represents * the same sequence of characters as this object. * * @param obj2 the object to compare this <code>String</code> * against. * @return <code>true</code> if the <code>String </code>are equal; * <code>false</code> otherwise. * @see java.lang.String#compareTo(java.lang.String) * @see java.lang.String#equalsIgnoreCase(java.lang.String) */ public boolean equals(XMLString obj2) { if (obj2 != null) { if (!obj2.hasString()) { return obj2.equals(str()); } else { return str().equals(obj2.toString()); } } return false; } /** * Compares this string to the specified object. * The result is <code>true</code> if and only if the argument is not * <code>null</code> and is a <code>String</code> object that represents * the same sequence of characters as this object. * * @param obj2 the object to compare this <code>String</code> * against. * @return <code>true</code> if the <code>String </code>are equal; * <code>false</code> otherwise. * @see java.lang.String#compareTo(java.lang.String) * @see java.lang.String#equalsIgnoreCase(java.lang.String) */ public boolean equals(Object obj2) { if (null == obj2) return false; // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. else if (obj2 instanceof XNodeSet) return obj2.equals(this); else if(obj2 instanceof XNumber) return obj2.equals(this); else return str().equals(obj2.toString()); } /** * Compares this <code>String</code> to another <code>String</code>, * ignoring case considerations. Two strings are considered equal * ignoring case if they are of the same length, and corresponding * characters in the two strings are equal ignoring case. * * @param anotherString the <code>String</code> to compare this * <code>String</code> against. * @return <code>true</code> if the argument is not <code>null</code> * and the <code>String</code>s are equal, * ignoring case; <code>false</code> otherwise. * @see #equals(Object) * @see java.lang.Character#toLowerCase(char) * @see java.lang.Character#toUpperCase(char) */ public boolean equalsIgnoreCase(String anotherString) { return str().equalsIgnoreCase(anotherString); } /** * Compares two strings lexicographically. * * @param xstr the <code>String</code> to be compared. * * @return the value <code>0</code> if the argument string is equal to * this string; a value less than <code>0</code> if this string * is lexicographically less than the string argument; and a * value greater than <code>0</code> if this string is * lexicographically greater than the string argument. * @exception java.lang.NullPointerException if <code>anotherString</code> * is <code>null</code>. */ public int compareTo(XMLString xstr) { int len1 = this.length(); int len2 = xstr.length(); int n = Math.min(len1, len2); int i = 0; int j = 0; while (n-- != 0) { char c1 = this.charAt(i); char c2 = xstr.charAt(j); if (c1 != c2) { return c1 - c2; } i++; j++; } return len1 - len2; } /** * Compares two strings lexicographically, ignoring case considerations. * This method returns an integer whose sign is that of * <code>this.toUpperCase().toLowerCase().compareTo( * str.toUpperCase().toLowerCase())</code>. * <p> * Note that this method does <em>not</em> take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides <em>collators</em> to allow * locale-sensitive ordering. * * @param str the <code>String</code> to be compared. * @return a negative integer, zero, or a positive integer as the * the specified String is greater than, equal to, or less * than this String, ignoring case considerations. * @see java.text.Collator#compare(String, String) * @since 1.2 */ public int compareToIgnoreCase(XMLString str) { // %REVIEW% Like it says, @since 1.2. Doesn't exist in earlier // versions of Java, hence we can't yet shell out to it. We can implement // it as character-by-character compare, but doing so efficiently // is likely to be (ahem) interesting. // // However, since nobody is actually _using_ this method yet: // return str().compareToIgnoreCase(str.toString()); throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException( new java.lang.NoSuchMethodException( "Java 1.2 method, not yet implemented")); } /** * Tests if this string starts with the specified prefix beginning * a specified index. * * @param prefix the prefix. * @param toffset where to begin looking in the string. * @return <code>true</code> if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index <code>toffset</code>; <code>false</code> otherwise. * The result is <code>false</code> if <code>toffset</code> is * negative or greater than the length of this * <code>String</code> object; otherwise the result is the same * as the result of the expression * <pre> * this.subString(toffset).startsWith(prefix) * </pre> * @exception java.lang.NullPointerException if <code>prefix</code> is * <code>null</code>. */ public boolean startsWith(String prefix, int toffset) { return str().startsWith(prefix, toffset); } /** * Tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return <code>true</code> if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; <code>false</code> otherwise. * Note also that <code>true</code> will be returned if the * argument is an empty string or is equal to this * <code>String</code> object as determined by the * {@link #equals(Object)} method. * @exception java.lang.NullPointerException if <code>prefix</code> is * <code>null</code>. */ public boolean startsWith(String prefix) { return startsWith(prefix, 0); } /** * Tests if this string starts with the specified prefix beginning * a specified index. * * @param prefix the prefix. * @param toffset where to begin looking in the string. * @return <code>true</code> if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index <code>toffset</code>; <code>false</code> otherwise. * The result is <code>false</code> if <code>toffset</code> is * negative or greater than the length of this * <code>String</code> object; otherwise the result is the same * as the result of the expression * <pre> * this.subString(toffset).startsWith(prefix) * </pre> * @exception java.lang.NullPointerException if <code>prefix</code> is * <code>null</code>. */ public boolean startsWith(XMLString prefix, int toffset) { int to = toffset; int tlim = this.length(); int po = 0; int pc = prefix.length(); // Note: toffset might be near -1>>>1. if ((toffset < 0) || (toffset > tlim - pc)) { return false; } while (--pc >= 0) { if (this.charAt(to) != prefix.charAt(po)) { return false; } to++; po++; } return true; } /** * Tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return <code>true</code> if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; <code>false</code> otherwise. * Note also that <code>true</code> will be returned if the * argument is an empty string or is equal to this * <code>String</code> object as determined by the * {@link #equals(Object)} method. * @exception java.lang.NullPointerException if <code>prefix</code> is * <code>null</code>. */ public boolean startsWith(XMLString prefix) { return startsWith(prefix, 0); } /** * Tests if this string ends with the specified suffix. * * @param suffix the suffix. * @return <code>true</code> if the character sequence represented by the * argument is a suffix of the character sequence represented by * this object; <code>false</code> otherwise. Note that the * result will be <code>true</code> if the argument is the * empty string or is equal to this <code>String</code> object * as determined by the {@link #equals(Object)} method. * @exception java.lang.NullPointerException if <code>suffix</code> is * <code>null</code>. */ public boolean endsWith(String suffix) { return str().endsWith(suffix); } /** * Returns a hashcode for this string. The hashcode for a * <code>String</code> object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using <code>int</code> arithmetic, where <code>s[i]</code> is the * <i>i</i>th character of the string, <code>n</code> is the length of * the string, and <code>^</code> indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ public int hashCode() { return str().hashCode(); } /** * Returns the index within this string of the first occurrence of the * specified character. If a character with value <code>ch</code> occurs * in the character sequence represented by this <code>String</code> * object, then the index of the first such occurrence is returned -- * that is, the smallest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is <code>true</code>. If no such character occurs in this string, * then <code>-1</code> is returned. * * @param ch a character. * @return the index of the first occurrence of the character in the * character sequence represented by this object, or * <code>-1</code> if the character does not occur. */ public int indexOf(int ch) { return str().indexOf(ch); } /** * Returns the index within this string of the first occurrence of the * specified character, starting the search at the specified index. * <p> * If a character with value <code>ch</code> occurs in the character * sequence represented by this <code>String</code> object at an index * no smaller than <code>fromIndex</code>, then the index of the first * such occurrence is returned--that is, the smallest value <i>k</i> * such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex) * </pre></blockquote> * is true. If no such character occurs in this string at or after * position <code>fromIndex</code>, then <code>-1</code> is returned. * <p> * There is no restriction on the value of <code>fromIndex</code>. If it * is negative, it has the same effect as if it were zero: this entire * string may be searched. If it is greater than the length of this * string, it has the same effect as if it were equal to the length of * this string: <code>-1</code> is returned. * * @param ch a character. * @param fromIndex the index to start the search from. * @return the index of the first occurrence of the character in the * character sequence represented by this object that is greater * than or equal to <code>fromIndex</code>, or <code>-1</code> * if the character does not occur. */ public int indexOf(int ch, int fromIndex) { return str().indexOf(ch, fromIndex); } /** * Returns the index within this string of the last occurrence of the * specified character. That is, the index returned is the largest * value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. * The String is searched backwards starting at the last character. * * @param ch a character. * @return the index of the last occurrence of the character in the * character sequence represented by this object, or * <code>-1</code> if the character does not occur. */ public int lastIndexOf(int ch) { return str().lastIndexOf(ch); } /** * Returns the index within this string of the last occurrence of the * specified character, searching backward starting at the specified * index. That is, the index returned is the largest value <i>k</i> * such that: * <blockquote><pre> * this.charAt(k) == ch) && (k <= fromIndex) * </pre></blockquote> * is true. * * @param ch a character. * @param fromIndex the index to start the search from. There is no * restriction on the value of <code>fromIndex</code>. If it is * greater than or equal to the length of this string, it has * the same effect as if it were equal to one less than the * length of this string: this entire string may be searched. * If it is negative, it has the same effect as if it were -1: * -1 is returned. * @return the index of the last occurrence of the character in the * character sequence represented by this object that is less * than or equal to <code>fromIndex</code>, or <code>-1</code> * if the character does not occur before that point. */ public int lastIndexOf(int ch, int fromIndex) { return str().lastIndexOf(ch, fromIndex); } /** * Returns the index within this string of the first occurrence of the * specified substring. The integer returned is the smallest value * <i>k</i> such that: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * is <code>true</code>. * * @param str any string. * @return if the string argument occurs as a substring within this * object, then the index of the first character of the first * such substring is returned; if it does not occur as a * substring, <code>-1</code> is returned. * @exception java.lang.NullPointerException if <code>str</code> is * <code>null</code>. */ public int indexOf(String str) { return str().indexOf(str); } /** * Returns the index within this string of the first occurrence of the * specified substring. The integer returned is the smallest value * <i>k</i> such that: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * is <code>true</code>. * * @param str any string. * @return if the string argument occurs as a substring within this * object, then the index of the first character of the first * such substring is returned; if it does not occur as a * substring, <code>-1</code> is returned. * @exception java.lang.NullPointerException if <code>str</code> is * <code>null</code>. */ public int indexOf(XMLString str) { return str().indexOf(str.toString()); } /** * Returns the index within this string of the first occurrence of the * specified substring, starting at the specified index. The integer * returned is the smallest value <i>k</i> such that: * <blockquote><pre> * this.startsWith(str, <i>k</i>) && (<i>k</i> >= fromIndex) * </pre></blockquote> * is <code>true</code>. * <p> * There is no restriction on the value of <code>fromIndex</code>. If * it is negative, it has the same effect as if it were zero: this entire * string may be searched. If it is greater than the length of this * string, it has the same effect as if it were equal to the length of * this string: <code>-1</code> is returned. * * @param str the substring to search for. * @param fromIndex the index to start the search from. * @return If the string argument occurs as a substring within this * object at a starting index no smaller than * <code>fromIndex</code>, then the index of the first character * of the first such substring is returned. If it does not occur * as a substring starting at <code>fromIndex</code> or beyond, * <code>-1</code> is returned. * @exception java.lang.NullPointerException if <code>str</code> is * <code>null</code> */ public int indexOf(String str, int fromIndex) { return str().indexOf(str, fromIndex); } /** * Returns the index within this string of the rightmost occurrence * of the specified substring. The rightmost empty string "" is * considered to occur at the index value <code>this.length()</code>. * The returned index is the largest value <i>k</i> such that * <blockquote><pre> * this.startsWith(str, k) * </pre></blockquote> * is true. * * @param str the substring to search for. * @return if the string argument occurs one or more times as a substring * within this object, then the index of the first character of * the last such substring is returned. If it does not occur as * a substring, <code>-1</code> is returned. * @exception java.lang.NullPointerException if <code>str</code> is * <code>null</code>. */ public int lastIndexOf(String str) { return str().lastIndexOf(str); } /** * Returns the index within this string of the last occurrence of * the specified substring. * * @param str the substring to search for. * @param fromIndex the index to start the search from. There is no * restriction on the value of fromIndex. If it is greater than * the length of this string, it has the same effect as if it * were equal to the length of this string: this entire string * may be searched. If it is negative, it has the same effect * as if it were -1: -1 is returned. * @return If the string argument occurs one or more times as a substring * within this object at a starting index no greater than * <code>fromIndex</code>, then the index of the first character of * the last such substring is returned. If it does not occur as a * substring starting at <code>fromIndex</code> or earlier, * <code>-1</code> is returned. * @exception java.lang.NullPointerException if <code>str</code> is * <code>null</code>. */ public int lastIndexOf(String str, int fromIndex) { return str().lastIndexOf(str, fromIndex); } /** * Returns a new string that is a substring of this string. The * substring begins with the character at the specified index and * extends to the end of this string. <p> * Examples: * <blockquote><pre> * "unhappy".substring(2) returns "happy" * "Harbison".substring(3) returns "bison" * "emptiness".substring(9) returns "" (an empty string) * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if * <code>beginIndex</code> is negative or larger than the * length of this <code>String</code> object. */ public XMLString substring(int beginIndex) { return new XString(str().substring(beginIndex)); } /** * Returns a new string that is a substring of this string. The * substring begins at the specified <code>beginIndex</code> and * extends to the character at index <code>endIndex - 1</code>. * Thus the length of the substring is <code>endIndex-beginIndex</code>. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of * this <code>String</code> object, or * <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public XMLString substring(int beginIndex, int endIndex) { return new XString(str().substring(beginIndex, endIndex)); } /** * Concatenates the specified string to the end of this string. * * @param str the <code>String</code> that is concatenated to the end * of this <code>String</code>. * @return a string that represents the concatenation of this object's * characters followed by the string argument's characters. * @exception java.lang.NullPointerException if <code>str</code> is * <code>null</code>. */ public XMLString concat(String str) { // %REVIEW% Make an FSB here? return new XString(str().concat(str)); } /** * Converts all of the characters in this <code>String</code> to lower * case using the rules of the given <code>Locale</code>. * * @param locale use the case transformation rules for this locale * @return the String, converted to lowercase. * @see java.lang.Character#toLowerCase(char) * @see java.lang.String#toUpperCase(Locale) */ public XMLString toLowerCase(Locale locale) { return new XString(str().toLowerCase(locale)); } /** * Converts all of the characters in this <code>String</code> to lower * case using the rules of the default locale, which is returned * by <code>Locale.getDefault</code>. * <p> * * @return the string, converted to lowercase. * @see java.lang.Character#toLowerCase(char) * @see java.lang.String#toLowerCase(Locale) */ public XMLString toLowerCase() { return new XString(str().toLowerCase()); } /** * Converts all of the characters in this <code>String</code> to upper * case using the rules of the given locale. * @param locale use the case transformation rules for this locale * @return the String, converted to uppercase. * @see java.lang.Character#toUpperCase(char) * @see java.lang.String#toLowerCase(Locale) */ public XMLString toUpperCase(Locale locale) { return new XString(str().toUpperCase(locale)); } /** * Converts all of the characters in this <code>String</code> to upper * case using the rules of the default locale, which is returned * by <code>Locale.getDefault</code>. * * <p> * If no character in this string has a different uppercase version, * based on calling the <code>toUpperCase</code> method defined by * <code>Character</code>, then the original string is returned. * <p> * Otherwise, this method creates a new <code>String</code> object * representing a character sequence identical in length to the * character sequence represented by this <code>String</code> object and * with every character equal to the result of applying the method * <code>Character.toUpperCase</code> to the corresponding character of * this <code>String</code> object. <p> * Examples: * <blockquote><pre> * "Fahrvergn&uuml;gen".toUpperCase() returns "FAHRVERGN&Uuml;GEN" * "Visit Ljubinje!".toUpperCase() returns "VISIT LJUBINJE!" * </pre></blockquote> * * @return the string, converted to uppercase. * @see java.lang.Character#toUpperCase(char) * @see java.lang.String#toUpperCase(Locale) */ public XMLString toUpperCase() { return new XString(str().toUpperCase()); } /** * Removes white space from both ends of this string. * * @return this string, with white space removed from the front and end. */ public XMLString trim() { return new XString(str().trim()); } /** * Returns whether the specified <var>ch</var> conforms to the XML 1.0 definition * of whitespace. Refer to <A href="http://www.w3.org/TR/1998/REC-xml-19980210#NT-S"> * the definition of <CODE>S</CODE></A> for details. * @param ch Character to check as XML whitespace. * @return =true if <var>ch</var> is XML whitespace; otherwise =false. */ private static boolean isSpace(char ch) { return XMLCharacterRecognizer.isWhiteSpace(ch); // Take the easy way out for now. } /** * Conditionally trim all leading and trailing whitespace in the specified String. * All strings of white space are * replaced by a single space character (#x20), except spaces after punctuation which * receive double spaces if doublePunctuationSpaces is true. * This function may be useful to a formatter, but to get first class * results, the formatter should probably do it's own white space handling * based on the semantics of the formatting object. * * @param trimHead Trim leading whitespace? * @param trimTail Trim trailing whitespace? * @param doublePunctuationSpaces Use double spaces for punctuation? * @return The trimmed string. */ public XMLString fixWhiteSpace(boolean trimHead, boolean trimTail, boolean doublePunctuationSpaces) { // %OPT% !!!!!!! int len = this.length(); char[] buf = new char[len]; this.getChars(0, len, buf, 0); boolean edit = false; int s; for (s = 0; s < len; s++) { if (isSpace(buf[s])) { break; } } /* replace S to ' '. and ' '+ -> single ' '. */ int d = s; boolean pres = false; for (; s < len; s++) { char c = buf[s]; if (isSpace(c)) { if (!pres) { if (' ' != c) { edit = true; } buf[d++] = ' '; if (doublePunctuationSpaces && (s != 0)) { char prevChar = buf[s - 1]; if (!((prevChar == '.') || (prevChar == '!') || (prevChar == '?'))) { pres = true; } } else { pres = true; } } else { edit = true; pres = true; } } else { buf[d++] = c; pres = false; } } if (trimTail && 1 <= d && ' ' == buf[d - 1]) { edit = true; d--; } int start = 0; if (trimHead && 0 < d && ' ' == buf[0]) { edit = true; start++; } XMLStringFactory xsf = XMLStringFactoryImpl.getFactory(); return edit ? xsf.newstr(new String(buf, start, d - start)) : this; } /** * @see com.sun.org.apache.xpath.internal.XPathVisitable#callVisitors(ExpressionOwner, XPathVisitor) */ public void callVisitors(ExpressionOwner owner, XPathVisitor visitor) { visitor.visitStringLiteral(owner, this); } }
googleapis/google-cloud-java
37,764
java-distributedcloudedge/proto-google-cloud-distributedcloudedge-v1/src/main/java/com/google/cloud/edgecontainer/v1/ClusterNetworking.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/edgecontainer/v1/resources.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.edgecontainer.v1; /** * * * <pre> * Cluster-wide networking configuration. * </pre> * * Protobuf type {@code google.cloud.edgecontainer.v1.ClusterNetworking} */ public final class ClusterNetworking extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.edgecontainer.v1.ClusterNetworking) ClusterNetworkingOrBuilder { private static final long serialVersionUID = 0L; // Use ClusterNetworking.newBuilder() to construct. private ClusterNetworking(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ClusterNetworking() { clusterIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); servicesIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ClusterNetworking(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.edgecontainer.v1.ResourcesProto .internal_static_google_cloud_edgecontainer_v1_ClusterNetworking_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.edgecontainer.v1.ResourcesProto .internal_static_google_cloud_edgecontainer_v1_ClusterNetworking_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.edgecontainer.v1.ClusterNetworking.class, com.google.cloud.edgecontainer.v1.ClusterNetworking.Builder.class); } public static final int CLUSTER_IPV4_CIDR_BLOCKS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList clusterIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return A list containing the clusterIpv4CidrBlocks. */ public com.google.protobuf.ProtocolStringList getClusterIpv4CidrBlocksList() { return clusterIpv4CidrBlocks_; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The count of clusterIpv4CidrBlocks. */ public int getClusterIpv4CidrBlocksCount() { return clusterIpv4CidrBlocks_.size(); } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the element to return. * @return The clusterIpv4CidrBlocks at the given index. */ public java.lang.String getClusterIpv4CidrBlocks(int index) { return clusterIpv4CidrBlocks_.get(index); } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the value to return. * @return The bytes of the clusterIpv4CidrBlocks at the given index. */ public com.google.protobuf.ByteString getClusterIpv4CidrBlocksBytes(int index) { return clusterIpv4CidrBlocks_.getByteString(index); } public static final int SERVICES_IPV4_CIDR_BLOCKS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList servicesIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return A list containing the servicesIpv4CidrBlocks. */ public com.google.protobuf.ProtocolStringList getServicesIpv4CidrBlocksList() { return servicesIpv4CidrBlocks_; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The count of servicesIpv4CidrBlocks. */ public int getServicesIpv4CidrBlocksCount() { return servicesIpv4CidrBlocks_.size(); } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the element to return. * @return The servicesIpv4CidrBlocks at the given index. */ public java.lang.String getServicesIpv4CidrBlocks(int index) { return servicesIpv4CidrBlocks_.get(index); } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the value to return. * @return The bytes of the servicesIpv4CidrBlocks at the given index. */ public com.google.protobuf.ByteString getServicesIpv4CidrBlocksBytes(int index) { return servicesIpv4CidrBlocks_.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 { for (int i = 0; i < clusterIpv4CidrBlocks_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString( output, 1, clusterIpv4CidrBlocks_.getRaw(i)); } for (int i = 0; i < servicesIpv4CidrBlocks_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString( output, 2, servicesIpv4CidrBlocks_.getRaw(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 < clusterIpv4CidrBlocks_.size(); i++) { dataSize += computeStringSizeNoTag(clusterIpv4CidrBlocks_.getRaw(i)); } size += dataSize; size += 1 * getClusterIpv4CidrBlocksList().size(); } { int dataSize = 0; for (int i = 0; i < servicesIpv4CidrBlocks_.size(); i++) { dataSize += computeStringSizeNoTag(servicesIpv4CidrBlocks_.getRaw(i)); } size += dataSize; size += 1 * getServicesIpv4CidrBlocksList().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.edgecontainer.v1.ClusterNetworking)) { return super.equals(obj); } com.google.cloud.edgecontainer.v1.ClusterNetworking other = (com.google.cloud.edgecontainer.v1.ClusterNetworking) obj; if (!getClusterIpv4CidrBlocksList().equals(other.getClusterIpv4CidrBlocksList())) return false; if (!getServicesIpv4CidrBlocksList().equals(other.getServicesIpv4CidrBlocksList())) 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 (getClusterIpv4CidrBlocksCount() > 0) { hash = (37 * hash) + CLUSTER_IPV4_CIDR_BLOCKS_FIELD_NUMBER; hash = (53 * hash) + getClusterIpv4CidrBlocksList().hashCode(); } if (getServicesIpv4CidrBlocksCount() > 0) { hash = (37 * hash) + SERVICES_IPV4_CIDR_BLOCKS_FIELD_NUMBER; hash = (53 * hash) + getServicesIpv4CidrBlocksList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.edgecontainer.v1.ClusterNetworking 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> * Cluster-wide networking configuration. * </pre> * * Protobuf type {@code google.cloud.edgecontainer.v1.ClusterNetworking} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.edgecontainer.v1.ClusterNetworking) com.google.cloud.edgecontainer.v1.ClusterNetworkingOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.edgecontainer.v1.ResourcesProto .internal_static_google_cloud_edgecontainer_v1_ClusterNetworking_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.edgecontainer.v1.ResourcesProto .internal_static_google_cloud_edgecontainer_v1_ClusterNetworking_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.edgecontainer.v1.ClusterNetworking.class, com.google.cloud.edgecontainer.v1.ClusterNetworking.Builder.class); } // Construct using com.google.cloud.edgecontainer.v1.ClusterNetworking.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; clusterIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); servicesIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.edgecontainer.v1.ResourcesProto .internal_static_google_cloud_edgecontainer_v1_ClusterNetworking_descriptor; } @java.lang.Override public com.google.cloud.edgecontainer.v1.ClusterNetworking getDefaultInstanceForType() { return com.google.cloud.edgecontainer.v1.ClusterNetworking.getDefaultInstance(); } @java.lang.Override public com.google.cloud.edgecontainer.v1.ClusterNetworking build() { com.google.cloud.edgecontainer.v1.ClusterNetworking result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.edgecontainer.v1.ClusterNetworking buildPartial() { com.google.cloud.edgecontainer.v1.ClusterNetworking result = new com.google.cloud.edgecontainer.v1.ClusterNetworking(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.edgecontainer.v1.ClusterNetworking result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { clusterIpv4CidrBlocks_.makeImmutable(); result.clusterIpv4CidrBlocks_ = clusterIpv4CidrBlocks_; } if (((from_bitField0_ & 0x00000002) != 0)) { servicesIpv4CidrBlocks_.makeImmutable(); result.servicesIpv4CidrBlocks_ = servicesIpv4CidrBlocks_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.edgecontainer.v1.ClusterNetworking) { return mergeFrom((com.google.cloud.edgecontainer.v1.ClusterNetworking) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.edgecontainer.v1.ClusterNetworking other) { if (other == com.google.cloud.edgecontainer.v1.ClusterNetworking.getDefaultInstance()) return this; if (!other.clusterIpv4CidrBlocks_.isEmpty()) { if (clusterIpv4CidrBlocks_.isEmpty()) { clusterIpv4CidrBlocks_ = other.clusterIpv4CidrBlocks_; bitField0_ |= 0x00000001; } else { ensureClusterIpv4CidrBlocksIsMutable(); clusterIpv4CidrBlocks_.addAll(other.clusterIpv4CidrBlocks_); } onChanged(); } if (!other.servicesIpv4CidrBlocks_.isEmpty()) { if (servicesIpv4CidrBlocks_.isEmpty()) { servicesIpv4CidrBlocks_ = other.servicesIpv4CidrBlocks_; bitField0_ |= 0x00000002; } else { ensureServicesIpv4CidrBlocksIsMutable(); servicesIpv4CidrBlocks_.addAll(other.servicesIpv4CidrBlocks_); } 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: { java.lang.String s = input.readStringRequireUtf8(); ensureClusterIpv4CidrBlocksIsMutable(); clusterIpv4CidrBlocks_.add(s); break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensureServicesIpv4CidrBlocksIsMutable(); servicesIpv4CidrBlocks_.add(s); 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.protobuf.LazyStringArrayList clusterIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureClusterIpv4CidrBlocksIsMutable() { if (!clusterIpv4CidrBlocks_.isModifiable()) { clusterIpv4CidrBlocks_ = new com.google.protobuf.LazyStringArrayList(clusterIpv4CidrBlocks_); } bitField0_ |= 0x00000001; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return A list containing the clusterIpv4CidrBlocks. */ public com.google.protobuf.ProtocolStringList getClusterIpv4CidrBlocksList() { clusterIpv4CidrBlocks_.makeImmutable(); return clusterIpv4CidrBlocks_; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The count of clusterIpv4CidrBlocks. */ public int getClusterIpv4CidrBlocksCount() { return clusterIpv4CidrBlocks_.size(); } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the element to return. * @return The clusterIpv4CidrBlocks at the given index. */ public java.lang.String getClusterIpv4CidrBlocks(int index) { return clusterIpv4CidrBlocks_.get(index); } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the value to return. * @return The bytes of the clusterIpv4CidrBlocks at the given index. */ public com.google.protobuf.ByteString getClusterIpv4CidrBlocksBytes(int index) { return clusterIpv4CidrBlocks_.getByteString(index); } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index to set the value at. * @param value The clusterIpv4CidrBlocks to set. * @return This builder for chaining. */ public Builder setClusterIpv4CidrBlocks(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureClusterIpv4CidrBlocksIsMutable(); clusterIpv4CidrBlocks_.set(index, value); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The clusterIpv4CidrBlocks to add. * @return This builder for chaining. */ public Builder addClusterIpv4CidrBlocks(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureClusterIpv4CidrBlocksIsMutable(); clusterIpv4CidrBlocks_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param values The clusterIpv4CidrBlocks to add. * @return This builder for chaining. */ public Builder addAllClusterIpv4CidrBlocks(java.lang.Iterable<java.lang.String> values) { ensureClusterIpv4CidrBlocksIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, clusterIpv4CidrBlocks_); bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearClusterIpv4CidrBlocks() { clusterIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); ; onChanged(); return this; } /** * * * <pre> * Required. All pods in the cluster are assigned an RFC1918 IPv4 address from * these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code>repeated string cluster_ipv4_cidr_blocks = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The bytes of the clusterIpv4CidrBlocks to add. * @return This builder for chaining. */ public Builder addClusterIpv4CidrBlocksBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureClusterIpv4CidrBlocksIsMutable(); clusterIpv4CidrBlocks_.add(value); bitField0_ |= 0x00000001; onChanged(); return this; } private com.google.protobuf.LazyStringArrayList servicesIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureServicesIpv4CidrBlocksIsMutable() { if (!servicesIpv4CidrBlocks_.isModifiable()) { servicesIpv4CidrBlocks_ = new com.google.protobuf.LazyStringArrayList(servicesIpv4CidrBlocks_); } bitField0_ |= 0x00000002; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return A list containing the servicesIpv4CidrBlocks. */ public com.google.protobuf.ProtocolStringList getServicesIpv4CidrBlocksList() { servicesIpv4CidrBlocks_.makeImmutable(); return servicesIpv4CidrBlocks_; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The count of servicesIpv4CidrBlocks. */ public int getServicesIpv4CidrBlocksCount() { return servicesIpv4CidrBlocks_.size(); } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the element to return. * @return The servicesIpv4CidrBlocks at the given index. */ public java.lang.String getServicesIpv4CidrBlocks(int index) { return servicesIpv4CidrBlocks_.get(index); } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index of the value to return. * @return The bytes of the servicesIpv4CidrBlocks at the given index. */ public com.google.protobuf.ByteString getServicesIpv4CidrBlocksBytes(int index) { return servicesIpv4CidrBlocks_.getByteString(index); } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param index The index to set the value at. * @param value The servicesIpv4CidrBlocks to set. * @return This builder for chaining. */ public Builder setServicesIpv4CidrBlocks(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureServicesIpv4CidrBlocksIsMutable(); servicesIpv4CidrBlocks_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The servicesIpv4CidrBlocks to add. * @return This builder for chaining. */ public Builder addServicesIpv4CidrBlocks(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureServicesIpv4CidrBlocksIsMutable(); servicesIpv4CidrBlocks_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param values The servicesIpv4CidrBlocks to add. * @return This builder for chaining. */ public Builder addAllServicesIpv4CidrBlocks(java.lang.Iterable<java.lang.String> values) { ensureServicesIpv4CidrBlocksIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, servicesIpv4CidrBlocks_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearServicesIpv4CidrBlocks() { servicesIpv4CidrBlocks_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * Required. All services in the cluster are assigned an RFC1918 IPv4 address * from these blocks. Only a single block is supported. This field cannot be * changed after creation. * </pre> * * <code> * repeated string services_ipv4_cidr_blocks = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The bytes of the servicesIpv4CidrBlocks to add. * @return This builder for chaining. */ public Builder addServicesIpv4CidrBlocksBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureServicesIpv4CidrBlocksIsMutable(); servicesIpv4CidrBlocks_.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.edgecontainer.v1.ClusterNetworking) } // @@protoc_insertion_point(class_scope:google.cloud.edgecontainer.v1.ClusterNetworking) private static final com.google.cloud.edgecontainer.v1.ClusterNetworking DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.edgecontainer.v1.ClusterNetworking(); } public static com.google.cloud.edgecontainer.v1.ClusterNetworking getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ClusterNetworking> PARSER = new com.google.protobuf.AbstractParser<ClusterNetworking>() { @java.lang.Override public ClusterNetworking 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<ClusterNetworking> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ClusterNetworking> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.edgecontainer.v1.ClusterNetworking getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hadoop
37,851
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSPermissionChecker.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.hdfs.server.namenode; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Stack; import java.util.function.LongFunction; import org.apache.hadoop.util.Preconditions; import org.apache.hadoop.ipc.CallerContext; import org.apache.hadoop.util.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.fs.FSExceptionMessages; import org.apache.hadoop.fs.ParentNotDirectoryException; import org.apache.hadoop.fs.permission.AclEntryScope; import org.apache.hadoop.fs.permission.AclEntryType; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.DFSUtil; import org.apache.hadoop.hdfs.protocol.UnresolvedPathException; import org.apache.hadoop.hdfs.server.namenode.INodeAttributeProvider.AccessControlEnforcer; import org.apache.hadoop.hdfs.server.namenode.INodeAttributeProvider.AuthorizationContext; import org.apache.hadoop.hdfs.util.ReadOnlyList; import org.apache.hadoop.hdfs.util.RwLockMode; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; /** * Class that helps in checking file system permission. * The state of this class need not be synchronized as it has data structures that * are read-only. * * Some of the helper methods are guarded by {@link FSNamesystem#readLock(RwLockMode)}. */ public class FSPermissionChecker implements AccessControlEnforcer { static final Logger LOG = LoggerFactory.getLogger(UserGroupInformation.class); private static String getPath(byte[][] components, int start, int end) { return DFSUtil.byteArray2PathString(components, start, end - start + 1); } /** @return a string for throwing {@link AccessControlException} */ private String toAccessControlString(INodeAttributes inodeAttrib, String path, FsAction access) { return toAccessControlString(inodeAttrib, path, access, false); } /** @return a string for throwing {@link AccessControlException} */ private String toAccessControlString(INodeAttributes inodeAttrib, String path, FsAction access, boolean deniedFromAcl) { StringBuilder sb = new StringBuilder("Permission denied: ") .append("user=").append(getUser()).append(", ") .append("access=").append(access).append(", ") .append("inode=\"").append(path).append("\":") .append(inodeAttrib.getUserName()).append(':') .append(inodeAttrib.getGroupName()).append(':') .append(inodeAttrib.isDirectory() ? 'd' : '-') .append(inodeAttrib.getFsPermission()); if (deniedFromAcl) { sb.append("+"); } return sb.toString(); } private final String fsOwner; private final String supergroup; private final UserGroupInformation callerUgi; private final String user; private final Collection<String> groups; private final boolean isSuper; private final INodeAttributeProvider attributeProvider; private final AccessControlEnforcer accessControlEnforcer; private final boolean authorizeWithContext; private final long accessControlEnforcerReportingThresholdMs; private static ThreadLocal<String> operationType = new ThreadLocal<>(); protected FSPermissionChecker(String fsOwner, String supergroup, UserGroupInformation callerUgi, INodeAttributeProvider attributeProvider) { this(fsOwner, supergroup, callerUgi, attributeProvider, false, 0); } protected FSPermissionChecker(String fsOwner, String supergroup, UserGroupInformation callerUgi, INodeAttributeProvider attributeProvider, boolean useAuthorizationWithContextAPI, long accessControlEnforcerReportingThresholdMs) { this.fsOwner = fsOwner; this.supergroup = supergroup; this.callerUgi = callerUgi; this.groups = callerUgi.getGroupsSet(); user = callerUgi.getShortUserName(); isSuper = user.equals(fsOwner) || groups.contains(supergroup); this.attributeProvider = attributeProvider; this.accessControlEnforcer = initAccessControlEnforcer(); if (attributeProvider == null) { // If attribute provider is null, use FSPermissionChecker default // implementation to authorize, which supports authorization with context. authorizeWithContext = true; LOG.debug("Default authorization provider supports the new authorization" + " provider API"); } else { authorizeWithContext = useAuthorizationWithContextAPI; } this.accessControlEnforcerReportingThresholdMs = accessControlEnforcerReportingThresholdMs; } private String checkAccessControlEnforcerSlowness( long elapsedMs, AccessControlEnforcer ace, boolean checkSuperuser, AuthorizationContext context) { return checkAccessControlEnforcerSlowness(elapsedMs, accessControlEnforcerReportingThresholdMs, ace.getClass(), checkSuperuser, context.getPath(), context.getOperationName(), context.getCallerContext()); } /** @return the warning message if there is any. */ static String checkAccessControlEnforcerSlowness( long elapsedMs, long thresholdMs, Class<? extends AccessControlEnforcer> clazz, boolean checkSuperuser, String path, String op, Object caller) { if (!LOG.isWarnEnabled()) { return null; } if (thresholdMs <= 0) { return null; } if (elapsedMs > thresholdMs) { final String message = clazz + " ran for " + elapsedMs + "ms (threshold=" + thresholdMs + "ms) to check " + (checkSuperuser ? "superuser" : "permission") + " on " + path + " for " + op + " from caller " + caller; LOG.warn(message, new Throwable("TRACE")); return message; } return null; } public static void setOperationType(String opType) { operationType.set(opType); } public boolean isMemberOfGroup(String group) { return groups.contains(group); } public String getUser() { return user; } public boolean isSuperUser() { return isSuper; } public INodeAttributeProvider getAttributesProvider() { return attributeProvider; } @FunctionalInterface interface CheckPermission { void run() throws AccessControlException; } static String runCheckPermission(CheckPermission checker, LongFunction<String> checkElapsedMs) throws AccessControlException { final String message; final long start = Time.monotonicNow(); try { checker.run(); } finally { final long end = Time.monotonicNow(); message = checkElapsedMs.apply(end - start); } return message; } private AccessControlEnforcer initAccessControlEnforcer() { final AccessControlEnforcer e = Optional.ofNullable(attributeProvider) .map(p -> p.getExternalAccessControlEnforcer(this)) .orElse(this); if (e == this) { return this; } // For an external AccessControlEnforcer, check for slowness. return new AccessControlEnforcer() { @Override public void checkPermission( String filesystemOwner, String superGroup, UserGroupInformation ugi, INodeAttributes[] inodeAttrs, INode[] inodes, byte[][] pathByNameArr, int snapshotId, String path, int ancestorIndex, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess, boolean ignoreEmptyDir) throws AccessControlException { runCheckPermission( () -> e.checkPermission(filesystemOwner, superGroup, ugi, inodeAttrs, inodes, pathByNameArr, snapshotId, path, ancestorIndex, doCheckOwner, ancestorAccess, parentAccess, access, subAccess, ignoreEmptyDir), elapsedMs -> checkAccessControlEnforcerSlowness(elapsedMs, accessControlEnforcerReportingThresholdMs, e.getClass(), false, path, operationType.get(), CallerContext.getCurrent())); } @Override public void checkPermissionWithContext(AuthorizationContext context) throws AccessControlException { runCheckPermission( () -> e.checkPermissionWithContext(context), elapsedMs -> checkAccessControlEnforcerSlowness(elapsedMs, e, false, context)); } @Override public void checkSuperUserPermissionWithContext( AuthorizationContext context) throws AccessControlException { runCheckPermission( () -> e.checkSuperUserPermissionWithContext(context), elapsedMs -> checkAccessControlEnforcerSlowness(elapsedMs, e, true, context)); } }; } private AuthorizationContext getAuthorizationContextForSuperUser( String path) { String opType = operationType.get(); AuthorizationContext.Builder builder = new INodeAttributeProvider.AuthorizationContext.Builder(); builder.fsOwner(fsOwner). supergroup(supergroup). callerUgi(callerUgi). operationName(opType). callerContext(CallerContext.getCurrent()); // Add path to the context builder only if it is not null. if (path != null && !path.isEmpty()) { builder.path(path); } return builder.build(); } /** * This method is retained to maintain backward compatibility. * Please use the new method {@link #checkSuperuserPrivilege(String)} to make * sure that the external enforcers have the correct context to audit. * * @throws AccessControlException if the caller is not a super user. */ public void checkSuperuserPrivilege() throws AccessControlException { checkSuperuserPrivilege(null); } /** * Checks if the caller has super user privileges. * Throws {@link AccessControlException} for non super users. * * @param path The resource path for which permission is being requested. * @throws AccessControlException if the caller is not a super user. */ public void checkSuperuserPrivilege(String path) throws AccessControlException { if (LOG.isDebugEnabled()) { LOG.debug("SUPERUSER ACCESS CHECK: " + this + ", operationName=" + FSPermissionChecker.operationType.get() + ", path=" + path); } accessControlEnforcer.checkSuperUserPermissionWithContext( getAuthorizationContextForSuperUser(path)); } /** * Calls the external enforcer to notify denial of access to the user with * the given error message. Always throws an ACE with the given message. * * @param path The resource path for which permission is being requested. * @param errorMessage message for the exception. * @throws AccessControlException with the error message. */ public void denyUserAccess(String path, String errorMessage) throws AccessControlException { if (LOG.isDebugEnabled()) { LOG.debug("DENY USER ACCESS: " + this + ", operationName=" + FSPermissionChecker.operationType.get() + ", path=" + path); } accessControlEnforcer.denyUserAccess( getAuthorizationContextForSuperUser(path), errorMessage); } /** * Check whether current user have permissions to access the path. * Traverse is always checked. * * Parent path means the parent directory for the path. * Ancestor path means the last (the closest) existing ancestor directory * of the path. * Note that if the parent path exists, * then the parent path and the ancestor path are the same. * * For example, suppose the path is "/foo/bar/baz". * No matter baz is a file or a directory, * the parent path is "/foo/bar". * If bar exists, then the ancestor path is also "/foo/bar". * If bar does not exist and foo exists, * then the ancestor path is "/foo". * Further, if both foo and bar do not exist, * then the ancestor path is "/". * * @param doCheckOwner Require user to be the owner of the path? * @param ancestorAccess The access required by the ancestor of the path. * @param parentAccess The access required by the parent of the path. * @param access The access required by the path. * @param subAccess If path is a directory, * it is the access required of the path and all the sub-directories. * If path is not a directory, there is no effect. * @param ignoreEmptyDir Ignore permission checking for empty directory? * @throws AccessControlException * * Guarded by {@link FSNamesystem#readLock(RwLockMode)} * Caller of this method must hold that lock. */ void checkPermission(INodesInPath inodesInPath, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess, boolean ignoreEmptyDir) throws AccessControlException { if (LOG.isDebugEnabled()) { LOG.debug("ACCESS CHECK: " + this + ", doCheckOwner=" + doCheckOwner + ", ancestorAccess=" + ancestorAccess + ", parentAccess=" + parentAccess + ", access=" + access + ", subAccess=" + subAccess + ", ignoreEmptyDir=" + ignoreEmptyDir); } // check if (parentAccess != null) && file exists, then check sb // If resolveLink, the check is performed on the link target. final int snapshotId = inodesInPath.getPathSnapshotId(); final INode[] inodes = inodesInPath.getINodesArray(); final INodeAttributes[] inodeAttrs = new INodeAttributes[inodes.length]; final byte[][] components = inodesInPath.getPathComponents(); for (int i = 0; i < inodes.length && inodes[i] != null; i++) { inodeAttrs[i] = getINodeAttrs(components, i, inodes[i], snapshotId); } String path = inodesInPath.getPath(); int ancestorIndex = inodes.length - 2; String opType = operationType.get(); try { if (this.authorizeWithContext && opType != null) { INodeAttributeProvider.AuthorizationContext.Builder builder = new INodeAttributeProvider.AuthorizationContext.Builder(); builder.fsOwner(fsOwner). supergroup(supergroup). callerUgi(callerUgi). inodeAttrs(inodeAttrs). inodes(inodes). pathByNameArr(components). snapshotId(snapshotId). path(path). ancestorIndex(ancestorIndex). doCheckOwner(doCheckOwner). ancestorAccess(ancestorAccess). parentAccess(parentAccess). access(access). subAccess(subAccess). ignoreEmptyDir(ignoreEmptyDir). operationName(opType). callerContext(CallerContext.getCurrent()); accessControlEnforcer.checkPermissionWithContext(builder.build()); } else { accessControlEnforcer.checkPermission(fsOwner, supergroup, callerUgi, inodeAttrs, inodes, components, snapshotId, path, ancestorIndex, doCheckOwner, ancestorAccess, parentAccess, access, subAccess, ignoreEmptyDir); } } catch (AccessControlException ace) { Class<?> exceptionClass = ace.getClass(); if (exceptionClass.equals(AccessControlException.class) || exceptionClass.equals(TraverseAccessControlException.class)) { throw ace; } // Only form a new ACE for subclasses which come from external enforcers throw new AccessControlException(ace); } } /** * Check permission only for the given inode (not checking the children's * access). * * @param inode the inode to check. * @param snapshotId the snapshot id. * @param access the target access. * @throws AccessControlException */ void checkPermission(INode inode, int snapshotId, FsAction access) throws AccessControlException { byte[][] pathComponents = inode.getPathComponents(); INodeAttributes nodeAttributes = getINodeAttrs(pathComponents, pathComponents.length - 1, inode, snapshotId); try { INodeAttributes[] iNodeAttr = {nodeAttributes}; String opType = operationType.get(); if (this.authorizeWithContext && opType != null) { INodeAttributeProvider.AuthorizationContext.Builder builder = new INodeAttributeProvider.AuthorizationContext.Builder(); builder.fsOwner(fsOwner) .supergroup(supergroup) .callerUgi(callerUgi) .inodeAttrs(iNodeAttr) // single inode attr in the array .inodes(new INode[] { inode }) // single inode attr in the array .pathByNameArr(pathComponents) .snapshotId(snapshotId) .path(null) .ancestorIndex(-1) // this will skip checkTraverse() // because not checking ancestor here .doCheckOwner(false) .ancestorAccess(null) .parentAccess(null) .access(access) // the target access to be checked against // the inode .subAccess(null) // passing null sub access avoids checking // children .ignoreEmptyDir(false) .operationName(opType) .callerContext(CallerContext.getCurrent()); accessControlEnforcer.checkPermissionWithContext(builder.build()); } else { accessControlEnforcer.checkPermission( fsOwner, supergroup, callerUgi, iNodeAttr, // single inode attr in the array new INode[]{inode}, // single inode in the array pathComponents, snapshotId, null, -1, // this will skip checkTraverse() because // not checking ancestor here false, null, null, access, // the target access to be checked against the inode null, // passing null sub access avoids checking children false); } } catch (AccessControlException ace) { LOG.debug("Error while checking permission: ", ace); throw new AccessControlException( toAccessControlString(nodeAttributes, inode.getFullPathName(), access)); } } @Override public void checkPermission(String fsOwner, String supergroup, UserGroupInformation callerUgi, INodeAttributes[] inodeAttrs, INode[] inodes, byte[][] components, int snapshotId, String path, int ancestorIndex, boolean doCheckOwner, FsAction ancestorAccess, FsAction parentAccess, FsAction access, FsAction subAccess, boolean ignoreEmptyDir) throws AccessControlException { for(; ancestorIndex >= 0 && inodes[ancestorIndex] == null; ancestorIndex--); try { checkTraverse(inodeAttrs, inodes, components, ancestorIndex); } catch (UnresolvedPathException | ParentNotDirectoryException ex) { // must tunnel these exceptions out to avoid breaking interface for // external enforcer throw new TraverseAccessControlException(ex); } final INodeAttributes last = inodeAttrs[inodeAttrs.length - 1]; if (parentAccess != null && parentAccess.implies(FsAction.WRITE) && inodeAttrs.length > 1 && last != null) { checkStickyBit(inodeAttrs, components, inodeAttrs.length - 2); } if (ancestorAccess != null && inodeAttrs.length > 1) { check(inodeAttrs, components, ancestorIndex, ancestorAccess); } if (parentAccess != null && inodeAttrs.length > 1) { check(inodeAttrs, components, inodeAttrs.length - 2, parentAccess); } if (access != null) { check(inodeAttrs, components, inodeAttrs.length - 1, access); } if (subAccess != null) { INode rawLast = inodes[inodeAttrs.length - 1]; checkSubAccess(components, inodeAttrs.length - 1, rawLast, snapshotId, subAccess, ignoreEmptyDir); } if (doCheckOwner) { checkOwner(inodeAttrs, components, inodeAttrs.length - 1); } } @Override public void checkPermissionWithContext( INodeAttributeProvider.AuthorizationContext authzContext) throws AccessControlException { // The default authorization provider does not use the additional context // parameters including operationName and callerContext. this.checkPermission(authzContext.getFsOwner(), authzContext.getSupergroup(), authzContext.getCallerUgi(), authzContext.getInodeAttrs(), authzContext.getInodes(), authzContext.getPathByNameArr(), authzContext.getSnapshotId(), authzContext.getPath(), authzContext.getAncestorIndex(), authzContext.isDoCheckOwner(), authzContext.getAncestorAccess(), authzContext.getParentAccess(), authzContext.getAccess(), authzContext.getSubAccess(), authzContext.isIgnoreEmptyDir()); } private INodeAttributes getINodeAttrs(byte[][] pathByNameArr, int pathIdx, INode inode, int snapshotId) { INodeAttributes inodeAttrs = inode.getSnapshotINode(snapshotId); if (getAttributesProvider() != null) { String[] elements = new String[pathIdx + 1]; /** * {@link INode#getPathComponents(String)} returns a null component * for the root only path "/". Assign an empty string if so. */ if (pathByNameArr.length == 1 && pathByNameArr[0] == null) { elements[0] = ""; } else { for (int i = 0; i < elements.length; i++) { elements[i] = DFSUtil.bytes2String(pathByNameArr[i]); } } inodeAttrs = getAttributesProvider().getAttributes(elements, inodeAttrs); } return inodeAttrs; } /** Guarded by {@link FSNamesystem#readLock(RwLockMode)}. */ private void checkOwner(INodeAttributes[] inodes, byte[][] components, int i) throws AccessControlException { if (getUser().equals(inodes[i].getUserName())) { return; } throw new AccessControlException( "Permission denied. user=" + getUser() + " is not the owner of inode=" + getPath(components, 0, i)); } /** Guarded by {@link FSNamesystem#readLock(RwLockMode)}. * @throws AccessControlException * @throws ParentNotDirectoryException * @throws UnresolvedPathException */ private void checkTraverse(INodeAttributes[] inodeAttrs, INode[] inodes, byte[][] components, int last) throws AccessControlException, UnresolvedPathException, ParentNotDirectoryException { for (int i=0; i <= last; i++) { checkIsDirectory(inodes[i], components, i); check(inodeAttrs, components, i, FsAction.EXECUTE); } } /** Guarded by {@link FSNamesystem#readLock(RwLockMode)}. */ private void checkSubAccess(byte[][] components, int pathIdx, INode inode, int snapshotId, FsAction access, boolean ignoreEmptyDir) throws AccessControlException { if (inode == null || !inode.isDirectory()) { return; } // Each inode in the subtree has a level. The root inode has level 0. // List subINodePath tracks the inode path in the subtree during // traversal. The root inode is not stored because it is already in array // components. The list index is (level - 1). ArrayList<INodeDirectory> subINodePath = new ArrayList<>(); // The stack of levels matches the stack of directory inodes. Stack<Integer> levels = new Stack<>(); levels.push(0); // Level 0 is the root Stack<INodeDirectory> directories = new Stack<INodeDirectory>(); for(directories.push(inode.asDirectory()); !directories.isEmpty(); ) { INodeDirectory d = directories.pop(); int level = levels.pop(); ReadOnlyList<INode> cList = d.getChildrenList(snapshotId); if (!(cList.isEmpty() && ignoreEmptyDir)) { //TODO have to figure this out with inodeattribute provider INodeAttributes inodeAttr = getINodeAttrs(components, pathIdx, d, snapshotId); if (!hasPermission(inodeAttr, access)) { throw new AccessControlException( toAccessControlString(inodeAttr, d.getFullPathName(), access)); } if (level > 0) { if (level - 1 < subINodePath.size()) { subINodePath.set(level - 1, d); } else { Preconditions.checkState(level - 1 == subINodePath.size()); subINodePath.add(d); } } if (inodeAttr.getFsPermission().getStickyBit()) { for (INode child : cList) { INodeAttributes childInodeAttr = getINodeAttrs(components, pathIdx, child, snapshotId); if (isStickyBitViolated(inodeAttr, childInodeAttr)) { List<byte[]> allComponentList = new ArrayList<>(); for (int i = 0; i <= pathIdx; ++i) { allComponentList.add(components[i]); } for (int i = 0; i < level; ++i) { allComponentList.add(subINodePath.get(i).getLocalNameBytes()); } allComponentList.add(child.getLocalNameBytes()); int index = pathIdx + level; byte[][] allComponents = allComponentList.toArray(new byte[][]{}); throwStickyBitException( getPath(allComponents, 0, index + 1), child, getPath(allComponents, 0, index), inode); } } } } for(INode child : cList) { if (child.isDirectory()) { directories.push(child.asDirectory()); levels.push(level + 1); } } } } /** Guarded by {@link FSNamesystem#readLock(RwLockMode)}. */ private void check(INodeAttributes[] inodes, byte[][] components, int i, FsAction access) throws AccessControlException { INodeAttributes inode = (i >= 0) ? inodes[i] : null; if (inode != null && !hasPermission(inode, access)) { throw new AccessControlException( toAccessControlString(inode, getPath(components, 0, i), access)); } } // return whether access is permitted. note it neither requires a path or // throws so the caller can build the path only if required for an exception. // very beneficial for subaccess checks! private boolean hasPermission(INodeAttributes inode, FsAction access) { if (inode == null) { return true; } final FsPermission mode = inode.getFsPermission(); final AclFeature aclFeature = inode.getAclFeature(); if (aclFeature != null && aclFeature.getEntriesSize() > 0) { // It's possible that the inode has a default ACL but no access ACL. int firstEntry = aclFeature.getEntryAt(0); if (AclEntryStatusFormat.getScope(firstEntry) == AclEntryScope.ACCESS) { return hasAclPermission(inode, access, mode, aclFeature); } } final FsAction checkAction; if (getUser().equals(inode.getUserName())) { //user class checkAction = mode.getUserAction(); } else if (isMemberOfGroup(inode.getGroupName())) { //group class checkAction = mode.getGroupAction(); } else { //other class checkAction = mode.getOtherAction(); } return checkAction.implies(access); } /** * Checks requested access against an Access Control List. This method relies * on finding the ACL data in the relevant portions of {@link FsPermission} and * {@link AclFeature} as implemented in the logic of {@link AclStorage}. This * method also relies on receiving the ACL entries in sorted order. This is * assumed to be true, because the ACL modification methods in * {@link AclTransformation} sort the resulting entries. * * More specifically, this method depends on these invariants in an ACL: * - The list must be sorted. * - Each entry in the list must be unique by scope + type + name. * - There is exactly one each of the unnamed user/group/other entries. * - The mask entry must not have a name. * - The other entry must not have a name. * - Default entries may be present, but they are ignored during enforcement. * * @param inode INodeAttributes accessed inode * @param access FsAction requested permission * @param mode FsPermission mode from inode * @param aclFeature AclFeature of inode * @throws AccessControlException if the ACL denies permission */ private boolean hasAclPermission(INodeAttributes inode, FsAction access, FsPermission mode, AclFeature aclFeature) { boolean foundMatch = false; // Use owner entry from permission bits if user is owner. if (getUser().equals(inode.getUserName())) { if (mode.getUserAction().implies(access)) { return true; } foundMatch = true; } // Check named user and group entries if user was not denied by owner entry. if (!foundMatch) { for (int pos = 0, entry; pos < aclFeature.getEntriesSize(); pos++) { entry = aclFeature.getEntryAt(pos); if (AclEntryStatusFormat.getScope(entry) == AclEntryScope.DEFAULT) { break; } AclEntryType type = AclEntryStatusFormat.getType(entry); String name = AclEntryStatusFormat.getName(entry); if (type == AclEntryType.USER) { // Use named user entry with mask from permission bits applied if user // matches name. if (getUser().equals(name)) { FsAction masked = AclEntryStatusFormat.getPermission(entry).and( mode.getGroupAction()); if (masked.implies(access)) { return true; } foundMatch = true; break; } } else if (type == AclEntryType.GROUP) { // Use group entry (unnamed or named) with mask from permission bits // applied if user is a member and entry grants access. If user is a // member of multiple groups that have entries that grant access, then // it doesn't matter which is chosen, so exit early after first match. String group = name == null ? inode.getGroupName() : name; if (isMemberOfGroup(group)) { FsAction masked = AclEntryStatusFormat.getPermission(entry).and( mode.getGroupAction()); if (masked.implies(access)) { return true; } foundMatch = true; } } } } // Use other entry if user was not denied by an earlier match. return !foundMatch && mode.getOtherAction().implies(access); } /** Guarded by {@link FSNamesystem#readLock(RwLockMode)}. */ private void checkStickyBit(INodeAttributes[] inodes, byte[][] components, int index) throws AccessControlException { INodeAttributes parent = inodes[index]; if (!parent.getFsPermission().getStickyBit()) { return; } INodeAttributes inode = inodes[index + 1]; if (!isStickyBitViolated(parent, inode)) { return; } throwStickyBitException(getPath(components, 0, index + 1), inode, getPath(components, 0, index), parent); } /** Return true when sticky bit is violated. */ private boolean isStickyBitViolated(INodeAttributes parent, INodeAttributes inode) { // If this user is the directory owner, return if (parent.getUserName().equals(getUser())) { return false; } // if this user is the file owner, return if (inode.getUserName().equals(getUser())) { return false; } return true; } private void throwStickyBitException( String inodePath, INodeAttributes inode, String parentPath, INodeAttributes parent) throws AccessControlException { throw new AccessControlException(String.format( FSExceptionMessages.PERMISSION_DENIED_BY_STICKY_BIT + ": user=%s, path=\"%s\":%s:%s:%s%s, " + "parent=\"%s\":%s:%s:%s%s", user, inodePath, inode.getUserName(), inode.getGroupName(), inode.isDirectory() ? "d" : "-", inode.getFsPermission().toString(), parentPath, parent.getUserName(), parent.getGroupName(), parent.isDirectory() ? "d" : "-", parent.getFsPermission().toString())); } /** * Whether a cache pool can be accessed by the current context * * @param pool CachePool being accessed * @param access type of action being performed on the cache pool * @throws AccessControlException if pool cannot be accessed */ public void checkPermission(CachePool pool, FsAction access) throws AccessControlException { FsPermission mode = pool.getMode(); if (isSuperUser()) { return; } if (getUser().equals(pool.getOwnerName()) && mode.getUserAction().implies(access)) { return; } if (isMemberOfGroup(pool.getGroupName()) && mode.getGroupAction().implies(access)) { return; } if (!getUser().equals(pool.getOwnerName()) && !isMemberOfGroup(pool.getGroupName()) && mode.getOtherAction().implies(access)) { return; } throw new AccessControlException("Permission denied while accessing pool " + pool.getPoolName() + ": user " + getUser() + " does not have " + access.toString() + " permissions."); } /** * Verifies that all existing ancestors are directories. If a permission * checker is provided then the user must have exec access. Ancestor * symlinks will throw an unresolved exception, and resolveLink determines * if the last inode will throw an unresolved exception. This method * should always be called after a path is resolved into an IIP. * @param pc for permission checker, null for no checking * @param iip path to verify * @param resolveLink whether last inode may be a symlink * @throws AccessControlException * @throws UnresolvedPathException * @throws ParentNotDirectoryException */ static void checkTraverse(FSPermissionChecker pc, INodesInPath iip, boolean resolveLink) throws AccessControlException, UnresolvedPathException, ParentNotDirectoryException { try { if (pc == null || pc.isSuperUser()) { if (pc != null) { // call the external enforcer for audit pc.checkSuperuserPrivilege(iip.getPath()); } checkSimpleTraverse(iip); } else { pc.checkPermission(iip, false, null, null, null, null, false); } } catch (TraverseAccessControlException tace) { // unwrap the non-ACE (unresolved, parent not dir) exception // tunneled out of checker. tace.throwCause(); } // maybe check that the last inode is a symlink if (resolveLink) { int last = iip.length() - 1; checkNotSymlink(iip.getINode(last), iip.getPathComponents(), last); } } // rudimentary permission-less directory check private static void checkSimpleTraverse(INodesInPath iip) throws UnresolvedPathException, ParentNotDirectoryException { byte[][] components = iip.getPathComponents(); for (int i=0; i < iip.length() - 1; i++) { INode inode = iip.getINode(i); if (inode == null) { break; } checkIsDirectory(inode, components, i); } } private static void checkIsDirectory(INode inode, byte[][] components, int i) throws UnresolvedPathException, ParentNotDirectoryException { if (inode != null && !inode.isDirectory()) { checkNotSymlink(inode, components, i); throw new ParentNotDirectoryException( getPath(components, 0, i) + " (is not a directory)"); } } private static void checkNotSymlink(INode inode, byte[][] components, int i) throws UnresolvedPathException { if (inode != null && inode.isSymlink()) { final int last = components.length - 1; final String path = getPath(components, 0, last); final String preceding = getPath(components, 0, i - 1); final String remainder = getPath(components, i + 1, last); final String target = inode.asSymlink().getSymlinkString(); if (LOG.isDebugEnabled()) { final String link = inode.getLocalName(); LOG.debug("UnresolvedPathException " + " path: " + path + " preceding: " + preceding + " count: " + i + " link: " + link + " target: " + target + " remainder: " + remainder); } throw new UnresolvedPathException(path, preceding, remainder, target); } } //used to tunnel non-ACE exceptions encountered during path traversal. //ops that create inodes are expected to throw ParentNotDirectoryExceptions. //the signature of other methods requires the PNDE to be thrown as an ACE. @SuppressWarnings("serial") static class TraverseAccessControlException extends AccessControlException { TraverseAccessControlException(IOException ioe) { super(ioe); } public void throwCause() throws UnresolvedPathException, ParentNotDirectoryException, AccessControlException { Throwable ioe = getCause(); if (ioe instanceof UnresolvedPathException) { throw (UnresolvedPathException)ioe; } if (ioe instanceof ParentNotDirectoryException) { throw (ParentNotDirectoryException)ioe; } throw this; } } }
apache/ofbiz
37,820
applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.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.product.category.ftl; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.StringUtil; import org.apache.ofbiz.base.util.StringUtil.StringWrapper; import org.apache.ofbiz.base.util.UtilMisc; import org.apache.ofbiz.base.util.UtilValidate; import org.apache.ofbiz.common.UrlServletHelper; import org.apache.ofbiz.entity.Delegator; 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.EntityExpr; import org.apache.ofbiz.entity.condition.EntityOperator; import org.apache.ofbiz.product.category.CatalogUrlServlet; import org.apache.ofbiz.product.category.CategoryContentWrapper; import org.apache.ofbiz.product.category.CategoryWorker; import org.apache.ofbiz.product.category.SeoConfigUtil; import org.apache.ofbiz.product.category.SeoUrlUtil; import org.apache.ofbiz.product.product.ProductContentWrapper; import freemarker.core.Environment; import freemarker.ext.beans.BeanModel; import freemarker.ext.beans.StringModel; import freemarker.template.SimpleScalar; import freemarker.template.TemplateModelException; import freemarker.template.TemplateTransformModel; public class CatalogUrlSeoTransform implements TemplateTransformModel { public final static String module = CatalogUrlSeoTransform.class.getName(); private static Map<String, String> categoryNameIdMap = null; private static Map<String, String> categoryIdNameMap = null; private static boolean categoryMapInitialed = false; private static final String asciiRegexp = "^[0-9-_a-zA-Z]*$"; private static Pattern asciiPattern = null; public static final String URL_HYPHEN = "-"; static { if (!SeoConfigUtil.isInitialed()) { SeoConfigUtil.init(); } try { Perl5Compiler perlCompiler = new Perl5Compiler(); asciiPattern = perlCompiler.compile(asciiRegexp, Perl5Compiler.READ_ONLY_MASK); } catch (MalformedPatternException e1) { Debug.logWarning(e1, module); } } public String getStringArg(Map args, String key) { Object o = args.get(key); if (o instanceof SimpleScalar) { return ((SimpleScalar) o).getAsString(); } else if (o instanceof StringModel) { return ((StringModel) o).getAsString(); } return null; } @Override public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException { final StringBuilder buf = new StringBuilder(); return new Writer(out) { @Override public void write(char[] cbuf, int off, int len) throws IOException { buf.append(cbuf, off, len); } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { try { Environment env = Environment.getCurrentEnvironment(); BeanModel req = (BeanModel) env.getVariable("request"); if (req != null) { String productId = getStringArg(args, "productId"); String currentCategoryId = getStringArg(args, "currentCategoryId"); String previousCategoryId = getStringArg(args, "previousCategoryId"); HttpServletRequest request = (HttpServletRequest) req.getWrappedObject(); if (!isCategoryMapInitialed()) { initCategoryMap(request); } String catalogUrl = ""; if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) { if (UtilValidate.isEmpty(productId)) { catalogUrl = makeCategoryUrl(request, currentCategoryId, previousCategoryId, null, null, null, null); } else { catalogUrl = makeProductUrl(request, productId, currentCategoryId, previousCategoryId); } } else { catalogUrl = CatalogUrlServlet.makeCatalogUrl(request, productId, currentCategoryId, previousCategoryId); } out.write(catalogUrl); } } catch (TemplateModelException e) { throw new IOException(e.getMessage()); } } }; } /** * Check whether the category map is initialed. * * @return a boolean value to indicate whether the category map has been initialized. */ public static boolean isCategoryMapInitialed() { return categoryMapInitialed; } /** * Get the category name/id map. * * @return the category name/id map */ public static Map<String, String> getCategoryNameIdMap() { return categoryNameIdMap; } /** * Get the category id/name map. * * @return the category id/name map */ public static Map<String, String> getCategoryIdNameMap() { return categoryIdNameMap; } /** * Initial category-name/category-id map. * Note: as a key, the category-name should be: * 1. ascii * 2. lower cased and use hyphen between the words. * If not, the category id will be used. * */ public static synchronized void initCategoryMap(HttpServletRequest request) { Delegator delegator = (Delegator) request.getAttribute("delegator"); initCategoryMap(request, delegator); } public static synchronized void initCategoryMap(HttpServletRequest request, Delegator delegator) { if (SeoConfigUtil.checkCategoryUrl()) { categoryNameIdMap = new Hashtable<String, String>(); categoryIdNameMap = new Hashtable<String, String>(); Perl5Matcher matcher = new Perl5Matcher(); try { Collection<GenericValue> allCategories = delegator.findList("ProductCategory", null, UtilMisc.toSet("productCategoryId", "categoryName"), null, null, false); for (GenericValue category : allCategories) { String categoryName = category.getString("categoryName"); String categoryNameId = null; String categoryIdName = null; String categoryId = category.getString("productCategoryId"); if (UtilValidate.isNotEmpty(categoryName)) { categoryName = SeoUrlUtil.replaceSpecialCharsUrl(categoryName.trim()); if (matcher.matches(categoryName, asciiPattern)) { categoryIdName = categoryName.replaceAll(" ", URL_HYPHEN); categoryNameId = categoryIdName + URL_HYPHEN + categoryId.trim().replaceAll(" ", URL_HYPHEN); } else { categoryIdName = categoryId.trim().replaceAll(" ", URL_HYPHEN); categoryNameId = categoryIdName; } } else { GenericValue productCategory = delegator.findOne("ProductCategory", UtilMisc.toMap("productCategoryId", categoryId), true); CategoryContentWrapper wrapper = new CategoryContentWrapper(productCategory, request); StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url"); if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) { categoryIdName = SeoUrlUtil.replaceSpecialCharsUrl(alternativeUrl.toString()); categoryNameId = categoryIdName + URL_HYPHEN + categoryId.trim().replaceAll(" ", URL_HYPHEN); } else { categoryNameId = categoryId.trim().replaceAll(" ", URL_HYPHEN); categoryIdName = categoryNameId; } } if (categoryNameIdMap.containsKey(categoryNameId)) { categoryNameId = categoryId.trim().replaceAll(" ", URL_HYPHEN); categoryIdName = categoryNameId; } if (!matcher.matches(categoryNameId, asciiPattern) || categoryNameIdMap.containsKey(categoryNameId)) { continue; } categoryNameIdMap.put(categoryNameId, categoryId); categoryIdNameMap.put(categoryId, categoryIdName); } } catch (GenericEntityException e) { Debug.logError(e, module); } } categoryMapInitialed = true; } /** * Make product url according to the configurations. * * @return String a catalog url */ public static String makeProductUrl(HttpServletRequest request, String productId, String currentCategoryId, String previousCategoryId) { Delegator delegator = (Delegator) request.getAttribute("delegator"); if (!isCategoryMapInitialed()) { initCategoryMap(request); } String contextPath = request.getContextPath(); StringBuilder urlBuilder = new StringBuilder(); GenericValue product = null; urlBuilder.append((request.getSession().getServletContext()).getContextPath()); if (urlBuilder.length() == 0 || urlBuilder.charAt(urlBuilder.length() - 1) != '/') { urlBuilder.append("/"); } if (UtilValidate.isNotEmpty(productId)) { try { product = delegator.findOne("Product", UtilMisc.toMap("productId", productId), true); } catch (GenericEntityException e) { Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(), module); } } if (product != null) { urlBuilder.append(CatalogUrlServlet.PRODUCT_REQUEST + "/"); } if (UtilValidate.isNotEmpty(currentCategoryId)) { List<String> trail = CategoryWorker.getTrail(request); trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId); if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { for (String trailCategoryId: trail) { if ("TOP".equals(trailCategoryId)) continue; urlBuilder.append("/"); urlBuilder.append(trailCategoryId); } } else { if (trail.size() > 1) { String lastCategoryId = trail.get(trail.size() - 1); if (!"TOP".equals(lastCategoryId)) { if (SeoConfigUtil.isCategoryNameEnabled()) { String categoryName = CatalogUrlSeoTransform.getCategoryIdNameMap().get(lastCategoryId); if (UtilValidate.isNotEmpty(categoryName)) { urlBuilder.append(categoryName); if (product != null) { urlBuilder.append(URL_HYPHEN); } } } } } } } if (UtilValidate.isNotEmpty(productId)) { if (product != null) { String productName = product.getString("productName"); productName = SeoUrlUtil.replaceSpecialCharsUrl(productName); if (UtilValidate.isNotEmpty(productName)) { urlBuilder.append(productName + URL_HYPHEN); } else { ProductContentWrapper wrapper = new ProductContentWrapper(product, request); StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url"); if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) { productName = SeoUrlUtil.replaceSpecialCharsUrl(alternativeUrl.toString()); if (UtilValidate.isNotEmpty(productName)) { urlBuilder.append(productName + URL_HYPHEN); } } } } try { urlBuilder.append(productId); } catch (Exception e) { urlBuilder.append(productId); } } if (!urlBuilder.toString().endsWith("/") && UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { urlBuilder.append(SeoConfigUtil.getCategoryUrlSuffix()); } return urlBuilder.toString(); } /** * Make category url according to the configurations. * * @return String a category url */ public static String makeCategoryUrl(HttpServletRequest request, String currentCategoryId, String previousCategoryId, String viewSize, String viewIndex, String viewSort, String searchString) { if (!isCategoryMapInitialed()) { initCategoryMap(request); } StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append((request.getSession().getServletContext()).getContextPath()); if (urlBuilder.length() == 0 || urlBuilder.charAt(urlBuilder.length() - 1) != '/') { urlBuilder.append("/"); } urlBuilder.append(CatalogUrlServlet.CATEGORY_REQUEST + "/"); if (UtilValidate.isNotEmpty(currentCategoryId)) { List<String> trail = CategoryWorker.getTrail(request); trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId); if (trail.size() > 1) { String lastCategoryId = trail.get(trail.size() - 1); if (!"TOP".equals(lastCategoryId)) { String categoryName = CatalogUrlSeoTransform.getCategoryIdNameMap().get(lastCategoryId); if (UtilValidate.isNotEmpty(categoryName)) { urlBuilder.append(categoryName); urlBuilder.append(URL_HYPHEN); urlBuilder.append(lastCategoryId.trim().replaceAll(" ", URL_HYPHEN)); } else { urlBuilder.append(lastCategoryId.trim().replaceAll(" ", URL_HYPHEN)); } } } } if (!urlBuilder.toString().endsWith("/") && UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { urlBuilder.append(SeoConfigUtil.getCategoryUrlSuffix()); } // append view index if (UtilValidate.isNotEmpty(viewIndex)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("viewIndex=" + viewIndex + "&"); } // append view size if (UtilValidate.isNotEmpty(viewSize)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("viewSize=" + viewSize + "&"); } // append view sort if (UtilValidate.isNotEmpty(viewSort)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("viewSort=" + viewSort + "&"); } // append search string if (UtilValidate.isNotEmpty(searchString)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("searchString=" + searchString + "&"); } if (urlBuilder.toString().endsWith("&")) { return urlBuilder.toString().substring(0, urlBuilder.toString().length()-1); } return urlBuilder.toString(); } /** * Make product url according to the configurations. * * @return String a catalog url */ public static String makeProductUrl(String contextPath, List<String> trail, String productId, String productName, String currentCategoryId, String previousCategoryId) { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(contextPath); if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') { urlBuilder.append("/"); } if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { urlBuilder.append(CatalogUrlServlet.CATALOG_URL_MOUNT_POINT); } else { urlBuilder.append(CatalogUrlServlet.PRODUCT_REQUEST + "/"); } if (UtilValidate.isNotEmpty(currentCategoryId)) { trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId); if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { for (String trailCategoryId: trail) { if ("TOP".equals(trailCategoryId)) continue; urlBuilder.append("/"); urlBuilder.append(trailCategoryId); } } else { if (trail.size() > 1) { String lastCategoryId = trail.get(trail.size() - 1); if (!"TOP".equals(lastCategoryId)) { if (SeoConfigUtil.isCategoryNameEnabled()) { String categoryName = CatalogUrlSeoTransform.getCategoryIdNameMap().get(lastCategoryId); if (UtilValidate.isNotEmpty(categoryName)) { urlBuilder.append(categoryName + URL_HYPHEN); } } } } } } if (UtilValidate.isNotEmpty(productId)) { if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { urlBuilder.append("/p_"); } else { productName = SeoUrlUtil.replaceSpecialCharsUrl(productName); if (UtilValidate.isNotEmpty(productName)) { urlBuilder.append(productName + URL_HYPHEN); } } urlBuilder.append(productId); } if (!urlBuilder.toString().endsWith("/") && UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { urlBuilder.append(SeoConfigUtil.getCategoryUrlSuffix()); } return urlBuilder.toString(); } /** * Get a string lower cased and hyphen connected. * * @param name a String to be transformed * @return String nice name */ protected static String getNiceName(String name) { Perl5Matcher matcher = new Perl5Matcher(); String niceName = null; if (UtilValidate.isNotEmpty(name)) { name = name.trim().replaceAll(" ", URL_HYPHEN); if (UtilValidate.isNotEmpty(name) && matcher.matches(name, asciiPattern)) { niceName = name; } } return niceName; } public static boolean forwardProductUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator) throws ServletException, IOException { return forwardProductUri(request, response, delegator, null); } public static boolean forwardProductUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException { return forwardUri(request, response, delegator, controlServlet); } /** * Forward a uri according to forward pattern regular expressions. * @param request * @param response * @param delegator * @param controlServlet * @return boolean to indicate whether the uri is forwarded. * @throws ServletException * @throws IOException */ public static boolean forwardUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException { String pathInfo = request.getRequestURI(); String contextPath = request.getContextPath(); if (!isCategoryMapInitialed()) { initCategoryMap(request, delegator); } if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { return false; } List<String> pathElements = StringUtil.split(pathInfo, "/"); if (UtilValidate.isEmpty(pathElements)) { return false; } // remove context path pathInfo = SeoUrlUtil.removeContextPath(pathInfo, contextPath); // remove servlet path pathInfo = SeoUrlUtil.removeContextPath(pathInfo, request.getServletPath()); if (pathInfo.startsWith("/" + CatalogUrlServlet.CATEGORY_REQUEST + "/")) { return forwardCategoryUri(request, response, delegator, controlServlet); } String lastPathElement = pathElements.get(pathElements.size() - 1); String categoryId = null; String productId = null; if (UtilValidate.isNotEmpty(lastPathElement)) { if (UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { if (lastPathElement.endsWith(SeoConfigUtil.getCategoryUrlSuffix())) { lastPathElement = lastPathElement.substring(0, lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length()); } else { return false; } } if (SeoConfigUtil.isCategoryNameEnabled() || pathInfo.startsWith("/" + CatalogUrlServlet.CATEGORY_REQUEST + "/")) { for (String categoryName : categoryNameIdMap.keySet()) { if (lastPathElement.startsWith(categoryName)) { categoryId = categoryNameIdMap.get(categoryName); if (!lastPathElement.equals(categoryName)) { lastPathElement = lastPathElement.substring(categoryName.length() + URL_HYPHEN.length()); } break; } } if (UtilValidate.isEmpty(categoryId)) { categoryId = lastPathElement; } } if (UtilValidate.isNotEmpty(lastPathElement)) { List<String> urlElements = StringUtil.split(lastPathElement, URL_HYPHEN); if (UtilValidate.isEmpty(urlElements)) { try { if (delegator.findOne("Product", UtilMisc.toMap("productId", lastPathElement), true) != null) { productId = lastPathElement; } } catch (GenericEntityException e) { Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), module); } } else { int i = urlElements.size() - 1; String tempProductId = urlElements.get(i); while (i >= 0) { try { List<EntityExpr> exprs = new LinkedList<EntityExpr>(); exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, lastPathElement)); exprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, tempProductId)); List<GenericValue> products = delegator.findList("Product", EntityCondition.makeCondition(exprs, EntityOperator.OR), UtilMisc.toSet("productId", "productName"), null, null, true); if (products != null && products.size() > 0) { if (products.size() == 1) { productId = products.get(0).getString("productId"); break; } else { productId = tempProductId; break; } } else if (i > 0) { tempProductId = urlElements.get(i - 1) + URL_HYPHEN + tempProductId; } } catch (GenericEntityException e) { Debug.logError(e, "Error looking up product info for ProductUrl with path info [" + pathInfo + "]: " + e.toString(), module); } i--; } } } } if (UtilValidate.isNotEmpty(productId) || UtilValidate.isNotEmpty(categoryId)) { if (categoryId != null) { request.setAttribute("productCategoryId", categoryId); } if (productId != null) { request.setAttribute("product_id", productId); request.setAttribute("productId", productId); } StringBuilder urlBuilder = new StringBuilder(); if (UtilValidate.isNotEmpty(controlServlet)) { urlBuilder.append("/" + controlServlet); } urlBuilder.append("/" + (productId != null ? CatalogUrlServlet.PRODUCT_REQUEST : CatalogUrlServlet.CATEGORY_REQUEST)); UrlServletHelper.setViewQueryParameters(request, urlBuilder); Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); RequestDispatcher rd = request.getRequestDispatcher(urlBuilder.toString()); rd.forward(request, response); return true; } return false; } /** * Forward a category uri according to forward pattern regular expressions. * @param request * @param response * @param delegator * @param controlServlet * @return * @throws ServletException * @throws IOException */ public static boolean forwardCategoryUri(HttpServletRequest request, HttpServletResponse response, Delegator delegator, String controlServlet) throws ServletException, IOException { String pathInfo = request.getRequestURI(); String contextPath = request.getContextPath(); if (!isCategoryMapInitialed()) { initCategoryMap(request); } if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { return false; } List<String> pathElements = StringUtil.split(pathInfo, "/"); if (UtilValidate.isEmpty(pathElements)) { return false; } String lastPathElement = pathElements.get(pathElements.size() - 1); String categoryId = null; if (UtilValidate.isNotEmpty(lastPathElement)) { if (UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { if (lastPathElement.endsWith(SeoConfigUtil.getCategoryUrlSuffix())) { lastPathElement = lastPathElement.substring(0, lastPathElement.length() - SeoConfigUtil.getCategoryUrlSuffix().length()); } else { return false; } } for (String categoryName : categoryNameIdMap.keySet()) { if (lastPathElement.startsWith(categoryName)) { categoryId = categoryNameIdMap.get(categoryName); break; } } if (UtilValidate.isEmpty(categoryId)) { categoryId = lastPathElement.trim(); } } if (UtilValidate.isNotEmpty(categoryId)) { request.setAttribute("productCategoryId", categoryId); StringBuilder urlBuilder = new StringBuilder(); if (UtilValidate.isNotEmpty(controlServlet)) { urlBuilder.append("/" + controlServlet); } urlBuilder.append("/" + CatalogUrlServlet.CATEGORY_REQUEST); UrlServletHelper.setViewQueryParameters(request, urlBuilder); Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module); RequestDispatcher rd = request.getRequestDispatcher(urlBuilder.toString()); rd.forward(request, response); return true; } return false; } /** * This is used when building product url in services. * * @param delegator * @param wrapper * @param prefix * @param contextPath * @param currentCategoryId * @param previousCategoryId * @param productId * @return */ public static String makeProductUrl(Delegator delegator, ProductContentWrapper wrapper, String prefix, String contextPath, String currentCategoryId, String previousCategoryId, String productId) { StringBuilder urlBuilder = new StringBuilder(); GenericValue product = null; urlBuilder.append(prefix); if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') { urlBuilder.append("/"); } if (UtilValidate.isNotEmpty(productId)) { try { product = delegator.findOne("Product", UtilMisc.toMap("productId", productId), true); } catch (GenericEntityException e) { Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(), module); } } if (product != null) { urlBuilder.append(CatalogUrlServlet.PRODUCT_REQUEST + "/"); } if (UtilValidate.isNotEmpty(currentCategoryId)) { List<String> trail = null; trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId); if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) { for (String trailCategoryId: trail) { if ("TOP".equals(trailCategoryId)) continue; urlBuilder.append("/"); urlBuilder.append(trailCategoryId); } } else { if (trail != null && trail.size() > 1) { String lastCategoryId = trail.get(trail.size() - 1); if (!"TOP".equals(lastCategoryId)) { if (SeoConfigUtil.isCategoryNameEnabled()) { String categoryName = CatalogUrlSeoTransform.getCategoryIdNameMap().get(lastCategoryId); if (UtilValidate.isNotEmpty(categoryName)) { urlBuilder.append(categoryName); if (product != null) { urlBuilder.append(URL_HYPHEN); } } } } } } } if (UtilValidate.isNotEmpty(productId)) { if (product != null) { String productName = product.getString("productName"); productName = SeoUrlUtil.replaceSpecialCharsUrl(productName); if (UtilValidate.isNotEmpty(productName)) { urlBuilder.append(productName + URL_HYPHEN); } else { StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url"); if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) { productName = SeoUrlUtil.replaceSpecialCharsUrl(alternativeUrl.toString()); if (UtilValidate.isNotEmpty(productName)) { urlBuilder.append(productName + URL_HYPHEN); } } } } try { urlBuilder.append(productId); } catch (Exception e) { urlBuilder.append(productId); } } if (!urlBuilder.toString().endsWith("/") && UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { urlBuilder.append(SeoConfigUtil.getCategoryUrlSuffix()); } return urlBuilder.toString(); } /** * This is used when building category url in services. * * @param delegator * @param wrapper * @param prefix * @param currentCategoryId * @param previousCategoryId * @param productId * @param viewSize * @param viewIndex * @param viewSort * @param searchString * @return */ public static String makeCategoryUrl(Delegator delegator, CategoryContentWrapper wrapper, String prefix, String currentCategoryId, String previousCategoryId, String productId, String viewSize, String viewIndex, String viewSort, String searchString) { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(prefix); if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') { urlBuilder.append("/"); } urlBuilder.append(CatalogUrlServlet.CATEGORY_REQUEST + "/"); if (UtilValidate.isNotEmpty(currentCategoryId)) { List<String> trail = null; trail = CategoryWorker.adjustTrail(trail, currentCategoryId, previousCategoryId); if (trail != null && trail.size() > 1) { String lastCategoryId = trail.get(trail.size() - 1); if (!"TOP".equals(lastCategoryId)) { String categoryName = CatalogUrlSeoTransform.getCategoryIdNameMap().get(lastCategoryId); if (UtilValidate.isNotEmpty(categoryName)) { urlBuilder.append(categoryName); urlBuilder.append(URL_HYPHEN); urlBuilder.append(lastCategoryId.trim().replaceAll(" ", URL_HYPHEN)); } else { urlBuilder.append(lastCategoryId.trim().replaceAll(" ", URL_HYPHEN)); } } } } if (!urlBuilder.toString().endsWith("/") && UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) { urlBuilder.append(SeoConfigUtil.getCategoryUrlSuffix()); } // append view index if (UtilValidate.isNotEmpty(viewIndex)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("viewIndex=" + viewIndex + "&"); } // append view size if (UtilValidate.isNotEmpty(viewSize)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("viewSize=" + viewSize + "&"); } // append view sort if (UtilValidate.isNotEmpty(viewSort)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("viewSort=" + viewSort + "&"); } // append search string if (UtilValidate.isNotEmpty(searchString)) { if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) { urlBuilder.append("?"); } urlBuilder.append("searchString=" + searchString + "&"); } if (urlBuilder.toString().endsWith("&")) { return urlBuilder.toString().substring(0, urlBuilder.toString().length()-1); } return urlBuilder.toString(); } }
googleapis/google-cloud-java
37,565
java-netapp/proto-google-cloud-netapp-v1/src/main/java/com/google/cloud/netapp/v1/ListVolumesRequest.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/netapp/v1/volume.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.netapp.v1; /** * * * <pre> * Message for requesting list of Volumes * </pre> * * Protobuf type {@code google.cloud.netapp.v1.ListVolumesRequest} */ public final class ListVolumesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.netapp.v1.ListVolumesRequest) ListVolumesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListVolumesRequest.newBuilder() to construct. private ListVolumesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListVolumesRequest() { parent_ = ""; pageToken_ = ""; filter_ = ""; orderBy_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListVolumesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_ListVolumesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_ListVolumesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.ListVolumesRequest.class, com.google.cloud.netapp.v1.ListVolumesRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, the server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } public static final int PAGE_TOKEN_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ @java.lang.Override public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ @java.lang.Override public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int FILTER_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object filter_ = ""; /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ @java.lang.Override public java.lang.String getFilter() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } } /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ @java.lang.Override public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ORDER_BY_FIELD_NUMBER = 5; @SuppressWarnings("serial") private volatile java.lang.Object orderBy_ = ""; /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @return The orderBy. */ @java.lang.Override public java.lang.String getOrderBy() { java.lang.Object ref = orderBy_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); orderBy_ = s; return s; } } /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @return The bytes for orderBy. */ @java.lang.Override public com.google.protobuf.ByteString getOrderByBytes() { java.lang.Object ref = orderBy_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); orderBy_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (pageSize_ != 0) { output.writeInt32(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (pageSize_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.netapp.v1.ListVolumesRequest)) { return super.equals(obj); } com.google.cloud.netapp.v1.ListVolumesRequest other = (com.google.cloud.netapp.v1.ListVolumesRequest) obj; if (!getParent().equals(other.getParent())) return false; if (getPageSize() != other.getPageSize()) return false; if (!getPageToken().equals(other.getPageToken())) return false; if (!getFilter().equals(other.getFilter())) return false; if (!getOrderBy().equals(other.getOrderBy())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER; hash = (53 * hash) + getPageSize(); hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getPageToken().hashCode(); hash = (37 * hash) + FILTER_FIELD_NUMBER; hash = (53 * hash) + getFilter().hashCode(); hash = (37 * hash) + ORDER_BY_FIELD_NUMBER; hash = (53 * hash) + getOrderBy().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.netapp.v1.ListVolumesRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.ListVolumesRequest 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.netapp.v1.ListVolumesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.ListVolumesRequest 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.netapp.v1.ListVolumesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.ListVolumesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.netapp.v1.ListVolumesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.ListVolumesRequest 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.netapp.v1.ListVolumesRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.ListVolumesRequest 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.netapp.v1.ListVolumesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.ListVolumesRequest 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.netapp.v1.ListVolumesRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Message for requesting list of Volumes * </pre> * * Protobuf type {@code google.cloud.netapp.v1.ListVolumesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.netapp.v1.ListVolumesRequest) com.google.cloud.netapp.v1.ListVolumesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_ListVolumesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_ListVolumesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.ListVolumesRequest.class, com.google.cloud.netapp.v1.ListVolumesRequest.Builder.class); } // Construct using com.google.cloud.netapp.v1.ListVolumesRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; pageSize_ = 0; pageToken_ = ""; filter_ = ""; orderBy_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.netapp.v1.VolumeProto .internal_static_google_cloud_netapp_v1_ListVolumesRequest_descriptor; } @java.lang.Override public com.google.cloud.netapp.v1.ListVolumesRequest getDefaultInstanceForType() { return com.google.cloud.netapp.v1.ListVolumesRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.netapp.v1.ListVolumesRequest build() { com.google.cloud.netapp.v1.ListVolumesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.netapp.v1.ListVolumesRequest buildPartial() { com.google.cloud.netapp.v1.ListVolumesRequest result = new com.google.cloud.netapp.v1.ListVolumesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.netapp.v1.ListVolumesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.pageSize_ = pageSize_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.pageToken_ = pageToken_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.filter_ = filter_; } if (((from_bitField0_ & 0x00000010) != 0)) { result.orderBy_ = orderBy_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.netapp.v1.ListVolumesRequest) { return mergeFrom((com.google.cloud.netapp.v1.ListVolumesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.netapp.v1.ListVolumesRequest other) { if (other == com.google.cloud.netapp.v1.ListVolumesRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.getPageSize() != 0) { setPageSize(other.getPageSize()); } if (!other.getPageToken().isEmpty()) { pageToken_ = other.pageToken_; bitField0_ |= 0x00000004; onChanged(); } if (!other.getFilter().isEmpty()) { filter_ = other.filter_; bitField0_ |= 0x00000008; onChanged(); } if (!other.getOrderBy().isEmpty()) { orderBy_ = other.orderBy_; bitField0_ |= 0x00000010; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 16: { pageSize_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 26: { pageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 34: { filter_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000008; break; } // case 34 case 42: { orderBy_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000010; break; } // case 42 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Parent value for ListVolumesRequest * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, the server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ @java.lang.Override public int getPageSize() { return pageSize_; } /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, the server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @param value The pageSize to set. * @return This builder for chaining. */ public Builder setPageSize(int value) { pageSize_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Requested page size. Server may return fewer items than requested. * If unspecified, the server will pick an appropriate default. * </pre> * * <code>int32 page_size = 2;</code> * * @return This builder for chaining. */ public Builder clearPageSize() { bitField0_ = (bitField0_ & ~0x00000002); pageSize_ = 0; onChanged(); return this; } private java.lang.Object pageToken_ = ""; /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ public java.lang.String getPageToken() { java.lang.Object ref = pageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ public com.google.protobuf.ByteString getPageTokenBytes() { java.lang.Object ref = pageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); pageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @param value The pageToken to set. * @return This builder for chaining. */ public Builder setPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @return This builder for chaining. */ public Builder clearPageToken() { pageToken_ = getDefaultInstance().getPageToken(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * A token identifying a page of results the server should return. * </pre> * * <code>string page_token = 3;</code> * * @param value The bytes for pageToken to set. * @return This builder for chaining. */ public Builder setPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pageToken_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private java.lang.Object filter_ = ""; /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @return The filter. */ public java.lang.String getFilter() { java.lang.Object ref = filter_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); filter_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @return The bytes for filter. */ public com.google.protobuf.ByteString getFilterBytes() { java.lang.Object ref = filter_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); filter_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @param value The filter to set. * @return This builder for chaining. */ public Builder setFilter(java.lang.String value) { if (value == null) { throw new NullPointerException(); } filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @return This builder for chaining. */ public Builder clearFilter() { filter_ = getDefaultInstance().getFilter(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); return this; } /** * * * <pre> * Filtering results * </pre> * * <code>string filter = 4;</code> * * @param value The bytes for filter to set. * @return This builder for chaining. */ public Builder setFilterBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); filter_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } private java.lang.Object orderBy_ = ""; /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @return The orderBy. */ public java.lang.String getOrderBy() { java.lang.Object ref = orderBy_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); orderBy_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @return The bytes for orderBy. */ public com.google.protobuf.ByteString getOrderByBytes() { java.lang.Object ref = orderBy_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); orderBy_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @param value The orderBy to set. * @return This builder for chaining. */ public Builder setOrderBy(java.lang.String value) { if (value == null) { throw new NullPointerException(); } orderBy_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @return This builder for chaining. */ public Builder clearOrderBy() { orderBy_ = getDefaultInstance().getOrderBy(); bitField0_ = (bitField0_ & ~0x00000010); onChanged(); return this; } /** * * * <pre> * Hint for how to order the results * </pre> * * <code>string order_by = 5;</code> * * @param value The bytes for orderBy to set. * @return This builder for chaining. */ public Builder setOrderByBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); orderBy_ = value; bitField0_ |= 0x00000010; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.netapp.v1.ListVolumesRequest) } // @@protoc_insertion_point(class_scope:google.cloud.netapp.v1.ListVolumesRequest) private static final com.google.cloud.netapp.v1.ListVolumesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.netapp.v1.ListVolumesRequest(); } public static com.google.cloud.netapp.v1.ListVolumesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListVolumesRequest> PARSER = new com.google.protobuf.AbstractParser<ListVolumesRequest>() { @java.lang.Override public ListVolumesRequest 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<ListVolumesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListVolumesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.netapp.v1.ListVolumesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }