repo_id
stringclasses
875 values
size
int64
974
38.9k
file_path
stringlengths
10
308
content
stringlengths
974
38.9k
google/j2objc
36,609
jre_emul/Classes/java/lang/Thread.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 java.lang; import com.google.j2objc.annotations.Weak; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import sun.nio.ch.Interruptible; /*-[ #import "java/lang/AssertionError.h" #import "java_lang_Thread.h" #import "objc-sync.h" #import <pthread.h> ]-*/ /*-[ @interface NativeThread : NSObject { @public pthread_t t; } @end @implementation NativeThread @end ]-*/ /** * Simplified iOS version of java.lang.Thread, based on Apache Harmony source * (both luni-kernel and vmcore). This class uses pthread for thread creation * and maintains a pthread handle for using other pthread functionality. * pthread's thread local mechanism (pthread_setspecific) is used to associate * this wrapper object with the current thread. * * @author Tom Ball, Keith Stanger */ public class Thread implements Runnable { private static final int NANOS_PER_MILLI = 1000000; /** Android source declares this as the native VMThread class. */ private final Object nativeThread; private Runnable target; private final long threadId; private String name; private final long stackSize; private int priority = NORM_PRIORITY; private volatile UncaughtExceptionHandler uncaughtExceptionHandler; private boolean isDaemon; private boolean interrupted; private ClassLoader contextClassLoader; ThreadLocal.ThreadLocalMap threadLocals = null; ThreadLocal.ThreadLocalMap inheritableThreadLocals = null; static final int STATE_NEW = 0; static final int STATE_RUNNABLE = 1; static final int STATE_BLOCKED = 2; static final int STATE_WAITING = 3; static final int STATE_TIMED_WAITING = 4; static final int STATE_TERMINATED = 5; // Accessing a volatile int is cheaper than a volatile object. volatile int state = STATE_NEW; /** The object the thread is waiting on (normally null). */ Object blocker; /** The object in which this thread is blocked in an interruptible I/O operation, if any. */ private Interruptible IOBlocker; private final Object IOBlockerLock = new Object(); @Weak private ThreadGroup threadGroup; /** the park state of the thread */ private int parkState = ParkState.UNPARKED; /** The synchronization object responsible for this thread parking. */ private Object parkBlocker; /** Callbacks to run on interruption. */ private final List<Runnable> interruptActions = new ArrayList<Runnable>(); /** * Counter used to generate thread's ID */ private static long threadOrdinalNum = 1; /** * A representation of a thread's state. A given thread may only be in one * state at a time. */ public enum State { /** * The thread has been created, but has never been started. */ NEW, /** * The thread may be run. */ RUNNABLE, /** * The thread is blocked and waiting for a lock. */ BLOCKED, /** * The thread is waiting. */ WAITING, /** * The thread is waiting for a specified amount of time. */ TIMED_WAITING, /** * The thread has been terminated. */ TERMINATED } /** Park states */ private static class ParkState { /** park state indicating unparked */ private static final int UNPARKED = 1; /** park state indicating preemptively unparked */ private static final int PREEMPTIVELY_UNPARKED = 2; /** park state indicating parked */ private static final int PARKED = 3; } public interface UncaughtExceptionHandler { void uncaughtException(Thread t, Throwable e); } // Fields accessed reflectively by ThreadLocalRandom. long threadLocalRandomSeed; int threadLocalRandomProbe; int threadLocalRandomSecondarySeed; /** * Holds the default handler for uncaught exceptions, in case there is one. */ private static volatile UncaughtExceptionHandler defaultUncaughtHandler = new SystemUncaughtExceptionHandler(); /** * <p> * The maximum priority value allowed for a thread. * </p> */ public final static int MAX_PRIORITY = 10; /** * <p> * The minimum priority value allowed for a thread. * </p> */ public final static int MIN_PRIORITY = 1; /** * <p> * The normal (default) priority value assigned to threads. * </p> */ public final static int NORM_PRIORITY = 5; /** * used to generate a default thread name */ private static final String THREAD = "Thread-"; // Milliseconds between polls for testing thread completion. private static final int POLL_INTERVAL = 20; static { initializeThreadClass(); } private static native Object newNativeThread() /*-[ return AUTORELEASE([[NativeThread alloc] init]); ]-*/; /** * Constructs a new Thread with no runnable object and a newly generated * name. The new Thread will belong to the same ThreadGroup as the Thread * calling this constructor. * * @see java.lang.ThreadGroup */ public Thread() { this(null, null, THREAD, 0, null); } /** * Constructs a new Thread with a runnable object and a newly generated * name. The new Thread will belong to the same ThreadGroup as the Thread * calling this constructor. * * @param runnable a java.lang.Runnable whose method <code>run</code> will * be executed by the new Thread * @see java.lang.ThreadGroup * @see java.lang.Runnable */ public Thread(Runnable runnable) { this(null, runnable, THREAD, 0, null); } /** * Constructs a new Thread with a runnable object and name provided. The new * Thread will belong to the same ThreadGroup as the Thread calling this * constructor. * * @param runnable a java.lang.Runnable whose method <code>run</code> will * be executed by the new Thread * @param threadName Name for the Thread being created * @see java.lang.ThreadGroup * @see java.lang.Runnable */ public Thread(Runnable runnable, String threadName) { this(null, runnable, threadName, 0, null); } /** * Constructs a new Thread with no runnable object and the name provided. * The new Thread will belong to the same ThreadGroup as the Thread calling * this constructor. * * @param threadName Name for the Thread being created * @see java.lang.ThreadGroup * @see java.lang.Runnable */ public Thread(String threadName) { this(null, null, threadName, 0, null); } /** * Constructs a new Thread with a runnable object and a newly generated * name. The new Thread will belong to the ThreadGroup passed as parameter. * * @param group ThreadGroup to which the new Thread will belong * @param runnable a java.lang.Runnable whose method <code>run</code> will * be executed by the new Thread * @throws SecurityException if <code>group.checkAccess()</code> fails * with a SecurityException * @throws IllegalThreadStateException if <code>group.destroy()</code> has * already been done * @see java.lang.ThreadGroup * @see java.lang.Runnable * @see java.lang.SecurityException * @see java.lang.SecurityManager */ public Thread(ThreadGroup group, Runnable runnable) { this(group, runnable, THREAD, 0, null); } /** * Constructs a new Thread with a runnable object, the given name and * belonging to the ThreadGroup passed as parameter. * * @param group ThreadGroup to which the new Thread will belong * @param runnable a java.lang.Runnable whose method <code>run</code> will * be executed by the new Thread * @param threadName Name for the Thread being created * @param stack Platform dependent stack size * @throws SecurityException if <code>group.checkAccess()</code> fails * with a SecurityException * @throws IllegalThreadStateException if <code>group.destroy()</code> has * already been done * @see java.lang.ThreadGroup * @see java.lang.Runnable * @see java.lang.SecurityException * @see java.lang.SecurityManager */ public Thread(ThreadGroup group, Runnable runnable, String threadName, long stack) { this(group, runnable, threadName, stack, null); } /** * Constructs a new Thread with a runnable object, the given name and * belonging to the ThreadGroup passed as parameter. * * @param group ThreadGroup to which the new Thread will belong * @param runnable a java.lang.Runnable whose method <code>run</code> will * be executed by the new Thread * @param threadName Name for the Thread being created * @throws SecurityException if <code>group.checkAccess()</code> fails * with a SecurityException * @throws IllegalThreadStateException if <code>group.destroy()</code> has * already been done * @see java.lang.ThreadGroup * @see java.lang.Runnable * @see java.lang.SecurityException * @see java.lang.SecurityManager */ public Thread(ThreadGroup group, Runnable runnable, String threadName) { this(group, runnable, threadName, 0, null); } /** * Constructs a new Thread with no runnable object, the given name and * belonging to the ThreadGroup passed as parameter. * * @param group ThreadGroup to which the new Thread will belong * @param threadName Name for the Thread being created * @throws SecurityException if <code>group.checkAccess()</code> fails * with a SecurityException * @throws IllegalThreadStateException if <code>group.destroy()</code> has * already been done * @see java.lang.ThreadGroup * @see java.lang.SecurityException * @see java.lang.SecurityManager */ public Thread(ThreadGroup group, String threadName) { this(group, null, threadName, 0, null); } private Thread( ThreadGroup group, Runnable runnable, String name, long stack, Object nativeThread) { this.target = runnable; this.threadId = getNextThreadId(); if (name.equals(THREAD)) { name += threadId; } this.name = name; this.stackSize = stack; if (nativeThread == null) { // Thread is not yet started. Thread currentThread = currentThread(); nativeThread = newNativeThread(); this.priority = currentThread.getPriority(); if (group == null) { group = currentThread.getThreadGroup(); } } else { // Thread is already running. state = STATE_RUNNABLE; group.add(this); } this.threadGroup = group; this.nativeThread = nativeThread; } /*-[ void *start_routine(void *arg) { JavaLangThread *thread = (JavaLangThread *)arg; pthread_setspecific(java_thread_key, thread); pthread_setname_np([thread->name_ UTF8String]); @autoreleasepool { @try { [thread run]; } @catch (JavaLangThrowable *t) { JavaLangThread_rethrowWithJavaLangThrowable_(thread, t); } @catch (id error) { JavaLangThread_rethrowWithJavaLangThrowable_( thread, create_JavaLangThrowable_initWithNSString_( [NSString stringWithFormat:@"Unknown error: %@", [error description]])); } return NULL; } } ]-*/ private static Thread createMainThread(Object nativeThread) { return new Thread(ThreadGroup.mainThreadGroup, null, "main", 0, nativeThread); } /** * Create a Thread wrapper around the main native thread. */ private static native void initializeThreadClass() /*-[ initJavaThreadKeyOnce(); NativeThread *nt = AUTORELEASE([[NativeThread alloc] init]); nt->t = pthread_self(); JavaLangThread *mainThread = JavaLangThread_createMainThreadWithId_(nt); pthread_setspecific(java_thread_key, RETAIN_(mainThread)); ]-*/; private static Thread createCurrentThread(Object nativeThread) { return new Thread(ThreadGroup.mainThreadGroup, null, THREAD, 0, nativeThread); } public static native Thread currentThread() /*-[ JavaLangThread *thread = pthread_getspecific(java_thread_key); if (thread) { return thread; } NativeThread *nt = AUTORELEASE([[NativeThread alloc] init]); nt->t = pthread_self(); thread = JavaLangThread_createCurrentThreadWithId_(nt); pthread_setspecific(java_thread_key, RETAIN_(thread)); return thread; ]-*/; public synchronized void start() { if (state != STATE_NEW) { throw new IllegalThreadStateException("This thread was already started!"); } threadGroup.add(this); state = STATE_RUNNABLE; start0(); if (priority != NORM_PRIORITY) { nativeSetPriority(priority); } } private native void start0() /*-[ NativeThread *nt = (NativeThread *)self->nativeThread_; pthread_attr_t attr; pthread_attr_init(&attr); size_t stack = (size_t)self->stackSize_; if (stack >= PTHREAD_STACK_MIN) { pthread_attr_setstacksize(&attr, stack); } pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&nt->t, &attr, &start_routine, RETAIN_(self)); ]-*/; void exit() { state = STATE_TERMINATED; if (threadGroup != null) { threadGroup.threadTerminated(this); threadGroup = null; } target = null; uncaughtExceptionHandler = null; interruptActions.clear(); } @Override public void run() { if (target != null) { target.run(); } } private void rethrow(Throwable t) throws Throwable { UncaughtExceptionHandler ueh = getUncaughtExceptionHandler(); if (ueh != null) { ueh.uncaughtException(this, t); } else { throw t; } } public static int activeCount() { return currentThread().getThreadGroup().activeCount(); } public boolean isDaemon() { return isDaemon; } public void setDaemon(boolean isDaemon) { this.isDaemon = isDaemon; } /** * Prints to the standard error stream a text representation of the current * stack for this Thread. * * @see Throwable#printStackTrace() */ public static void dumpStack() { new Throwable("stack dump").printStackTrace(); } public static int enumerate(Thread[] threads) { Thread thread = Thread.currentThread(); return thread.getThreadGroup().enumerate(threads); } public long getId() { return threadId; } public final String getName() { return name; } public final void setName(String name) { checkAccess(); if (name == null) { throw new NullPointerException("name == null"); } this.name = name; } public final int getPriority() { return priority; } public final void setPriority(int newPriority) { ThreadGroup g; checkAccess(); if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) { throw new IllegalArgumentException(); } if ((g = getThreadGroup()) != null) { if (newPriority > g.getMaxPriority()) { newPriority = g.getMaxPriority(); } synchronized (this) { this.priority = newPriority; if (isAlive()) { nativeSetPriority(newPriority); } } } } private native void nativeSetPriority(int priority) /*-[ struct sched_param param; param.sched_priority = (priority * 64 / JavaLangThread_MAX_PRIORITY) - 1; NativeThread *nt = (NativeThread *)self->nativeThread_; pthread_setschedparam(nt->t, SCHED_OTHER, &param); ]-*/; public State getState() { switch (state) { case STATE_NEW: return State.NEW; case STATE_RUNNABLE: return State.RUNNABLE; case STATE_BLOCKED: return State.BLOCKED; case STATE_WAITING: return State.WAITING; case STATE_TIMED_WAITING: return State.TIMED_WAITING; case STATE_TERMINATED: return State.TERMINATED; } // Unreachable. return null; } public ThreadGroup getThreadGroup() { return state == STATE_TERMINATED ? null : threadGroup; } public StackTraceElement[] getStackTrace() { // Get the stack trace for a new exception, stripping the exception's // and preamble's (runtime startup) frames. StackTraceElement[] exceptionTrace = new Throwable().getStackTrace(); int firstElement = 0; int lastElement = exceptionTrace.length; for (int i = 0; i < exceptionTrace.length; i++) { String methodName = exceptionTrace[i].getMethodName(); if (methodName.contains("getStackTrace")) { firstElement = i; continue; } if (methodName.contains("mainWithNSStringArray:")) { lastElement = i; break; } } int nFrames = lastElement - firstElement + 1; if (nFrames < 0) { // Something failed, return the whole stack trace. return exceptionTrace; } if (firstElement + nFrames > exceptionTrace.length) { nFrames = exceptionTrace.length - firstElement; } StackTraceElement[] result = new StackTraceElement[nFrames]; System.arraycopy(exceptionTrace, firstElement, result, 0, nFrames); return result; } @Deprecated public int countStackFrames() { return getStackTrace().length; } /** Set the IOBlocker field; invoked from java.nio code. */ public void blockedOn(Interruptible b) { synchronized (IOBlockerLock) { IOBlocker = b; } } /** * Posts an interrupt request to this {@code Thread}. Unless the caller is * the {@link #currentThread()}, the method {@code checkAccess()} is called * for the installed {@code SecurityManager}, if any. This may result in a * {@code SecurityException} being thrown. The further behavior depends on * the state of this {@code Thread}: * <ul> * <li> * {@code Thread}s blocked in one of {@code Object}'s {@code wait()} methods * or one of {@code Thread}'s {@code join()} or {@code sleep()} methods will * be woken up, their interrupt status will be cleared, and they receive an * {@link InterruptedException}. * <li> * {@code Thread}s blocked in an I/O operation of an * {@link java.nio.channels.InterruptibleChannel} will have their interrupt * status set and receive an * {@link java.nio.channels.ClosedByInterruptException}. Also, the channel * will be closed. * <li> * {@code Thread}s blocked in a {@link java.nio.channels.Selector} will have * their interrupt status set and return immediately. They don't receive an * exception in this case. * <ul> * * @throws SecurityException * if <code>checkAccess()</code> fails with a SecurityException * @see java.lang.SecurityException * @see java.lang.SecurityManager * @see Thread#interrupted * @see Thread#isInterrupted */ public void interrupt() { synchronized(nativeThread) { synchronized (interruptActions) { for (int i = interruptActions.size() - 1; i >= 0; i--) { interruptActions.get(i).run(); } } synchronized (IOBlockerLock) { Interruptible b = IOBlocker; if (b != null) { b.interrupt(this); } } if (interrupted) { return; // No further action needed. } interrupted = true; if (blocker != null) { synchronized(blocker) { blocker.notify(); } } } } /** * Returns a <code>boolean</code> indicating whether the current Thread ( <code>currentThread() * </code>) has a pending interrupt request (<code> * true</code>) or not (<code>false</code>). It also has the side-effect of clearing the flag. * * @return a <code>boolean</code> indicating the interrupt status * @see Thread#currentThread * @see Thread#interrupt * @see Thread#isInterrupted */ public static native boolean interrupted() /*-[ JavaLangThread *currentThread = JavaLangThread_currentThread(); @synchronized(currentThread->nativeThread_) { bool result = currentThread->interrupted_; currentThread->interrupted_ = false; return result; } ]-*/; /** * Returns a <code>boolean</code> indicating whether the receiver has a * pending interrupt request (<code>true</code>) or not ( * <code>false</code>) * * @return a <code>boolean</code> indicating the interrupt status * @see Thread#interrupt * @see Thread#interrupted */ public boolean isInterrupted() { synchronized (nativeThread) { return interrupted; } } /** * Blocks the current Thread (<code>Thread.currentThread()</code>) until * the receiver finishes its execution and dies. * * @throws InterruptedException if <code>interrupt()</code> was called for * the receiver while it was in the <code>join()</code> call * @see Object#notifyAll * @see java.lang.ThreadDeath */ public final void join() throws InterruptedException { if (!isAlive()) { return; } Object lock = currentThread().nativeThread; synchronized (lock) { while (isAlive()) { lock.wait(POLL_INTERVAL); } } } /** * Blocks the current Thread (<code>Thread.currentThread()</code>) until * the receiver finishes its execution and dies or the specified timeout * expires, whatever happens first. * * @param millis The maximum time to wait (in milliseconds). * @throws InterruptedException if <code>interrupt()</code> was called for * the receiver while it was in the <code>join()</code> call * @see Object#notifyAll * @see java.lang.ThreadDeath */ public final void join(long millis) throws InterruptedException { join(millis, 0); } /** * Blocks the current Thread (<code>Thread.currentThread()</code>) until * the receiver finishes its execution and dies or the specified timeout * expires, whatever happens first. * * @param millis The maximum time to wait (in milliseconds). * @param nanos Extra nanosecond precision * @throws InterruptedException if <code>interrupt()</code> was called for * the receiver while it was in the <code>join()</code> call * @see Object#notifyAll * @see java.lang.ThreadDeath */ public final void join(long millis, int nanos) throws InterruptedException { if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) { throw new IllegalArgumentException("bad timeout: millis=" + millis + ",nanos=" + nanos); } // avoid overflow: if total > 292,277 years, just wait forever boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI; boolean forever = (millis | nanos) == 0; if (forever | overflow) { join(); return; } if (!isAlive()) { return; } Object lock = currentThread().nativeThread; synchronized (lock) { if (!isAlive()) { return; } // guaranteed not to overflow long nanosToWait = millis * NANOS_PER_MILLI + nanos; // wait until this thread completes or the timeout has elapsed long start = System.nanoTime(); while (true) { if (millis > POLL_INTERVAL) { lock.wait(POLL_INTERVAL); } else { lock.wait(millis, nanos); } if (!isAlive()) { break; } long nanosElapsed = System.nanoTime() - start; long nanosRemaining = nanosToWait - nanosElapsed; if (nanosRemaining <= 0) { break; } millis = nanosRemaining / NANOS_PER_MILLI; nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI); } } } public final boolean isAlive() { int s = state; return s != STATE_NEW && s != STATE_TERMINATED; } public void checkAccess() { // Access checks not implemented on iOS. } public static void sleep(long millis) throws InterruptedException { sleep(millis, 0); } public static void sleep(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("millis < 0: " + millis); } if (nanos < 0) { throw new IllegalArgumentException("nanos < 0: " + nanos); } if (nanos > 999999) { throw new IllegalArgumentException("nanos > 999999: " + nanos); } // The JLS 3rd edition, section 17.9 says: "...sleep for zero // time...need not have observable effects." if (millis == 0 && nanos == 0) { // ...but we still have to handle being interrupted. if (Thread.interrupted()) { throw new InterruptedException(); } return; } Object lock = currentThread().nativeThread; synchronized(lock) { lock.wait(millis, nanos); } } /** * Causes the calling Thread to yield execution time to another Thread that * is ready to run. The actual scheduling is implementation-dependent. */ public static native void yield() /*-[ pthread_yield_np(); ]-*/; private static synchronized long getNextThreadId() { return threadOrdinalNum++; } /** * Indicates whether the current Thread has a monitor lock on the specified * object. * * @param object the object to test for the monitor lock * @return true if the current thread has a monitor lock on the specified * object; false otherwise */ public static native boolean holdsLock(Object object) /*-[ return j2objc_sync_holds_lock(object); ]-*/; /** * Returns the context ClassLoader for this Thread. * * @return ClassLoader The context ClassLoader * @see java.lang.ClassLoader */ public ClassLoader getContextClassLoader() { return contextClassLoader != null ? contextClassLoader : ClassLoader.getSystemClassLoader(); } public void setContextClassLoader(ClassLoader cl) { contextClassLoader = cl; } public String toString() { ThreadGroup group = getThreadGroup(); if (group != null) { return "Thread[" + getName() + "," + getPriority() + "," + group.getName() + "]"; } return "Thread[" + getName() + "," + getPriority() + ",]"; } /** * Unparks this thread. This unblocks the thread it if it was * previously parked, or indicates that the thread is "preemptively * unparked" if it wasn't already parked. The latter means that the * next time the thread is told to park, it will merely clear its * latent park bit and carry on without blocking. * * <p>See {@link java.util.concurrent.locks.LockSupport} for more * in-depth information of the behavior of this method.</p> * * @hide for Unsafe */ public final void unpark$() { Object vmt = nativeThread; synchronized (vmt) { switch (parkState) { case ParkState.PREEMPTIVELY_UNPARKED: { /* * Nothing to do in this case: By definition, a * preemptively unparked thread is to remain in * the preemptively unparked state if it is told * to unpark. */ break; } case ParkState.UNPARKED: { parkState = ParkState.PREEMPTIVELY_UNPARKED; break; } default /*parked*/: { parkState = ParkState.UNPARKED; vmt.notifyAll(); break; } } } } /** * Parks the current thread for a particular number of nanoseconds, or * indefinitely. If not indefinitely, this method unparks the thread * after the given number of nanoseconds if no other thread unparks it * first. If the thread has been "preemptively unparked," this method * cancels that unparking and returns immediately. This method may * also return spuriously (that is, without the thread being told to * unpark and without the indicated amount of time elapsing). * * <p>See {@link java.util.concurrent.locks.LockSupport} for more * in-depth information of the behavior of this method.</p> * * <p>This method must only be called when <code>this</code> is the current * thread. * * @param nanos number of nanoseconds to park for or <code>0</code> * to park indefinitely * @throws IllegalArgumentException thrown if <code>nanos &lt; 0</code> * * @hide for Unsafe */ public final void parkFor$(long nanos) { Object vmt = nativeThread; synchronized (vmt) { switch (parkState) { case ParkState.PREEMPTIVELY_UNPARKED: { parkState = ParkState.UNPARKED; break; } case ParkState.UNPARKED: { long millis = nanos / NANOS_PER_MILLI; nanos %= NANOS_PER_MILLI; parkState = ParkState.PARKED; try { vmt.wait(millis, (int) nanos); } catch (InterruptedException ex) { interrupt(); } finally { /* * Note: If parkState manages to become * PREEMPTIVELY_UNPARKED before hitting this * code, it should left in that state. */ if (parkState == ParkState.PARKED) { parkState = ParkState.UNPARKED; } } break; } default /*parked*/: { throw new AssertionError("shouldn't happen: attempt to repark"); } } } } /** * Parks the current thread until the specified system time. This * method attempts to unpark the current thread immediately after * <code>System.currentTimeMillis()</code> reaches the specified * value, if no other thread unparks it first. If the thread has * been "preemptively unparked," this method cancels that * unparking and returns immediately. This method may also return * spuriously (that is, without the thread being told to unpark * and without the indicated amount of time elapsing). * * <p>See {@link java.util.concurrent.locks.LockSupport} for more * in-depth information of the behavior of this method.</p> * * <p>This method must only be called when <code>this</code> is the * current thread. * * @param time the time after which the thread should be unparked, * in absolute milliseconds-since-the-epoch * * @hide for Unsafe */ public final void parkUntil$(long time) { Object vmt = nativeThread; synchronized (vmt) { /* * Note: This conflates the two time bases of "wall clock" * time and "monotonic uptime" time. However, given that * the underlying system can only wait on monotonic time, * it is unclear if there is any way to avoid the * conflation. The downside here is that if, having * calculated the delay, the wall clock gets moved ahead, * this method may not return until well after the wall * clock has reached the originally designated time. The * reverse problem (the wall clock being turned back) * isn't a big deal, since this method is allowed to * spuriously return for any reason, and this situation * can safely be construed as just such a spurious return. */ long delayMillis = time - System.currentTimeMillis(); if (delayMillis <= 0) { parkState = ParkState.UNPARKED; } else { parkFor$(delayMillis * NANOS_PER_MILLI); } } } /** * Returns the default exception handler that's executed when uncaught * exception terminates a thread. * * @return an {@link UncaughtExceptionHandler} or <code>null</code> if * none exists. */ public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() { return defaultUncaughtHandler; } /** * Sets the default uncaught exception handler. This handler is invoked in * case any Thread dies due to an unhandled exception. * * @param handler * The handler to set or null. */ public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler) { Thread.defaultUncaughtHandler = handler; } /** * Returns the handler invoked when this thread abruptly terminates * due to an uncaught exception. If this thread has not had an * uncaught exception handler explicitly set then this thread's * <tt>ThreadGroup</tt> object is returned, unless this thread * has terminated, in which case <tt>null</tt> is returned. * @since 1.5 */ public UncaughtExceptionHandler getUncaughtExceptionHandler() { UncaughtExceptionHandler h = uncaughtExceptionHandler; return h != null ? h : threadGroup; } /** * Set the handler invoked when this thread abruptly terminates * due to an uncaught exception. * <p>A thread can take full control of how it responds to uncaught * exceptions by having its uncaught exception handler explicitly set. * If no such handler is set then the thread's <tt>ThreadGroup</tt> * object acts as its handler. * @param eh the object to use as this thread's uncaught exception * handler. If <tt>null</tt> then this thread has no explicit handler. * @throws SecurityException if the current thread is not allowed to * modify this thread. * @see #setDefaultUncaughtExceptionHandler * @see ThreadGroup#uncaughtException * @since 1.5 */ public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) { checkAccess(); uncaughtExceptionHandler = eh; } private static class SystemUncaughtExceptionHandler implements UncaughtExceptionHandler { @Override public synchronized void uncaughtException(Thread t, Throwable e) { // Log the exception using the root logger (""), so it isn't accidentally filtered. Logger.getLogger("").log( Level.SEVERE, "Uncaught exception in thread \"" + t.getName() + "\"", e); } } /** * Adds a runnable to be invoked upon interruption. If this thread has * already been interrupted, the runnable will be invoked immediately. The * action should be idempotent as it may be invoked multiple times for a * single interruption. * * <p>Each call to this method must be matched with a corresponding call to * {@link #popInterruptAction$}. * * @hide used by NIO */ public final void pushInterruptAction$(Runnable interruptAction) { synchronized (interruptActions) { interruptActions.add(interruptAction); } if (interruptAction != null && isInterrupted()) { interruptAction.run(); } } /** * Removes {@code interruptAction} so it is not invoked upon interruption. * * @param interruptAction the pushed action, used to check that the call * stack is correctly nested. * * @hide used by NIO */ public final void popInterruptAction$(Runnable interruptAction) { synchronized (interruptActions) { Runnable removed = interruptActions.remove(interruptActions.size() - 1); if (interruptAction != removed) { throw new IllegalArgumentException( "Expected " + interruptAction + " but was " + removed); } } } /** * Returns a map of stack traces for all live threads. */ // TODO(dweis): Can we update this to return something useful? public static Map<Thread,StackTraceElement[]> getAllStackTraces() { return Collections.<Thread, StackTraceElement[]>emptyMap(); } @Deprecated public final void stop() { stop(new ThreadDeath()); } @Deprecated public final void stop(Throwable obj) { throw new UnsupportedOperationException(); } @Deprecated public void destroy() { throw new UnsupportedOperationException(); } @Deprecated public final void suspend() { throw new UnsupportedOperationException(); } @Deprecated public final void resume() { throw new UnsupportedOperationException(); } }
googleapis/google-cloud-java
36,550
java-vision/proto-google-cloud-vision-v1p3beta1/src/main/java/com/google/cloud/vision/v1p3beta1/ListProductsInProductSetResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1p3beta1/product_search_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.vision.v1p3beta1; /** * * * <pre> * Response message for the `ListProductsInProductSet` method. * </pre> * * Protobuf type {@code google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse} */ public final class ListProductsInProductSetResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) ListProductsInProductSetResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListProductsInProductSetResponse.newBuilder() to construct. private ListProductsInProductSetResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListProductsInProductSetResponse() { products_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListProductsInProductSetResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p3beta1_ListProductsInProductSetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p3beta1_ListProductsInProductSetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.class, com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.Builder.class); } public static final int PRODUCTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.vision.v1p3beta1.Product> products_; /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.vision.v1p3beta1.Product> getProductsList() { return products_; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.vision.v1p3beta1.ProductOrBuilder> getProductsOrBuilderList() { return products_; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ @java.lang.Override public int getProductsCount() { return products_.size(); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ @java.lang.Override public com.google.cloud.vision.v1p3beta1.Product getProducts(int index) { return products_.get(index); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ @java.lang.Override public com.google.cloud.vision.v1p3beta1.ProductOrBuilder getProductsOrBuilder(int index) { return products_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < products_.size(); i++) { output.writeMessage(1, products_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < products_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, products_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse)) { return super.equals(obj); } com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse other = (com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) obj; if (!getProductsList().equals(other.getProductsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getProductsCount() > 0) { hash = (37 * hash) + PRODUCTS_FIELD_NUMBER; hash = (53 * hash) + getProductsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse 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 `ListProductsInProductSet` method. * </pre> * * Protobuf type {@code google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p3beta1_ListProductsInProductSetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p3beta1_ListProductsInProductSetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.class, com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.Builder.class); } // Construct using // com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (productsBuilder_ == null) { products_ = java.util.Collections.emptyList(); } else { products_ = null; productsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p3beta1_ListProductsInProductSetResponse_descriptor; } @java.lang.Override public com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse getDefaultInstanceForType() { return com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse build() { com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse buildPartial() { com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse result = new com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse result) { if (productsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { products_ = java.util.Collections.unmodifiableList(products_); bitField0_ = (bitField0_ & ~0x00000001); } result.products_ = products_; } else { result.products_ = productsBuilder_.build(); } } private void buildPartial0( com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) { return mergeFrom( (com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse other) { if (other == com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse .getDefaultInstance()) return this; if (productsBuilder_ == null) { if (!other.products_.isEmpty()) { if (products_.isEmpty()) { products_ = other.products_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProductsIsMutable(); products_.addAll(other.products_); } onChanged(); } } else { if (!other.products_.isEmpty()) { if (productsBuilder_.isEmpty()) { productsBuilder_.dispose(); productsBuilder_ = null; products_ = other.products_; bitField0_ = (bitField0_ & ~0x00000001); productsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getProductsFieldBuilder() : null; } else { productsBuilder_.addAllMessages(other.products_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.vision.v1p3beta1.Product m = input.readMessage( com.google.cloud.vision.v1p3beta1.Product.parser(), extensionRegistry); if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.add(m); } else { productsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.vision.v1p3beta1.Product> products_ = java.util.Collections.emptyList(); private void ensureProductsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { products_ = new java.util.ArrayList<com.google.cloud.vision.v1p3beta1.Product>(products_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vision.v1p3beta1.Product, com.google.cloud.vision.v1p3beta1.Product.Builder, com.google.cloud.vision.v1p3beta1.ProductOrBuilder> productsBuilder_; /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public java.util.List<com.google.cloud.vision.v1p3beta1.Product> getProductsList() { if (productsBuilder_ == null) { return java.util.Collections.unmodifiableList(products_); } else { return productsBuilder_.getMessageList(); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public int getProductsCount() { if (productsBuilder_ == null) { return products_.size(); } else { return productsBuilder_.getCount(); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p3beta1.Product getProducts(int index) { if (productsBuilder_ == null) { return products_.get(index); } else { return productsBuilder_.getMessage(index); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder setProducts(int index, com.google.cloud.vision.v1p3beta1.Product value) { if (productsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProductsIsMutable(); products_.set(index, value); onChanged(); } else { productsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder setProducts( int index, com.google.cloud.vision.v1p3beta1.Product.Builder builderForValue) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.set(index, builderForValue.build()); onChanged(); } else { productsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder addProducts(com.google.cloud.vision.v1p3beta1.Product value) { if (productsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProductsIsMutable(); products_.add(value); onChanged(); } else { productsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder addProducts(int index, com.google.cloud.vision.v1p3beta1.Product value) { if (productsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProductsIsMutable(); products_.add(index, value); onChanged(); } else { productsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder addProducts(com.google.cloud.vision.v1p3beta1.Product.Builder builderForValue) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.add(builderForValue.build()); onChanged(); } else { productsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder addProducts( int index, com.google.cloud.vision.v1p3beta1.Product.Builder builderForValue) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.add(index, builderForValue.build()); onChanged(); } else { productsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder addAllProducts( java.lang.Iterable<? extends com.google.cloud.vision.v1p3beta1.Product> values) { if (productsBuilder_ == null) { ensureProductsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, products_); onChanged(); } else { productsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder clearProducts() { if (productsBuilder_ == null) { products_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { productsBuilder_.clear(); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public Builder removeProducts(int index) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.remove(index); onChanged(); } else { productsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p3beta1.Product.Builder getProductsBuilder(int index) { return getProductsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p3beta1.ProductOrBuilder getProductsOrBuilder(int index) { if (productsBuilder_ == null) { return products_.get(index); } else { return productsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public java.util.List<? extends com.google.cloud.vision.v1p3beta1.ProductOrBuilder> getProductsOrBuilderList() { if (productsBuilder_ != null) { return productsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(products_); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p3beta1.Product.Builder addProductsBuilder() { return getProductsFieldBuilder() .addBuilder(com.google.cloud.vision.v1p3beta1.Product.getDefaultInstance()); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p3beta1.Product.Builder addProductsBuilder(int index) { return getProductsFieldBuilder() .addBuilder(index, com.google.cloud.vision.v1p3beta1.Product.getDefaultInstance()); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code> */ public java.util.List<com.google.cloud.vision.v1p3beta1.Product.Builder> getProductsBuilderList() { return getProductsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vision.v1p3beta1.Product, com.google.cloud.vision.v1p3beta1.Product.Builder, com.google.cloud.vision.v1p3beta1.ProductOrBuilder> getProductsFieldBuilder() { if (productsBuilder_ == null) { productsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vision.v1p3beta1.Product, com.google.cloud.vision.v1p3beta1.Product.Builder, com.google.cloud.vision.v1p3beta1.ProductOrBuilder>( products_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); products_ = null; } return productsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) } // @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse) private static final com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse(); } public static com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListProductsInProductSetResponse> PARSER = new com.google.protobuf.AbstractParser<ListProductsInProductSetResponse>() { @java.lang.Override public ListProductsInProductSetResponse 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<ListProductsInProductSetResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListProductsInProductSetResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vision.v1p3beta1.ListProductsInProductSetResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,550
java-vision/proto-google-cloud-vision-v1p4beta1/src/main/java/com/google/cloud/vision/v1p4beta1/ListProductsInProductSetResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1p4beta1/product_search_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.vision.v1p4beta1; /** * * * <pre> * Response message for the `ListProductsInProductSet` method. * </pre> * * Protobuf type {@code google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse} */ public final class ListProductsInProductSetResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) ListProductsInProductSetResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListProductsInProductSetResponse.newBuilder() to construct. private ListProductsInProductSetResponse( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListProductsInProductSetResponse() { products_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListProductsInProductSetResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p4beta1_ListProductsInProductSetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p4beta1_ListProductsInProductSetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.class, com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.Builder.class); } public static final int PRODUCTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.vision.v1p4beta1.Product> products_; /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.vision.v1p4beta1.Product> getProductsList() { return products_; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.vision.v1p4beta1.ProductOrBuilder> getProductsOrBuilderList() { return products_; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ @java.lang.Override public int getProductsCount() { return products_.size(); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ @java.lang.Override public com.google.cloud.vision.v1p4beta1.Product getProducts(int index) { return products_.get(index); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ @java.lang.Override public com.google.cloud.vision.v1p4beta1.ProductOrBuilder getProductsOrBuilder(int index) { return products_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < products_.size(); i++) { output.writeMessage(1, products_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < products_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, products_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse)) { return super.equals(obj); } com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse other = (com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) obj; if (!getProductsList().equals(other.getProductsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getProductsCount() > 0) { hash = (37 * hash) + PRODUCTS_FIELD_NUMBER; hash = (53 * hash) + getProductsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse 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 `ListProductsInProductSet` method. * </pre> * * Protobuf type {@code google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p4beta1_ListProductsInProductSetResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p4beta1_ListProductsInProductSetResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.class, com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.Builder.class); } // Construct using // com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (productsBuilder_ == null) { products_ = java.util.Collections.emptyList(); } else { products_ = null; productsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto .internal_static_google_cloud_vision_v1p4beta1_ListProductsInProductSetResponse_descriptor; } @java.lang.Override public com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse getDefaultInstanceForType() { return com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse .getDefaultInstance(); } @java.lang.Override public com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse build() { com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse buildPartial() { com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse result = new com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse result) { if (productsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { products_ = java.util.Collections.unmodifiableList(products_); bitField0_ = (bitField0_ & ~0x00000001); } result.products_ = products_; } else { result.products_ = productsBuilder_.build(); } } private void buildPartial0( com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) { return mergeFrom( (com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse other) { if (other == com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse .getDefaultInstance()) return this; if (productsBuilder_ == null) { if (!other.products_.isEmpty()) { if (products_.isEmpty()) { products_ = other.products_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProductsIsMutable(); products_.addAll(other.products_); } onChanged(); } } else { if (!other.products_.isEmpty()) { if (productsBuilder_.isEmpty()) { productsBuilder_.dispose(); productsBuilder_ = null; products_ = other.products_; bitField0_ = (bitField0_ & ~0x00000001); productsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getProductsFieldBuilder() : null; } else { productsBuilder_.addAllMessages(other.products_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.vision.v1p4beta1.Product m = input.readMessage( com.google.cloud.vision.v1p4beta1.Product.parser(), extensionRegistry); if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.add(m); } else { productsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.vision.v1p4beta1.Product> products_ = java.util.Collections.emptyList(); private void ensureProductsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { products_ = new java.util.ArrayList<com.google.cloud.vision.v1p4beta1.Product>(products_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vision.v1p4beta1.Product, com.google.cloud.vision.v1p4beta1.Product.Builder, com.google.cloud.vision.v1p4beta1.ProductOrBuilder> productsBuilder_; /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public java.util.List<com.google.cloud.vision.v1p4beta1.Product> getProductsList() { if (productsBuilder_ == null) { return java.util.Collections.unmodifiableList(products_); } else { return productsBuilder_.getMessageList(); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public int getProductsCount() { if (productsBuilder_ == null) { return products_.size(); } else { return productsBuilder_.getCount(); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p4beta1.Product getProducts(int index) { if (productsBuilder_ == null) { return products_.get(index); } else { return productsBuilder_.getMessage(index); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder setProducts(int index, com.google.cloud.vision.v1p4beta1.Product value) { if (productsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProductsIsMutable(); products_.set(index, value); onChanged(); } else { productsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder setProducts( int index, com.google.cloud.vision.v1p4beta1.Product.Builder builderForValue) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.set(index, builderForValue.build()); onChanged(); } else { productsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder addProducts(com.google.cloud.vision.v1p4beta1.Product value) { if (productsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProductsIsMutable(); products_.add(value); onChanged(); } else { productsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder addProducts(int index, com.google.cloud.vision.v1p4beta1.Product value) { if (productsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureProductsIsMutable(); products_.add(index, value); onChanged(); } else { productsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder addProducts(com.google.cloud.vision.v1p4beta1.Product.Builder builderForValue) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.add(builderForValue.build()); onChanged(); } else { productsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder addProducts( int index, com.google.cloud.vision.v1p4beta1.Product.Builder builderForValue) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.add(index, builderForValue.build()); onChanged(); } else { productsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder addAllProducts( java.lang.Iterable<? extends com.google.cloud.vision.v1p4beta1.Product> values) { if (productsBuilder_ == null) { ensureProductsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, products_); onChanged(); } else { productsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder clearProducts() { if (productsBuilder_ == null) { products_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { productsBuilder_.clear(); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public Builder removeProducts(int index) { if (productsBuilder_ == null) { ensureProductsIsMutable(); products_.remove(index); onChanged(); } else { productsBuilder_.remove(index); } return this; } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p4beta1.Product.Builder getProductsBuilder(int index) { return getProductsFieldBuilder().getBuilder(index); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p4beta1.ProductOrBuilder getProductsOrBuilder(int index) { if (productsBuilder_ == null) { return products_.get(index); } else { return productsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public java.util.List<? extends com.google.cloud.vision.v1p4beta1.ProductOrBuilder> getProductsOrBuilderList() { if (productsBuilder_ != null) { return productsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(products_); } } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p4beta1.Product.Builder addProductsBuilder() { return getProductsFieldBuilder() .addBuilder(com.google.cloud.vision.v1p4beta1.Product.getDefaultInstance()); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public com.google.cloud.vision.v1p4beta1.Product.Builder addProductsBuilder(int index) { return getProductsFieldBuilder() .addBuilder(index, com.google.cloud.vision.v1p4beta1.Product.getDefaultInstance()); } /** * * * <pre> * The list of Products. * </pre> * * <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code> */ public java.util.List<com.google.cloud.vision.v1p4beta1.Product.Builder> getProductsBuilderList() { return getProductsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vision.v1p4beta1.Product, com.google.cloud.vision.v1p4beta1.Product.Builder, com.google.cloud.vision.v1p4beta1.ProductOrBuilder> getProductsFieldBuilder() { if (productsBuilder_ == null) { productsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vision.v1p4beta1.Product, com.google.cloud.vision.v1p4beta1.Product.Builder, com.google.cloud.vision.v1p4beta1.ProductOrBuilder>( products_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); products_ = null; } return productsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Token to retrieve the next page of results, or empty if there are no more * results in the list. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) } // @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse) private static final com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse(); } public static com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListProductsInProductSetResponse> PARSER = new com.google.protobuf.AbstractParser<ListProductsInProductSetResponse>() { @java.lang.Override public ListProductsInProductSetResponse 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<ListProductsInProductSetResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListProductsInProductSetResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vision.v1p4beta1.ListProductsInProductSetResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,585
java-container/proto-google-cloud-container-v1beta1/src/main/java/com/google/container/v1beta1/AdvancedMachineFeatures.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/container/v1beta1/cluster_service.proto // Protobuf Java Version: 3.25.8 package com.google.container.v1beta1; /** * * * <pre> * Specifies options for controlling advanced machine features. * </pre> * * Protobuf type {@code google.container.v1beta1.AdvancedMachineFeatures} */ public final class AdvancedMachineFeatures extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.container.v1beta1.AdvancedMachineFeatures) AdvancedMachineFeaturesOrBuilder { private static final long serialVersionUID = 0L; // Use AdvancedMachineFeatures.newBuilder() to construct. private AdvancedMachineFeatures(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AdvancedMachineFeatures() { performanceMonitoringUnit_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new AdvancedMachineFeatures(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_AdvancedMachineFeatures_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_AdvancedMachineFeatures_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.AdvancedMachineFeatures.class, com.google.container.v1beta1.AdvancedMachineFeatures.Builder.class); } /** * * * <pre> * Level of PMU access. * </pre> * * Protobuf enum {@code * google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit} */ public enum PerformanceMonitoringUnit implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * PMU not enabled. * </pre> * * <code>PERFORMANCE_MONITORING_UNIT_UNSPECIFIED = 0;</code> */ PERFORMANCE_MONITORING_UNIT_UNSPECIFIED(0), /** * * * <pre> * Architecturally defined non-LLC events. * </pre> * * <code>ARCHITECTURAL = 1;</code> */ ARCHITECTURAL(1), /** * * * <pre> * Most documented core/L2 events. * </pre> * * <code>STANDARD = 2;</code> */ STANDARD(2), /** * * * <pre> * Most documented core/L2 and LLC events. * </pre> * * <code>ENHANCED = 3;</code> */ ENHANCED(3), UNRECOGNIZED(-1), ; /** * * * <pre> * PMU not enabled. * </pre> * * <code>PERFORMANCE_MONITORING_UNIT_UNSPECIFIED = 0;</code> */ public static final int PERFORMANCE_MONITORING_UNIT_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Architecturally defined non-LLC events. * </pre> * * <code>ARCHITECTURAL = 1;</code> */ public static final int ARCHITECTURAL_VALUE = 1; /** * * * <pre> * Most documented core/L2 events. * </pre> * * <code>STANDARD = 2;</code> */ public static final int STANDARD_VALUE = 2; /** * * * <pre> * Most documented core/L2 and LLC events. * </pre> * * <code>ENHANCED = 3;</code> */ public static final int ENHANCED_VALUE = 3; 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 PerformanceMonitoringUnit 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 PerformanceMonitoringUnit forNumber(int value) { switch (value) { case 0: return PERFORMANCE_MONITORING_UNIT_UNSPECIFIED; case 1: return ARCHITECTURAL; case 2: return STANDARD; case 3: return ENHANCED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<PerformanceMonitoringUnit> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<PerformanceMonitoringUnit> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<PerformanceMonitoringUnit>() { public PerformanceMonitoringUnit findValueByNumber(int number) { return PerformanceMonitoringUnit.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.container.v1beta1.AdvancedMachineFeatures.getDescriptor() .getEnumTypes() .get(0); } private static final PerformanceMonitoringUnit[] VALUES = values(); public static PerformanceMonitoringUnit 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 PerformanceMonitoringUnit(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit) } private int bitField0_; public static final int THREADS_PER_CORE_FIELD_NUMBER = 1; private long threadsPerCore_ = 0L; /** * * * <pre> * The number of threads per physical core. To disable simultaneous * multithreading (SMT) set this to 1. If unset, the maximum number of threads * supported per core by the underlying processor is assumed. * </pre> * * <code>optional int64 threads_per_core = 1;</code> * * @return Whether the threadsPerCore field is set. */ @java.lang.Override public boolean hasThreadsPerCore() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The number of threads per physical core. To disable simultaneous * multithreading (SMT) set this to 1. If unset, the maximum number of threads * supported per core by the underlying processor is assumed. * </pre> * * <code>optional int64 threads_per_core = 1;</code> * * @return The threadsPerCore. */ @java.lang.Override public long getThreadsPerCore() { return threadsPerCore_; } public static final int ENABLE_NESTED_VIRTUALIZATION_FIELD_NUMBER = 2; private boolean enableNestedVirtualization_ = false; /** * * * <pre> * Whether or not to enable nested virtualization (defaults to false). * </pre> * * <code>optional bool enable_nested_virtualization = 2;</code> * * @return Whether the enableNestedVirtualization field is set. */ @java.lang.Override public boolean hasEnableNestedVirtualization() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Whether or not to enable nested virtualization (defaults to false). * </pre> * * <code>optional bool enable_nested_virtualization = 2;</code> * * @return The enableNestedVirtualization. */ @java.lang.Override public boolean getEnableNestedVirtualization() { return enableNestedVirtualization_; } public static final int PERFORMANCE_MONITORING_UNIT_FIELD_NUMBER = 3; private int performanceMonitoringUnit_ = 0; /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return Whether the performanceMonitoringUnit field is set. */ @java.lang.Override public boolean hasPerformanceMonitoringUnit() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return The enum numeric value on the wire for performanceMonitoringUnit. */ @java.lang.Override public int getPerformanceMonitoringUnitValue() { return performanceMonitoringUnit_; } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return The performanceMonitoringUnit. */ @java.lang.Override public com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit getPerformanceMonitoringUnit() { com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit result = com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit.forNumber( performanceMonitoringUnit_); return result == null ? com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit .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 (((bitField0_ & 0x00000001) != 0)) { output.writeInt64(1, threadsPerCore_); } if (((bitField0_ & 0x00000002) != 0)) { output.writeBool(2, enableNestedVirtualization_); } if (((bitField0_ & 0x00000004) != 0)) { output.writeEnum(3, performanceMonitoringUnit_); } 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.computeInt64Size(1, threadsPerCore_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(2, enableNestedVirtualization_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, performanceMonitoringUnit_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.container.v1beta1.AdvancedMachineFeatures)) { return super.equals(obj); } com.google.container.v1beta1.AdvancedMachineFeatures other = (com.google.container.v1beta1.AdvancedMachineFeatures) obj; if (hasThreadsPerCore() != other.hasThreadsPerCore()) return false; if (hasThreadsPerCore()) { if (getThreadsPerCore() != other.getThreadsPerCore()) return false; } if (hasEnableNestedVirtualization() != other.hasEnableNestedVirtualization()) return false; if (hasEnableNestedVirtualization()) { if (getEnableNestedVirtualization() != other.getEnableNestedVirtualization()) return false; } if (hasPerformanceMonitoringUnit() != other.hasPerformanceMonitoringUnit()) return false; if (hasPerformanceMonitoringUnit()) { if (performanceMonitoringUnit_ != other.performanceMonitoringUnit_) 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 (hasThreadsPerCore()) { hash = (37 * hash) + THREADS_PER_CORE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getThreadsPerCore()); } if (hasEnableNestedVirtualization()) { hash = (37 * hash) + ENABLE_NESTED_VIRTUALIZATION_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getEnableNestedVirtualization()); } if (hasPerformanceMonitoringUnit()) { hash = (37 * hash) + PERFORMANCE_MONITORING_UNIT_FIELD_NUMBER; hash = (53 * hash) + performanceMonitoringUnit_; } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.container.v1beta1.AdvancedMachineFeatures parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.container.v1beta1.AdvancedMachineFeatures 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> * Specifies options for controlling advanced machine features. * </pre> * * Protobuf type {@code google.container.v1beta1.AdvancedMachineFeatures} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.container.v1beta1.AdvancedMachineFeatures) com.google.container.v1beta1.AdvancedMachineFeaturesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_AdvancedMachineFeatures_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_AdvancedMachineFeatures_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.container.v1beta1.AdvancedMachineFeatures.class, com.google.container.v1beta1.AdvancedMachineFeatures.Builder.class); } // Construct using com.google.container.v1beta1.AdvancedMachineFeatures.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; threadsPerCore_ = 0L; enableNestedVirtualization_ = false; performanceMonitoringUnit_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.container.v1beta1.ClusterServiceProto .internal_static_google_container_v1beta1_AdvancedMachineFeatures_descriptor; } @java.lang.Override public com.google.container.v1beta1.AdvancedMachineFeatures getDefaultInstanceForType() { return com.google.container.v1beta1.AdvancedMachineFeatures.getDefaultInstance(); } @java.lang.Override public com.google.container.v1beta1.AdvancedMachineFeatures build() { com.google.container.v1beta1.AdvancedMachineFeatures result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.container.v1beta1.AdvancedMachineFeatures buildPartial() { com.google.container.v1beta1.AdvancedMachineFeatures result = new com.google.container.v1beta1.AdvancedMachineFeatures(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.container.v1beta1.AdvancedMachineFeatures result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.threadsPerCore_ = threadsPerCore_; to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000002) != 0)) { result.enableNestedVirtualization_ = enableNestedVirtualization_; to_bitField0_ |= 0x00000002; } if (((from_bitField0_ & 0x00000004) != 0)) { result.performanceMonitoringUnit_ = performanceMonitoringUnit_; to_bitField0_ |= 0x00000004; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.container.v1beta1.AdvancedMachineFeatures) { return mergeFrom((com.google.container.v1beta1.AdvancedMachineFeatures) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.container.v1beta1.AdvancedMachineFeatures other) { if (other == com.google.container.v1beta1.AdvancedMachineFeatures.getDefaultInstance()) return this; if (other.hasThreadsPerCore()) { setThreadsPerCore(other.getThreadsPerCore()); } if (other.hasEnableNestedVirtualization()) { setEnableNestedVirtualization(other.getEnableNestedVirtualization()); } if (other.hasPerformanceMonitoringUnit()) { setPerformanceMonitoringUnit(other.getPerformanceMonitoringUnit()); } 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: { threadsPerCore_ = input.readInt64(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { enableNestedVirtualization_ = input.readBool(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { performanceMonitoringUnit_ = input.readEnum(); 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 long threadsPerCore_; /** * * * <pre> * The number of threads per physical core. To disable simultaneous * multithreading (SMT) set this to 1. If unset, the maximum number of threads * supported per core by the underlying processor is assumed. * </pre> * * <code>optional int64 threads_per_core = 1;</code> * * @return Whether the threadsPerCore field is set. */ @java.lang.Override public boolean hasThreadsPerCore() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * The number of threads per physical core. To disable simultaneous * multithreading (SMT) set this to 1. If unset, the maximum number of threads * supported per core by the underlying processor is assumed. * </pre> * * <code>optional int64 threads_per_core = 1;</code> * * @return The threadsPerCore. */ @java.lang.Override public long getThreadsPerCore() { return threadsPerCore_; } /** * * * <pre> * The number of threads per physical core. To disable simultaneous * multithreading (SMT) set this to 1. If unset, the maximum number of threads * supported per core by the underlying processor is assumed. * </pre> * * <code>optional int64 threads_per_core = 1;</code> * * @param value The threadsPerCore to set. * @return This builder for chaining. */ public Builder setThreadsPerCore(long value) { threadsPerCore_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * The number of threads per physical core. To disable simultaneous * multithreading (SMT) set this to 1. If unset, the maximum number of threads * supported per core by the underlying processor is assumed. * </pre> * * <code>optional int64 threads_per_core = 1;</code> * * @return This builder for chaining. */ public Builder clearThreadsPerCore() { bitField0_ = (bitField0_ & ~0x00000001); threadsPerCore_ = 0L; onChanged(); return this; } private boolean enableNestedVirtualization_; /** * * * <pre> * Whether or not to enable nested virtualization (defaults to false). * </pre> * * <code>optional bool enable_nested_virtualization = 2;</code> * * @return Whether the enableNestedVirtualization field is set. */ @java.lang.Override public boolean hasEnableNestedVirtualization() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Whether or not to enable nested virtualization (defaults to false). * </pre> * * <code>optional bool enable_nested_virtualization = 2;</code> * * @return The enableNestedVirtualization. */ @java.lang.Override public boolean getEnableNestedVirtualization() { return enableNestedVirtualization_; } /** * * * <pre> * Whether or not to enable nested virtualization (defaults to false). * </pre> * * <code>optional bool enable_nested_virtualization = 2;</code> * * @param value The enableNestedVirtualization to set. * @return This builder for chaining. */ public Builder setEnableNestedVirtualization(boolean value) { enableNestedVirtualization_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Whether or not to enable nested virtualization (defaults to false). * </pre> * * <code>optional bool enable_nested_virtualization = 2;</code> * * @return This builder for chaining. */ public Builder clearEnableNestedVirtualization() { bitField0_ = (bitField0_ & ~0x00000002); enableNestedVirtualization_ = false; onChanged(); return this; } private int performanceMonitoringUnit_ = 0; /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return Whether the performanceMonitoringUnit field is set. */ @java.lang.Override public boolean hasPerformanceMonitoringUnit() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return The enum numeric value on the wire for performanceMonitoringUnit. */ @java.lang.Override public int getPerformanceMonitoringUnitValue() { return performanceMonitoringUnit_; } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @param value The enum numeric value on the wire for performanceMonitoringUnit to set. * @return This builder for chaining. */ public Builder setPerformanceMonitoringUnitValue(int value) { performanceMonitoringUnit_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return The performanceMonitoringUnit. */ @java.lang.Override public com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit getPerformanceMonitoringUnit() { com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit result = com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit.forNumber( performanceMonitoringUnit_); return result == null ? com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit .UNRECOGNIZED : result; } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @param value The performanceMonitoringUnit to set. * @return This builder for chaining. */ public Builder setPerformanceMonitoringUnit( com.google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; performanceMonitoringUnit_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Type of Performance Monitoring Unit (PMU) requested on node pool instances. * If unset, PMU will not be available to the node. * </pre> * * <code> * optional .google.container.v1beta1.AdvancedMachineFeatures.PerformanceMonitoringUnit performance_monitoring_unit = 3; * </code> * * @return This builder for chaining. */ public Builder clearPerformanceMonitoringUnit() { bitField0_ = (bitField0_ & ~0x00000004); performanceMonitoringUnit_ = 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.container.v1beta1.AdvancedMachineFeatures) } // @@protoc_insertion_point(class_scope:google.container.v1beta1.AdvancedMachineFeatures) private static final com.google.container.v1beta1.AdvancedMachineFeatures DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.container.v1beta1.AdvancedMachineFeatures(); } public static com.google.container.v1beta1.AdvancedMachineFeatures getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AdvancedMachineFeatures> PARSER = new com.google.protobuf.AbstractParser<AdvancedMachineFeatures>() { @java.lang.Override public AdvancedMachineFeatures 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<AdvancedMachineFeatures> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AdvancedMachineFeatures> getParserForType() { return PARSER; } @java.lang.Override public com.google.container.v1beta1.AdvancedMachineFeatures getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/guava
36,213
guava/src/com/google/common/net/HttpHeaders.java
/* * Copyright (C) 2011 The Guava 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.common.net; import com.google.common.annotations.GwtCompatible; /** * Contains constant definitions for the HTTP header field names. See: * * <ul> * <li><a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> * <li><a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a> * <li><a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616</a> * <li><a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a> * <li><a href="http://www.ietf.org/rfc/rfc5988.txt">RFC 5988</a> * </ul> * * @author Kurt Alfred Kluever * @since 11.0 */ @GwtCompatible public final class HttpHeaders { private HttpHeaders() {} // HTTP Request and Response header fields /** The HTTP {@code Cache-Control} header field name. */ public static final String CACHE_CONTROL = "Cache-Control"; /** The HTTP {@code Content-Length} header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** The HTTP {@code Content-Type} header field name. */ public static final String CONTENT_TYPE = "Content-Type"; /** The HTTP {@code Date} header field name. */ public static final String DATE = "Date"; /** The HTTP {@code Pragma} header field name. */ public static final String PRAGMA = "Pragma"; /** The HTTP {@code Via} header field name. */ public static final String VIA = "Via"; /** The HTTP {@code Warning} header field name. */ public static final String WARNING = "Warning"; // HTTP Request header fields /** The HTTP {@code Accept} header field name. */ public static final String ACCEPT = "Accept"; /** The HTTP {@code Accept-Charset} header field name. */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** The HTTP {@code Accept-Encoding} header field name. */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** The HTTP {@code Accept-Language} header field name. */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** The HTTP {@code Access-Control-Request-Headers} header field name. */ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; /** The HTTP {@code Access-Control-Request-Method} header field name. */ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; /** The HTTP {@code Authorization} header field name. */ public static final String AUTHORIZATION = "Authorization"; /** The HTTP {@code Connection} header field name. */ public static final String CONNECTION = "Connection"; /** The HTTP {@code Cookie} header field name. */ public static final String COOKIE = "Cookie"; /** * The HTTP <a href="https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header">{@code * Cross-Origin-Resource-Policy}</a> header field name. * * @since 28.0 */ public static final String CROSS_ORIGIN_RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc8470">{@code Early-Data}</a> header * field name. * * @since 27.0 */ public static final String EARLY_DATA = "Early-Data"; /** The HTTP {@code Expect} header field name. */ public static final String EXPECT = "Expect"; /** The HTTP {@code From} header field name. */ public static final String FROM = "From"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc7239">{@code Forwarded}</a> header * field name. * * @since 20.0 */ public static final String FORWARDED = "Forwarded"; /** * The HTTP {@code Follow-Only-When-Prerender-Shown} header field name. * * @since 17.0 */ public static final String FOLLOW_ONLY_WHEN_PRERENDER_SHOWN = "Follow-Only-When-Prerender-Shown"; /** The HTTP {@code Host} header field name. */ public static final String HOST = "Host"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc7540#section-3.2.1">{@code * HTTP2-Settings} </a> header field name. * * @since 24.0 */ public static final String HTTP2_SETTINGS = "HTTP2-Settings"; /** The HTTP {@code If-Match} header field name. */ public static final String IF_MATCH = "If-Match"; /** The HTTP {@code If-Modified-Since} header field name. */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** The HTTP {@code If-None-Match} header field name. */ public static final String IF_NONE_MATCH = "If-None-Match"; /** The HTTP {@code If-Range} header field name. */ public static final String IF_RANGE = "If-Range"; /** The HTTP {@code If-Unmodified-Since} header field name. */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** The HTTP {@code Last-Event-ID} header field name. */ public static final String LAST_EVENT_ID = "Last-Event-ID"; /** The HTTP {@code Max-Forwards} header field name. */ public static final String MAX_FORWARDS = "Max-Forwards"; /** The HTTP {@code Origin} header field name. */ public static final String ORIGIN = "Origin"; /** * The HTTP <a href="https://github.com/WICG/origin-isolation">{@code Origin-Isolation}</a> header * field name. * * @since 30.1 */ public static final String ORIGIN_ISOLATION = "Origin-Isolation"; /** The HTTP {@code Proxy-Authorization} header field name. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** The HTTP {@code Range} header field name. */ public static final String RANGE = "Range"; /** The HTTP {@code Referer} header field name. */ public static final String REFERER = "Referer"; /** * The HTTP <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> header * field name. * * @since 23.4 */ public static final String REFERRER_POLICY = "Referrer-Policy"; /** * Values for the <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> * header. * * @since 23.4 */ public static final class ReferrerPolicyValues { private ReferrerPolicyValues() {} public static final String NO_REFERRER = "no-referrer"; public static final String NO_REFFERER_WHEN_DOWNGRADE = "no-referrer-when-downgrade"; public static final String SAME_ORIGIN = "same-origin"; public static final String ORIGIN = "origin"; public static final String STRICT_ORIGIN = "strict-origin"; public static final String ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin"; public static final String STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"; public static final String UNSAFE_URL = "unsafe-url"; } /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER = "Service-Worker"; /** The HTTP {@code TE} header field name. */ public static final String TE = "TE"; /** The HTTP {@code Upgrade} header field name. */ public static final String UPGRADE = "Upgrade"; /** * The HTTP <a href="https://w3c.github.io/webappsec-upgrade-insecure-requests/#preference">{@code * Upgrade-Insecure-Requests}</a> header field name. * * @since 28.1 */ public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; /** The HTTP {@code User-Agent} header field name. */ public static final String USER_AGENT = "User-Agent"; // HTTP Response header fields /** The HTTP {@code Accept-Ranges} header field name. */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** The HTTP {@code Access-Control-Allow-Headers} header field name. */ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; /** The HTTP {@code Access-Control-Allow-Methods} header field name. */ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; /** The HTTP {@code Access-Control-Allow-Origin} header field name. */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; /** * The HTTP <a href="https://wicg.github.io/private-network-access/#headers">{@code * Access-Control-Allow-Private-Network}</a> header field name. * * @since 31.1 */ public static final String ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK = "Access-Control-Allow-Private-Network"; /** The HTTP {@code Access-Control-Allow-Credentials} header field name. */ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; /** The HTTP {@code Access-Control-Expose-Headers} header field name. */ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; /** The HTTP {@code Access-Control-Max-Age} header field name. */ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; /** The HTTP {@code Age} header field name. */ public static final String AGE = "Age"; /** The HTTP {@code Allow} header field name. */ public static final String ALLOW = "Allow"; /** The HTTP {@code Content-Disposition} header field name. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; /** The HTTP {@code Content-Encoding} header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** The HTTP {@code Content-Language} header field name. */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** The HTTP {@code Content-Location} header field name. */ public static final String CONTENT_LOCATION = "Content-Location"; /** The HTTP {@code Content-MD5} header field name. */ public static final String CONTENT_MD5 = "Content-MD5"; /** The HTTP {@code Content-Range} header field name. */ public static final String CONTENT_RANGE = "Content-Range"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-header-field">{@code * Content-Security-Policy}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-report-only-header-field"> * {@code Content-Security-Policy-Report-Only}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-Content-Security-Policy} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Firefox until * version 23 and the Internet Explorer version 10. Please, use {@link #CONTENT_SECURITY_POLICY} * to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY = "X-Content-Security-Policy"; /** * The HTTP nonstandard {@code X-Content-Security-Policy-Report-Only} header field name. It was * introduced in <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the * Firefox until version 23 and the Internet Explorer version 10. Please, use {@link * #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY_REPORT_ONLY = "X-Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-WebKit-CSP} header field name. It was introduced in <a * href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP = "X-WebKit-CSP"; /** * The HTTP nonstandard {@code X-WebKit-CSP-Report-Only} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP_REPORT_ONLY = "X-WebKit-CSP-Report-Only"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP">{@code * Cross-Origin-Embedder-Policy}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP-RO">{@code * Cross-Origin-Embedder-Policy-Report-Only}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY = "Cross-Origin-Embedder-Policy-Report-Only"; /** * The HTTP Cross-Origin-Opener-Policy header field name. * * @since 28.2 */ public static final String CROSS_ORIGIN_OPENER_POLICY = "Cross-Origin-Opener-Policy"; /** The HTTP {@code ETag} header field name. */ public static final String ETAG = "ETag"; /** The HTTP {@code Expires} header field name. */ public static final String EXPIRES = "Expires"; /** The HTTP {@code Last-Modified} header field name. */ public static final String LAST_MODIFIED = "Last-Modified"; /** The HTTP {@code Link} header field name. */ public static final String LINK = "Link"; /** The HTTP {@code Location} header field name. */ public static final String LOCATION = "Location"; /** * The HTTP {@code Keep-Alive} header field name. * * @since 31.0 */ public static final String KEEP_ALIVE = "Keep-Alive"; /** * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/no-vary-search.md">{@code * No-Vary-Seearch}</a> header field name. * * @since 32.0.0 */ public static final String NO_VARY_SEARCH = "No-Vary-Search"; /** * The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code Origin-Trial}</a> * header field name. * * @since 27.1 */ public static final String ORIGIN_TRIAL = "Origin-Trial"; /** The HTTP {@code P3P} header field name. Limited browser support. */ public static final String P3P = "P3P"; /** The HTTP {@code Proxy-Authenticate} header field name. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** The HTTP {@code Refresh} header field name. Non-standard header supported by most browsers. */ public static final String REFRESH = "Refresh"; /** * The HTTP <a href="https://www.w3.org/TR/reporting/">{@code Report-To}</a> header field name. * * @since 27.1 */ public static final String REPORT_TO = "Report-To"; /** The HTTP {@code Retry-After} header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** The HTTP {@code Server} header field name. */ public static final String SERVER = "Server"; /** * The HTTP <a href="https://www.w3.org/TR/server-timing/">{@code Server-Timing}</a> header field * name. * * @since 23.6 */ public static final String SERVER_TIMING = "Server-Timing"; /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker-Allowed}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER_ALLOWED = "Service-Worker-Allowed"; /** The HTTP {@code Set-Cookie} header field name. */ public static final String SET_COOKIE = "Set-Cookie"; /** The HTTP {@code Set-Cookie2} header field name. */ public static final String SET_COOKIE2 = "Set-Cookie2"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap">{@code * SourceMap}</a> header field name. * * @since 27.1 */ public static final String SOURCE_MAP = "SourceMap"; /** * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/opt-in.md">{@code * Supports-Loading-Mode}</a> header field name. This can be used to specify, for example, <a * href="https://developer.chrome.com/docs/privacy-sandbox/fenced-frame/#server-opt-in">fenced * frames</a>. * * @since 32.0.0 */ public static final String SUPPORTS_LOADING_MODE = "Supports-Loading-Mode"; /** * The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">{@code * Strict-Transport-Security}</a> header field name. * * @since 15.0 */ public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; /** * The HTTP <a href="http://www.w3.org/TR/resource-timing/#cross-origin-resources">{@code * Timing-Allow-Origin}</a> header field name. * * @since 15.0 */ public static final String TIMING_ALLOW_ORIGIN = "Timing-Allow-Origin"; /** The HTTP {@code Trailer} header field name. */ public static final String TRAILER = "Trailer"; /** The HTTP {@code Transfer-Encoding} header field name. */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** The HTTP {@code Vary} header field name. */ public static final String VARY = "Vary"; /** The HTTP {@code WWW-Authenticate} header field name. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; // Common, non-standard HTTP header fields /** The HTTP {@code DNT} header field name. */ public static final String DNT = "DNT"; /** The HTTP {@code X-Content-Type-Options} header field name. */ public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-IP}</a> header field name. Header used for VAST requests to provide the IP address of * the device on whose behalf the request is being made. * * @since 31.0 */ public static final String X_DEVICE_IP = "X-Device-IP"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Referer}</a> header field name. Header used for VAST requests to provide the {@link * #REFERER} header value that the on-behalf-of client would have used when making a request * itself. * * @since 31.0 */ public static final String X_DEVICE_REFERER = "X-Device-Referer"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Accept-Language}</a> header field name. Header used for VAST requests to provide the * {@link #ACCEPT_LANGUAGE} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_ACCEPT_LANGUAGE = "X-Device-Accept-Language"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Requested-With}</a> header field name. Header used for VAST requests to provide the * {@link #X_REQUESTED_WITH} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_REQUESTED_WITH = "X-Device-Requested-With"; /** The HTTP {@code X-Do-Not-Track} header field name. */ public static final String X_DO_NOT_TRACK = "X-Do-Not-Track"; /** The HTTP {@code X-Forwarded-For} header field name (superseded by {@code Forwarded}). */ public static final String X_FORWARDED_FOR = "X-Forwarded-For"; /** The HTTP {@code X-Forwarded-Proto} header field name. */ public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host">{@code * X-Forwarded-Host}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; /** * The HTTP <a * href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-port">{@code * X-Forwarded-Port}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_PORT = "X-Forwarded-Port"; /** The HTTP {@code X-Frame-Options} header field name. */ public static final String X_FRAME_OPTIONS = "X-Frame-Options"; /** The HTTP {@code X-Powered-By} header field name. */ public static final String X_POWERED_BY = "X-Powered-By"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS = "Public-Key-Pins"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins-Report-Only}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS_REPORT_ONLY = "Public-Key-Pins-Report-Only"; /** * The HTTP {@code X-Request-ID} header field name. * * @since 30.1 */ public static final String X_REQUEST_ID = "X-Request-ID"; /** The HTTP {@code X-Requested-With} header field name. */ public static final String X_REQUESTED_WITH = "X-Requested-With"; /** The HTTP {@code X-User-IP} header field name. */ public static final String X_USER_IP = "X-User-IP"; /** * The HTTP <a * href="https://learn.microsoft.com/en-us/archive/blogs/ieinternals/internet-explorer-and-custom-http-headers#:~:text=X%2DDownload%2DOptions">{@code * X-Download-Options}</a> header field name. * * <p>When the new X-Download-Options header is present with the value {@code noopen}, the user is * prevented from opening a file download directly; instead, they must first save the file * locally. * * @since 24.1 */ public static final String X_DOWNLOAD_OPTIONS = "X-Download-Options"; /** The HTTP {@code X-XSS-Protection} header field name. */ public static final String X_XSS_PROTECTION = "X-XSS-Protection"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control">{@code * X-DNS-Prefetch-Control}</a> header controls DNS prefetch behavior. Value can be "on" or "off". * By default, DNS prefetching is "on" for HTTP pages and "off" for HTTPS pages. */ public static final String X_DNS_PREFETCH_CONTROL = "X-DNS-Prefetch-Control"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-From}</a> header field name. * * @since 19.0 */ public static final String PING_FROM = "Ping-From"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-To}</a> header field name. * * @since 19.0 */ public static final String PING_TO = "Ping-To"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * Purpose}</a> header field name. * * @since 28.0 */ public static final String PURPOSE = "Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Purpose}</a> header field name. * * @since 28.0 */ public static final String X_PURPOSE = "X-Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Moz}</a> header field name. * * @since 28.0 */ public static final String X_MOZ = "X-Moz"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Device-Memory">{@code * Device-Memory}</a> header field name. * * @since 31.0 */ public static final String DEVICE_MEMORY = "Device-Memory"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Downlink">{@code * Downlink}</a> header field name. * * @since 31.0 */ public static final String DOWNLINK = "Downlink"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ECT">{@code * ECT}</a> header field name. * * @since 31.0 */ public static final String ECT = "ECT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/RTT">{@code * RTT}</a> header field name. * * @since 31.0 */ public static final String RTT = "RTT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data">{@code * Save-Data}</a> header field name. * * @since 31.0 */ public static final String SAVE_DATA = "Save-Data"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Viewport-Width">{@code * Viewport-Width}</a> header field name. * * @since 31.0 */ public static final String VIEWPORT_WIDTH = "Viewport-Width"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Width">{@code * Width}</a> header field name. * * @since 31.0 */ public static final String WIDTH = "Width"; /** * The HTTP <a href="https://www.w3.org/TR/permissions-policy-1/">{@code Permissions-Policy}</a> * header field name. * * @since 31.0 */ public static final String PERMISSIONS_POLICY = "Permissions-Policy"; /** * The HTTP <a * href="https://w3c.github.io/webappsec-permissions-policy/#permissions-policy-report-only-http-header-field">{@code * Permissions-Policy-Report-Only}</a> header field name. * * @since 33.2.0 */ public static final String PERMISSIONS_POLICY_REPORT_ONLY = "Permissions-Policy-Report-Only"; /** * The HTTP <a * href="https://wicg.github.io/user-preference-media-features-headers/#sec-ch-prefers-color-scheme">{@code * Sec-CH-Prefers-Color-Scheme}</a> header field name. * * <p>This header is experimental. * * @since 31.0 */ public static final String SEC_CH_PREFERS_COLOR_SCHEME = "Sec-CH-Prefers-Color-Scheme"; /** * The HTTP <a * href="https://www.rfc-editor.org/rfc/rfc8942#name-the-accept-ch-response-head">{@code * Accept-CH}</a> header field name. * * @since 31.0 */ public static final String ACCEPT_CH = "Accept-CH"; /** * The HTTP <a * href="https://datatracker.ietf.org/doc/html/draft-davidben-http-client-hint-reliability-03.txt#section-3">{@code * Critical-CH}</a> header field name. * * @since 31.0 */ public static final String CRITICAL_CH = "Critical-CH"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua">{@code Sec-CH-UA}</a> * header field name. * * @since 30.0 */ public static final String SEC_CH_UA = "Sec-CH-UA"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-arch">{@code * Sec-CH-UA-Arch}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_ARCH = "Sec-CH-UA-Arch"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-model">{@code * Sec-CH-UA-Model}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MODEL = "Sec-CH-UA-Model"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform">{@code * Sec-CH-UA-Platform}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM = "Sec-CH-UA-Platform"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform-version">{@code * Sec-CH-UA-Platform-Version}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM_VERSION = "Sec-CH-UA-Platform-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @deprecated Prefer {@link SEC_CH_UA_FULL_VERSION_LIST}. * @since 30.0 */ @Deprecated public static final String SEC_CH_UA_FULL_VERSION = "Sec-CH-UA-Full-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version-list">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @since 31.1 */ public static final String SEC_CH_UA_FULL_VERSION_LIST = "Sec-CH-UA-Full-Version-List"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-mobile">{@code * Sec-CH-UA-Mobile}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MOBILE = "Sec-CH-UA-Mobile"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-wow64">{@code * Sec-CH-UA-WoW64}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_UA_WOW64 = "Sec-CH-UA-WoW64"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness">{@code * Sec-CH-UA-Bitness}</a> header field name. * * @since 31.0 */ public static final String SEC_CH_UA_BITNESS = "Sec-CH-UA-Bitness"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factor">{@code * Sec-CH-UA-Form-Factor}</a> header field name. * * @deprecated Prefer {@link SEC_CH_UA_FORM_FACTORS}. * @since 32.0.0 */ @Deprecated public static final String SEC_CH_UA_FORM_FACTOR = "Sec-CH-UA-Form-Factor"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factors">{@code * Sec-CH-UA-Form-Factors}</a> header field name. * * @since 33.3.0 */ public static final String SEC_CH_UA_FORM_FACTORS = "Sec-CH-UA-Form-Factors"; /** * The HTTP <a * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-width">{@code * Sec-CH-Viewport-Width}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_VIEWPORT_WIDTH = "Sec-CH-Viewport-Width"; /** * The HTTP <a * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-height">{@code * Sec-CH-Viewport-Height}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_VIEWPORT_HEIGHT = "Sec-CH-Viewport-Height"; /** * The HTTP <a href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-dpr">{@code * Sec-CH-DPR}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_DPR = "Sec-CH-DPR"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Dest}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_DEST = "Sec-Fetch-Dest"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Mode}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_MODE = "Sec-Fetch-Mode"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Site}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_SITE = "Sec-Fetch-Site"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-User}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_USER = "Sec-Fetch-User"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Metadata}</a> * header field name. * * @since 26.0 */ public static final String SEC_METADATA = "Sec-Metadata"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/draft-ietf-tokbind-https">{@code * Sec-Token-Binding}</a> header field name. * * @since 25.1 */ public static final String SEC_TOKEN_BINDING = "Sec-Token-Binding"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/draft-ietf-tokbind-ttrp">{@code * Sec-Provided-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_PROVIDED_TOKEN_BINDING_ID = "Sec-Provided-Token-Binding-ID"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/draft-ietf-tokbind-ttrp">{@code * Sec-Referred-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_REFERRED_TOKEN_BINDING_ID = "Sec-Referred-Token-Binding-ID"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Accept}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_ACCEPT = "Sec-WebSocket-Accept"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Extensions}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_EXTENSIONS = "Sec-WebSocket-Extensions"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code Sec-WebSocket-Key}</a> * header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_KEY = "Sec-WebSocket-Key"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Protocol}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Version}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version"; /** * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code * Sec-Browsing-Topics}</a> header field name. * * @since 32.0.0 */ public static final String SEC_BROWSING_TOPICS = "Sec-Browsing-Topics"; /** * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code * Observe-Browsing-Topics}</a> header field name. * * @since 32.0.0 */ public static final String OBSERVE_BROWSING_TOPICS = "Observe-Browsing-Topics"; /** * The HTTP <a * href="https://wicg.github.io/turtledove/#handling-direct-from-seller-signals">{@code * Sec-Ad-Auction-Fetch}</a> header field name. * * @since 33.0.0 */ public static final String SEC_AD_AUCTION_FETCH = "Sec-Ad-Auction-Fetch"; /** * The HTTP <a * href="https://privacycg.github.io/gpc-spec/#the-sec-gpc-header-field-for-http-requests">{@code * Sec-GPC}</a> header field name. * * @since 33.2.0 */ public static final String SEC_GPC = "Sec-GPC"; /** * The HTTP <a * href="https://wicg.github.io/turtledove/#handling-direct-from-seller-signals">{@code * Ad-Auction-Signals}</a> header field name. * * @since 33.0.0 */ public static final String AD_AUCTION_SIGNALS = "Ad-Auction-Signals"; /** * The HTTP <a href="https://wicg.github.io/turtledove/#http-headerdef-ad-auction-allowed">{@code * Ad-Auction-Allowed}</a> header field name. * * @since 33.2.0 */ public static final String AD_AUCTION_ALLOWED = "Ad-Auction-Allowed"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc8586">{@code CDN-Loop}</a> header * field name. * * @since 28.0 */ public static final String CDN_LOOP = "CDN-Loop"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc7838#page-8">{@code Alt-Svc}</a> * header field name. * * @since 33.4.0 */ public static final String ALT_SVC = "Alt-Svc"; }
apache/juneau
34,985
juneau-utest/src/test/java/org/apache/juneau/httppart/HttpPartSchema_Response_Test.java
// *************************************************************************************************************************** // * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * // * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * // * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * // * with the License. You may obtain a copy of the License at * // * * // * http://www.apache.org/licenses/LICENSE-2.0 * // * * // * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * // * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * // * specific language governing permissions and limitations under the License. * // *************************************************************************************************************************** package org.apache.juneau.httppart; import static org.apache.juneau.TestUtils.*; import static org.junit.jupiter.api.Assertions.*; import java.util.*; import org.apache.juneau.*; import org.apache.juneau.annotation.*; import org.apache.juneau.http.annotation.*; import org.junit.jupiter.api.*; class HttpPartSchema_Response_Test extends TestBase { //----------------------------------------------------------------------------------------------------------------- // Basic test //----------------------------------------------------------------------------------------------------------------- @Test void a01_basic() { assertDoesNotThrow(()->HttpPartSchema.create().build()); } //----------------------------------------------------------------------------------------------------------------- // @Response //----------------------------------------------------------------------------------------------------------------- @Response( schema=@Schema( t="number", f="int32", max="1", min="2", mo="3", p="4", maxl=1, minl=2, maxi=3, mini=4, maxp=5, minp=6, emax=true, emin=true, ui=true, df={"c1","c2"}, e="e1,e2", items=@Items( t="integer", f="int64", cf="ssv", max="5", min="6", mo="7", p="8", maxl=5, minl=6, maxi=7, mini=8, emax=false, emin=false, ui=false, df={"c3","c4"}, e="e3,e4", items=@SubItems( t="string", f="float", cf="tsv", max="9", min="10", mo="11", p="12", maxl=9, minl=10, maxi=11, mini=12, emax=true, emin=true, ui=true, df={"c5","c6"}, e="e5,e6", items={ "type:'array',", "format:'double',", "collectionFormat:'pipes',", "maximum:'13',", "minimum:'14',", "multipleOf:'15',", "pattern:'16',", "maxLength:13,", "minLength:14,", "maxItems:15,", "minItems:16,", "exclusiveMaximum:false,", "exclusiveMinimum:false,", "uniqueItems:false,", "default:'c7\\nc8',", "enum:['e7','e8']", } ) ) ) ) public static class A05 {} @Test void a05_basic_nestedItems_onClass() { var s = HttpPartSchema.create().apply(Response.class, A05.class).noValidate().build(); assertBean( s, "type,format,maximum,minimum,multipleOf,pattern,maxLength,minLength,maxItems,minItems,maxProperties,minProperties,exclusiveMaximum,exclusiveMinimum,uniqueItems,enum,default", "NUMBER,INT32,1,2,3,4,1,2,3,4,5,6,true,true,true,[e1,e2],c1\nc2" ); var items = s.getItems(); assertBean( items, "type,format,collectionFormat,maximum,minimum,multipleOf,pattern,maxLength,minLength,maxItems,minItems,exclusiveMaximum,exclusiveMinimum,uniqueItems,enum,default", "INTEGER,INT64,SSV,5,6,7,8,5,6,7,8,false,false,false,[e3,e4],c3\nc4" ); items = items.getItems(); assertBean( items, "type,format,collectionFormat,maximum,minimum,multipleOf,pattern,maxLength,minLength,maxItems,minItems,exclusiveMaximum,exclusiveMinimum,uniqueItems,enum,default", "STRING,FLOAT,TSV,9,10,11,12,9,10,11,12,true,true,true,[e5,e6],c5\nc6" ); items = items.getItems(); assertBean( items, "type,format,collectionFormat,maximum,minimum,multipleOf,pattern,maxLength,minLength,maxItems,minItems,exclusiveMaximum,exclusiveMinimum,uniqueItems,enum,default", "ARRAY,DOUBLE,PIPES,13,14,15,16,13,14,15,16,false,false,false,[e7,e8],c7\nc8" ); } //----------------------------------------------------------------------------------------------------------------- // String input validations. //----------------------------------------------------------------------------------------------------------------- @Response( schema=@Schema( p="x.*", aev=true ) ) public static class B02a {} @Test void b02a_pattern() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B02a.class).build(); s.validateInput("x"); s.validateInput("xx"); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match expected pattern. Must match pattern: x.*", ()->s.validateInput("")); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match expected pattern. Must match pattern: x.*", ()->s.validateInput("y")); } @Response( schema=@Schema( items=@Items( p="w.*", items=@SubItems( p="x.*", items={ "pattern:'y.*',", "items:{pattern:'z.*'}" } ) ) ) ) public static class B02b {} @Response( schema=@Schema( minl=2, maxl=3 ) ) public static class B03a {} @Test void b03a_length() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B03a.class).build(); s.validateInput("12"); s.validateInput("123"); s.validateInput(null); assertThrowsWithMessage(SchemaValidationException.class, "Minimum length of value not met.", ()->s.validateInput("1")); assertThrowsWithMessage(SchemaValidationException.class, "Maximum length of value exceeded.", ()->s.validateInput("1234")); } @Response( schema=@Schema( items=@Items( minl=2, maxl=3, items=@SubItems( minl=3, maxl=4, items={ "minLength:4,maxLength:5,", "items:{minLength:5,maxLength:6}" } ) ) ) ) public static class B03b {} @Test void b03b_length_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B03b.class).build(); s.getItems().validateInput("12"); s.getItems().getItems().validateInput("123"); s.getItems().getItems().getItems().validateInput("1234"); s.getItems().getItems().getItems().getItems().validateInput("12345"); s.getItems().validateInput("123"); s.getItems().getItems().validateInput("1234"); s.getItems().getItems().getItems().validateInput("12345"); s.getItems().getItems().getItems().getItems().validateInput("123456"); s.getItems().validateInput(null); s.getItems().getItems().validateInput(null); s.getItems().getItems().getItems().validateInput(null); s.getItems().getItems().getItems().getItems().validateInput(null); assertThrowsWithMessage(SchemaValidationException.class, "Minimum length of value not met.", ()->s.getItems().validateInput("1")); assertThrowsWithMessage(SchemaValidationException.class, "Minimum length of value not met.", ()->s.getItems().getItems().validateInput("12")); assertThrowsWithMessage(SchemaValidationException.class, "Minimum length of value not met.", ()->s.getItems().getItems().getItems().validateInput("123")); assertThrowsWithMessage(SchemaValidationException.class, "Minimum length of value not met.", ()->s.getItems().getItems().getItems().getItems().validateInput("1234")); assertThrowsWithMessage(SchemaValidationException.class, "Maximum length of value exceeded.", ()->s.getItems().validateInput("1234")); assertThrowsWithMessage(SchemaValidationException.class, "Maximum length of value exceeded.", ()->s.getItems().getItems().validateInput("12345")); assertThrowsWithMessage(SchemaValidationException.class, "Maximum length of value exceeded.", ()->s.getItems().getItems().getItems().validateInput("123456")); assertThrowsWithMessage(SchemaValidationException.class, "Maximum length of value exceeded.", ()->s.getItems().getItems().getItems().getItems().validateInput("1234567")); } @Response(schema=@Schema(e="X,Y")) public static class B04a {} @Test void b04a_enum() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B04a.class).build(); s.validateInput("X"); s.validateInput("Y"); s.validateInput(null); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: X, Y", ()->s.validateInput("Z")); } @Response(schema=@Schema(e=" X , Y ")) public static class B04b {} @Test void b04b_enum() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B04b.class).build(); s.validateInput("X"); s.validateInput("Y"); s.validateInput(null); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: X, Y", ()->s.validateInput("Z")); } @Response(schema=@Schema(e="X,Y")) public static class B04c {} @Test void b04c_enum_json() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B04c.class).build(); s.validateInput("X"); s.validateInput("Y"); s.validateInput(null); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: X, Y", ()->s.validateInput("Z")); } @Response( schema=@Schema( items=@Items( e="W", items=@SubItems( e="X", items={ "enum:['Y'],", "items:{enum:['Z']}" } ) ) ) ) public static class B04d {} @Test void b04d_enum_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, B04d.class).build(); s.getItems().validateInput("W"); s.getItems().getItems().validateInput("X"); s.getItems().getItems().getItems().validateInput("Y"); s.getItems().getItems().getItems().getItems().validateInput("Z"); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: W", ()->s.getItems().validateInput("V")); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: X", ()->s.getItems().getItems().validateInput("V")); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: Y", ()->s.getItems().getItems().getItems().validateInput("V")); assertThrowsWithMessage(SchemaValidationException.class, "Value does not match one of the expected values. Must be one of the following: Z", ()->s.getItems().getItems().getItems().getItems().validateInput("V")); } //----------------------------------------------------------------------------------------------------------------- // Numeric validations //----------------------------------------------------------------------------------------------------------------- @Response(schema=@Schema(min="10", max="100")) public static class C01a {} @Test void c01a_minmax_ints() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C01a.class).build(); s.validateOutput(10, BeanContext.DEFAULT); s.validateOutput(100, BeanContext.DEFAULT); s.validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.validateOutput(9, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.validateOutput(101, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( min="10", max="100", items=@SubItems( min="100", max="1000", items={ "minimum:1000,maximum:10000,", "items:{minimum:10000,maximum:100000}" } ) ) ) ) public static class C01b {} @Test void c01b_minmax_ints_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C01b.class).build(); s.getItems().validateOutput(10, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(100, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1000, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10000, BeanContext.DEFAULT); s.getItems().validateOutput(100, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(1000, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(10000, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(100000, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().validateOutput(9, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().validateOutput(99, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().validateOutput(999, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(9999, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().validateOutput(101, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().validateOutput(1001, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().validateOutput(10001, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().getItems().validateOutput(100001, BeanContext.DEFAULT)); } @Response(schema=@Schema(min="10", max="100", emin=true, emax=true)) public static class C02a {} @Test void c02a_minmax_exclusive() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C02a.class).build(); s.validateOutput(11, BeanContext.DEFAULT); s.validateOutput(99, BeanContext.DEFAULT); s.validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.validateOutput(10, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.validateOutput(100, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( min="10", max="100", emin=true, emax=true, items=@SubItems( min="100", max="1000", emin=true, emax=true, items={ "minimum:1000,maximum:10000,exclusiveMinimum:true,exclusiveMaximum:true,", "items:{minimum:10000,maximum:100000,exclusiveMinimum:true,exclusiveMaximum:true}" } ) ) ) ) public static class C02b {} @Test void c02b_minmax_exclusive_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C02b.class).build(); s.getItems().validateOutput(11, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(101, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1001, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10001, BeanContext.DEFAULT); s.getItems().validateOutput(99, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(999, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(9999, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(99999, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().validateOutput(10, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().validateOutput(100, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().validateOutput(1000, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(10000, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().validateOutput(100, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().validateOutput(1000, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().validateOutput(10000, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().getItems().validateOutput(100000, BeanContext.DEFAULT)); } @Response(schema=@Schema(min="10.1", max="100.1")) public static class C03a {} @Test void c03_minmax_floats() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C03a.class).build(); s.validateOutput(10.1f, BeanContext.DEFAULT); s.validateOutput(100.1f, BeanContext.DEFAULT); s.validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.validateOutput(10f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.validateOutput(100.2f, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( min="10.1", max="100.1", items=@SubItems( min="100.1", max="1000.1", items={ "minimum:1000.1,maximum:10000.1,", "items:{minimum:10000.1,maximum:100000.1}" } ) ) ) ) public static class C03b {} @Test void c03b_minmax_floats_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C03b.class).build(); s.getItems().validateOutput(10.1f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(100.1f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1000.1f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10000.1f, BeanContext.DEFAULT); s.getItems().validateOutput(100.1f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(1000.1f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(10000.1f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(100000.1f, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().validateOutput(10f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().validateOutput(100f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().validateOutput(1000f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(10000f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().validateOutput(100.2f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().validateOutput(1000.2f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().validateOutput(10000.2f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().getItems().validateOutput(100000.2f, BeanContext.DEFAULT)); } @Response(schema=@Schema(min="10.1", max="100.1", emin=true, emax=true)) public static class C04a {} @Test void c04a_minmax_floats_exclusive() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C04a.class).build(); s.validateOutput(10.2f, BeanContext.DEFAULT); s.validateOutput(100f, BeanContext.DEFAULT); s.validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.validateOutput(10.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.validateOutput(100.1f, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( min="10.1", max="100.1", emin=true, emax=true, items=@SubItems( min="100.1", max="1000.1", emin=true, emax=true, items={ "minimum:1000.1,maximum:10000.1,exclusiveMinimum:true,exclusiveMaximum:true,", "items:{minimum:10000.1,maximum:100000.1,exclusiveMinimum:true,exclusiveMaximum:true}" } ) ) ) ) public static class C04b {} @Test void c04b_minmax_floats_exclusive_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C04b.class).build(); s.getItems().validateOutput(10.2f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(100.2f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1000.2f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10000.2f, BeanContext.DEFAULT); s.getItems().validateOutput(100f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(1000f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(10000f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(100000f, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().validateOutput(10.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().validateOutput(100.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().validateOutput(1000.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum value not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(10000.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().validateOutput(100.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().validateOutput(1000.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().validateOutput(10000.1f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum value exceeded.", ()->s.getItems().getItems().getItems().getItems().validateOutput(100000.1f, BeanContext.DEFAULT)); } @Response(schema=@Schema(mo="10")) public static class C05a {} @Test void c05a_multipleOf() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C05a.class).build(); s.validateOutput(0, BeanContext.DEFAULT); s.validateOutput(10, BeanContext.DEFAULT); s.validateOutput(20, BeanContext.DEFAULT); s.validateOutput(10f, BeanContext.DEFAULT); s.validateOutput(20f, BeanContext.DEFAULT); s.validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.validateOutput(11, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( mo="10", items=@SubItems( mo="100", items={ "multipleOf:1000,", "items:{multipleOf:10000}" } ) ) ) ) public static class C05b {} @Test void c05b_multipleOf_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C05b.class).build(); s.getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().validateOutput(10, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(100, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1000, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10000, BeanContext.DEFAULT); s.getItems().validateOutput(20, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(200, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(2000, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(20000, BeanContext.DEFAULT); s.getItems().validateOutput(10f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(100f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1000f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10000f, BeanContext.DEFAULT); s.getItems().validateOutput(20f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(200f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(2000f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(20000f, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().validateOutput(11, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().getItems().validateOutput(101, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().getItems().getItems().validateOutput(1001, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(10001, BeanContext.DEFAULT)); } @Response(schema=@Schema(mo="10.1")) public static class C06a {} @Test void c06a_multipleOf_floats() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C06a.class).build(); s.validateOutput(0, BeanContext.DEFAULT); s.validateOutput(10.1f, BeanContext.DEFAULT); s.validateOutput(20.2f, BeanContext.DEFAULT); s.validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.validateOutput(10.2f, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( mo="10.1", items=@SubItems( mo="100.1", items={ "multipleOf:1000.1,", "items:{multipleOf:10000.1}" } ) ) ) ) public static class C06b {} @Test void c06b_multipleOf_floats_items() throws Exception { var s = HttpPartSchema.create().apply(Response.class, C06b.class).build(); s.getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(0, BeanContext.DEFAULT); s.getItems().validateOutput(10.1f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(100.1f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(1000.1f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(10000.1f, BeanContext.DEFAULT); s.getItems().validateOutput(20.2f, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(200.2f, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(2000.2f, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(20000.2f, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().validateOutput(10.2f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().getItems().validateOutput(100.2f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().getItems().getItems().validateOutput(1000.2f, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Multiple-of not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(10000.2f, BeanContext.DEFAULT)); } //----------------------------------------------------------------------------------------------------------------- // Collections/Array validations //----------------------------------------------------------------------------------------------------------------- @Response( schema=@Schema( items=@Items( ui=true, items=@SubItems( ui=true, items={ "uniqueItems:true,", "items:{uniqueItems:true}" } ) ) ) ) public static class D01 {} @Test void d01a_uniqueItems_arrays() throws Exception { var s = HttpPartSchema.create().apply(Response.class, D01.class).build(); var good = split("a,b"); var bad = split("a,a"); s.getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().validateOutput(bad, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().getItems().validateOutput(bad, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().getItems().getItems().validateOutput(bad, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().getItems().getItems().getItems().validateOutput(bad, BeanContext.DEFAULT)); } @Test void d01b_uniqueItems_collections() throws Exception { var s = HttpPartSchema.create().apply(Response.class, D01.class).build(); List<String> good = alist("a","b"), bad = alist("a","a"); s.getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(good, BeanContext.DEFAULT); s.getItems().validateOutput(null, BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().validateOutput(bad, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().getItems().validateOutput(bad, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().getItems().getItems().validateOutput(bad, BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Duplicate items not allowed.", ()->s.getItems().getItems().getItems().getItems().validateOutput(bad, BeanContext.DEFAULT)); } @Response( schema=@Schema( items=@Items( mini=1, maxi=2, items=@SubItems( mini=2, maxi=3, items={ "minItems:3,maxItems:4,", "items:{minItems:4,maxItems:5}" } ) ) ) ) public static class D02 {} @Test void d02a_minMaxItems_arrays() throws Exception { var s = HttpPartSchema.create().apply(Response.class, D02.class).build(); s.getItems().validateOutput(split("1"), BeanContext.DEFAULT); s.getItems().getItems().validateOutput(split("1,2"), BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(split("1,2,3"), BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(split("1,2,3,4"), BeanContext.DEFAULT); s.getItems().validateOutput(split("1,2"), BeanContext.DEFAULT); s.getItems().getItems().validateOutput(split("1,2,3"), BeanContext.DEFAULT); s.getItems().getItems().getItems().validateOutput(split("1,2,3,4"), BeanContext.DEFAULT); s.getItems().getItems().getItems().getItems().validateOutput(split("1,2,3,4,5"), BeanContext.DEFAULT); assertThrowsWithMessage(SchemaValidationException.class, "Minimum number of items not met.", ()->s.getItems().validateOutput(new String[0], BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum number of items not met.", ()->s.getItems().getItems().validateOutput(split("1"), BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum number of items not met.", ()->s.getItems().getItems().getItems().validateOutput(split("1,2"), BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Minimum number of items not met.", ()->s.getItems().getItems().getItems().getItems().validateOutput(split("1,2,3"), BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum number of items exceeded.", ()->s.getItems().validateOutput(split("1,2,3"), BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum number of items exceeded.", ()->s.getItems().getItems().validateOutput(split("1,2,3,4"), BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum number of items exceeded.", ()->s.getItems().getItems().getItems().validateOutput(split("1,2,3,4,5"), BeanContext.DEFAULT)); assertThrowsWithMessage(SchemaValidationException.class, "Maximum number of items exceeded.", ()->s.getItems().getItems().getItems().getItems().validateOutput(split("1,2,3,4,5,6"), BeanContext.DEFAULT)); } }
google/guava
36,805
guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
/* * Copyright (C) 2011 The Guava 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.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.j2objc.annotations.Weak; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import org.jspecify.annotations.Nullable; /** * The {@code CycleDetectingLockFactory} creates {@link ReentrantLock} instances and {@link * ReentrantReadWriteLock} instances that detect potential deadlock by checking for cycles in lock * acquisition order. * * <p>Potential deadlocks detected when calling the {@code lock()}, {@code lockInterruptibly()}, or * {@code tryLock()} methods will result in the execution of the {@link Policy} specified when * creating the factory. The currently available policies are: * * <ul> * <li>DISABLED * <li>WARN * <li>THROW * </ul> * * <p>The locks created by a factory instance will detect lock acquisition cycles with locks created * by other {@code CycleDetectingLockFactory} instances (except those with {@code Policy.DISABLED}). * A lock's behavior when a cycle is detected, however, is defined by the {@code Policy} of the * factory that created it. This allows detection of cycles across components while delegating * control over lock behavior to individual components. * * <p>Applications are encouraged to use a {@code CycleDetectingLockFactory} to create any locks for * which external/unmanaged code is executed while the lock is held. (See caveats under * <strong>Performance</strong>). * * <p><strong>Cycle Detection</strong> * * <p>Deadlocks can arise when locks are acquired in an order that forms a cycle. In a simple * example involving two locks and two threads, deadlock occurs when one thread acquires Lock A, and * then Lock B, while another thread acquires Lock B, and then Lock A: * * <pre> * Thread1: acquire(LockA) --X acquire(LockB) * Thread2: acquire(LockB) --X acquire(LockA) * </pre> * * <p>Neither thread will progress because each is waiting for the other. In more complex * applications, cycles can arise from interactions among more than 2 locks: * * <pre> * Thread1: acquire(LockA) --X acquire(LockB) * Thread2: acquire(LockB) --X acquire(LockC) * ... * ThreadN: acquire(LockN) --X acquire(LockA) * </pre> * * <p>The implementation detects cycles by constructing a directed graph in which each lock * represents a node and each edge represents an acquisition ordering between two locks. * * <ul> * <li>Each lock adds (and removes) itself to/from a ThreadLocal Set of acquired locks when the * Thread acquires its first hold (and releases its last remaining hold). * <li>Before the lock is acquired, the lock is checked against the current set of acquired * locks---to each of the acquired locks, an edge from the soon-to-be-acquired lock is either * verified or created. * <li>If a new edge needs to be created, the outgoing edges of the acquired locks are traversed * to check for a cycle that reaches the lock to be acquired. If no cycle is detected, a new * "safe" edge is created. * <li>If a cycle is detected, an "unsafe" (cyclic) edge is created to represent a potential * deadlock situation, and the appropriate Policy is executed. * </ul> * * <p>Note that detection of potential deadlock does not necessarily indicate that deadlock will * happen, as it is possible that higher level application logic prevents the cyclic lock * acquisition from occurring. One example of a false positive is: * * <pre> * LockA -&gt; LockB -&gt; LockC * LockA -&gt; LockC -&gt; LockB * </pre> * * <p><strong>ReadWriteLocks</strong> * * <p>While {@code ReadWriteLock} instances have different properties and can form cycles without * potential deadlock, this class treats {@code ReadWriteLock} instances as equivalent to * traditional exclusive locks. Although this increases the false positives that the locks detect * (i.e. cycles that will not actually result in deadlock), it simplifies the algorithm and * implementation considerably. The assumption is that a user of this factory wishes to eliminate * any cyclic acquisition ordering. * * <p><strong>Explicit Lock Acquisition Ordering</strong> * * <p>The {@link CycleDetectingLockFactory.WithExplicitOrdering} class can be used to enforce an * application-specific ordering in addition to performing general cycle detection. * * <p><strong>Garbage Collection</strong> * * <p>In order to allow proper garbage collection of unused locks, the edges of the lock graph are * weak references. * * <p><strong>Performance</strong> * * <p>The extra bookkeeping done by cycle detecting locks comes at some cost to performance. * Benchmarks (as of December 2011) show that: * * <ul> * <li>for an unnested {@code lock()} and {@code unlock()}, a cycle detecting lock takes 38ns as * opposed to the 24ns taken by a plain lock. * <li>for nested locking, the cost increases with the depth of the nesting: * <ul> * <li>2 levels: average of 64ns per lock()/unlock() * <li>3 levels: average of 77ns per lock()/unlock() * <li>4 levels: average of 99ns per lock()/unlock() * <li>5 levels: average of 103ns per lock()/unlock() * <li>10 levels: average of 184ns per lock()/unlock() * <li>20 levels: average of 393ns per lock()/unlock() * </ul> * </ul> * * <p>As such, the CycleDetectingLockFactory may not be suitable for performance-critical * applications which involve tightly-looped or deeply-nested locking algorithms. * * @author Darick Tong * @since 13.0 */ @J2ktIncompatible @GwtIncompatible public class CycleDetectingLockFactory { /** * Encapsulates the action to be taken when a potential deadlock is encountered. Clients can use * one of the predefined {@link Policies} or specify a custom implementation. Implementations must * be thread-safe. * * @since 13.0 */ public interface Policy { /** * Called when a potential deadlock is encountered. Implementations can throw the given {@code * exception} and/or execute other desired logic. * * <p>Note that the method will be called even upon an invocation of {@code tryLock()}. Although * {@code tryLock()} technically recovers from deadlock by eventually timing out, this behavior * is chosen based on the assumption that it is the application's wish to prohibit any cyclical * lock acquisitions. */ void handlePotentialDeadlock(PotentialDeadlockException exception); } /** * Pre-defined {@link Policy} implementations. * * @since 13.0 */ public enum Policies implements Policy { /** * When potential deadlock is detected, this policy results in the throwing of the {@code * PotentialDeadlockException} indicating the potential deadlock, which includes stack traces * illustrating the cycle in lock acquisition order. */ THROW { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { throw e; } }, /** * When potential deadlock is detected, this policy results in the logging of a {@link * Level#SEVERE} message indicating the potential deadlock, which includes stack traces * illustrating the cycle in lock acquisition order. */ WARN { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { logger.get().log(Level.SEVERE, "Detected potential deadlock", e); } }, /** * Disables cycle detection. This option causes the factory to return unmodified lock * implementations provided by the JDK, and is provided to allow applications to easily * parameterize when cycle detection is enabled. * * <p>Note that locks created by a factory with this policy will <em>not</em> participate the * cycle detection performed by locks created by other factories. */ DISABLED { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) {} }; } /** Creates a new factory with the specified policy. */ public static CycleDetectingLockFactory newInstance(Policy policy) { return new CycleDetectingLockFactory(policy); } /** Equivalent to {@code newReentrantLock(lockName, false)}. */ public ReentrantLock newReentrantLock(String lockName) { return newReentrantLock(lockName, false); } /** * Creates a {@link ReentrantLock} with the given fairness policy. The {@code lockName} is used in * the warning or exception output to help identify the locks involved in the detected deadlock. */ public ReentrantLock newReentrantLock(String lockName, boolean fair) { return policy == Policies.DISABLED ? new ReentrantLock(fair) : new CycleDetectingReentrantLock(new LockGraphNode(lockName), fair); } /** Equivalent to {@code newReentrantReadWriteLock(lockName, false)}. */ public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName) { return newReentrantReadWriteLock(lockName, false); } /** * Creates a {@link ReentrantReadWriteLock} with the given fairness policy. The {@code lockName} * is used in the warning or exception output to help identify the locks involved in the detected * deadlock. */ public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName, boolean fair) { return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair) : new CycleDetectingReentrantReadWriteLock(new LockGraphNode(lockName), fair); } // A static mapping from an Enum type to its set of LockGraphNodes. private static final ConcurrentMap< Class<? extends Enum<?>>, Map<? extends Enum<?>, LockGraphNode>> lockGraphNodesPerType = new MapMaker().weakKeys().makeMap(); /** Creates a {@code CycleDetectingLockFactory.WithExplicitOrdering<E>}. */ public static <E extends Enum<E>> WithExplicitOrdering<E> newInstanceWithExplicitOrdering( Class<E> enumClass, Policy policy) { // createNodes maps each enumClass to a Map with the corresponding enum key // type. checkNotNull(enumClass); checkNotNull(policy); @SuppressWarnings("unchecked") Map<E, LockGraphNode> lockGraphNodes = (Map<E, LockGraphNode>) getOrCreateNodes(enumClass); return new WithExplicitOrdering<>(policy, lockGraphNodes); } @SuppressWarnings("unchecked") private static <E extends Enum<E>> Map<? extends E, LockGraphNode> getOrCreateNodes( Class<E> clazz) { Map<E, LockGraphNode> existing = (Map<E, LockGraphNode>) lockGraphNodesPerType.get(clazz); if (existing != null) { return existing; } Map<E, LockGraphNode> created = createNodes(clazz); existing = (Map<E, LockGraphNode>) lockGraphNodesPerType.putIfAbsent(clazz, created); return MoreObjects.firstNonNull(existing, created); } /** * For a given Enum type, creates an immutable map from each of the Enum's values to a * corresponding LockGraphNode, with the {@code allowedPriorLocks} and {@code * disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the * associated Enum values. */ @VisibleForTesting static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) { EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz); E[] keys = clazz.getEnumConstants(); int numKeys = keys.length; ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys); // Create a LockGraphNode for each enum value. for (E key : keys) { LockGraphNode node = new LockGraphNode(getLockName(key)); nodes.add(node); map.put(key, node); } // Pre-populate all allowedPriorLocks with nodes of smaller ordinal. for (int i = 1; i < numKeys; i++) { nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i)); } // Pre-populate all disallowedPriorLocks with nodes of larger ordinal. for (int i = 0; i < numKeys - 1; i++) { nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys)); } return Collections.unmodifiableMap(map); } /** * For the given Enum value {@code rank}, returns the value's {@code "EnumClass.name"}, which is * used in exception and warning output. */ private static String getLockName(Enum<?> rank) { return rank.getDeclaringClass().getSimpleName() + "." + rank.name(); } /** * A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the additional enforcement of * an application-specified ordering of lock acquisitions. The application defines the allowed * ordering with an {@code Enum} whose values each correspond to a lock type. The order in which * the values are declared dictates the allowed order of lock acquisition. In other words, locks * corresponding to smaller values of {@link Enum#ordinal()} should only be acquired before locks * with larger ordinals. Example: * * {@snippet : * enum MyLockOrder { * FIRST, SECOND, THIRD; * } * * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(Policies.THROW); * * Lock lock1 = factory.newReentrantLock(MyLockOrder.FIRST); * Lock lock2 = factory.newReentrantLock(MyLockOrder.SECOND); * Lock lock3 = factory.newReentrantLock(MyLockOrder.THIRD); * * lock1.lock(); * lock3.lock(); * lock2.lock(); // will throw an IllegalStateException * } * * <p>As with all locks created by instances of {@code CycleDetectingLockFactory} explicitly * ordered locks participate in general cycle detection with all other cycle detecting locks, and * a lock's behavior when detecting a cyclic lock acquisition is defined by the {@code Policy} of * the factory that created it. * * <p>Note, however, that although multiple locks can be created for a given Enum value, whether * it be through separate factory instances or through multiple calls to the same factory, * attempting to acquire multiple locks with the same Enum value (within the same thread) will * result in an IllegalStateException regardless of the factory's policy. For example: * * {@snippet : * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory1 = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...); * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory2 = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...); * * Lock lockA = factory1.newReentrantLock(MyLockOrder.FIRST); * Lock lockB = factory1.newReentrantLock(MyLockOrder.FIRST); * Lock lockC = factory2.newReentrantLock(MyLockOrder.FIRST); * * lockA.lock(); * * lockB.lock(); // will throw an IllegalStateException * lockC.lock(); // will throw an IllegalStateException * * lockA.lock(); // reentrant acquisition is okay * } * * <p>It is the responsibility of the application to ensure that multiple lock instances with the * same rank are never acquired in the same thread. * * @param <E> The Enum type representing the explicit lock ordering. * @since 13.0 */ public static final class WithExplicitOrdering<E extends Enum<E>> extends CycleDetectingLockFactory { private final Map<E, LockGraphNode> lockGraphNodes; @VisibleForTesting WithExplicitOrdering(Policy policy, Map<E, LockGraphNode> lockGraphNodes) { super(policy); this.lockGraphNodes = lockGraphNodes; } /** Equivalent to {@code newReentrantLock(rank, false)}. */ public ReentrantLock newReentrantLock(E rank) { return newReentrantLock(rank, false); } /** * Creates a {@link ReentrantLock} with the given fairness policy and rank. The values returned * by {@link Enum#getDeclaringClass()} and {@link Enum#name()} are used to describe the lock in * warning or exception output. * * @throws IllegalStateException If the factory has already created a {@code Lock} with the * specified rank. */ public ReentrantLock newReentrantLock(E rank, boolean fair) { return policy == Policies.DISABLED ? new ReentrantLock(fair) // requireNonNull is safe because createNodes inserts an entry for every E. // (If the caller passes `null` for the `rank` parameter, this will throw, but that's OK.) : new CycleDetectingReentrantLock(requireNonNull(lockGraphNodes.get(rank)), fair); } /** Equivalent to {@code newReentrantReadWriteLock(rank, false)}. */ public ReentrantReadWriteLock newReentrantReadWriteLock(E rank) { return newReentrantReadWriteLock(rank, false); } /** * Creates a {@link ReentrantReadWriteLock} with the given fairness policy and rank. The values * returned by {@link Enum#getDeclaringClass()} and {@link Enum#name()} are used to describe the * lock in warning or exception output. * * @throws IllegalStateException If the factory has already created a {@code Lock} with the * specified rank. */ public ReentrantReadWriteLock newReentrantReadWriteLock(E rank, boolean fair) { return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair) // requireNonNull is safe because createNodes inserts an entry for every E. // (If the caller passes `null` for the `rank` parameter, this will throw, but that's OK.) : new CycleDetectingReentrantReadWriteLock( requireNonNull(lockGraphNodes.get(rank)), fair); } } //////// Implementation ///////// private static final LazyLogger logger = new LazyLogger(CycleDetectingLockFactory.class); final Policy policy; private CycleDetectingLockFactory(Policy policy) { this.policy = checkNotNull(policy); } /** * Tracks the currently acquired locks for each Thread, kept up to date by calls to {@link * #aboutToAcquire(CycleDetectingLock)} and {@link #lockStateChanged(CycleDetectingLock)}. */ // This is logically a Set, but an ArrayList is used to minimize the amount // of allocation done on lock()/unlock(). private static final ThreadLocal<List<LockGraphNode>> acquiredLocks = new ThreadLocal<List<LockGraphNode>>() { @Override protected List<LockGraphNode> initialValue() { return newArrayListWithCapacity(3); } }; /** * A Throwable used to record a stack trace that illustrates an example of a specific lock * acquisition ordering. The top of the stack trace is truncated such that it starts with the * acquisition of the lock in question, e.g. * * <pre> * com...ExampleStackTrace: LockB -&gt; LockC * at com...CycleDetectingReentrantLock.lock(CycleDetectingLockFactory.java:443) * at ... * at ... * at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123) * </pre> */ private static class ExampleStackTrace extends IllegalStateException { static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; static final ImmutableSet<String> EXCLUDED_CLASS_NAMES = ImmutableSet.of( CycleDetectingLockFactory.class.getName(), ExampleStackTrace.class.getName(), LockGraphNode.class.getName()); ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) { super(node1.getLockName() + " -> " + node2.getLockName()); StackTraceElement[] origStackTrace = getStackTrace(); for (int i = 0, n = origStackTrace.length; i < n; i++) { if (WithExplicitOrdering.class.getName().equals(origStackTrace[i].getClassName())) { // For pre-populated disallowedPriorLocks edges, omit the stack trace. setStackTrace(EMPTY_STACK_TRACE); break; } if (!EXCLUDED_CLASS_NAMES.contains(origStackTrace[i].getClassName())) { setStackTrace(Arrays.copyOfRange(origStackTrace, i, n)); break; } } } } /** * Represents a detected cycle in lock acquisition ordering. The exception includes a causal chain * of {@code ExampleStackTrace} instances to illustrate the cycle, e.g. * * <pre> * com....PotentialDeadlockException: Potential Deadlock from LockC -&gt; ReadWriteA * at ... * at ... * Caused by: com...ExampleStackTrace: LockB -&gt; LockC * at ... * at ... * Caused by: com...ExampleStackTrace: ReadWriteA -&gt; LockB * at ... * at ... * </pre> * * <p>Instances are logged for the {@code Policies.WARN}, and thrown for {@code Policies.THROW}. * * @since 13.0 */ public static final class PotentialDeadlockException extends ExampleStackTrace { private final ExampleStackTrace conflictingStackTrace; private PotentialDeadlockException( LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) { super(node1, node2); this.conflictingStackTrace = conflictingStackTrace; initCause(conflictingStackTrace); } public ExampleStackTrace getConflictingStackTrace() { return conflictingStackTrace; } /** * Appends the chain of messages from the {@code conflictingStackTrace} to the original {@code * message}. */ @Override public String getMessage() { // requireNonNull is safe because ExampleStackTrace sets a non-null message. StringBuilder message = new StringBuilder(requireNonNull(super.getMessage())); for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) { message.append(", ").append(t.getMessage()); } return message.toString(); } } /** * Internal Lock implementations implement the {@code CycleDetectingLock} interface, allowing the * detection logic to treat all locks in the same manner. */ private interface CycleDetectingLock { /** * @return the {@link LockGraphNode} associated with this lock. */ LockGraphNode getLockGraphNode(); /** * @return {@code true} if the current thread has acquired this lock. */ boolean isAcquiredByCurrentThread(); } /** * A {@code LockGraphNode} associated with each lock instance keeps track of the directed edges in * the lock acquisition graph. */ private static final class LockGraphNode { /** * The map tracking the locks that are known to be acquired before this lock, each associated * with an example stack trace. Locks are weakly keyed to allow proper garbage collection when * they are no longer referenced. */ final Map<LockGraphNode, ExampleStackTrace> allowedPriorLocks = new MapMaker().weakKeys().makeMap(); /** * The map tracking lock nodes that can cause a lock acquisition cycle if acquired before this * node. */ final Map<LockGraphNode, PotentialDeadlockException> disallowedPriorLocks = new MapMaker().weakKeys().makeMap(); final String lockName; LockGraphNode(String lockName) { this.lockName = Preconditions.checkNotNull(lockName); } String getLockName() { return lockName; } void checkAcquiredLocks(Policy policy, List<LockGraphNode> acquiredLocks) { for (LockGraphNode acquiredLock : acquiredLocks) { checkAcquiredLock(policy, acquiredLock); } } /** * Checks the acquisition-ordering between {@code this}, which is about to be acquired, and the * specified {@code acquiredLock}. * * <p>When this method returns, the {@code acquiredLock} should be in either the {@code * preAcquireLocks} map, for the case in which it is safe to acquire {@code this} after the * {@code acquiredLock}, or in the {@code disallowedPriorLocks} map, in which case it is not * safe. */ void checkAcquiredLock(Policy policy, LockGraphNode acquiredLock) { // checkAcquiredLock() should never be invoked by a lock that has already // been acquired. For unordered locks, aboutToAcquire() ensures this by // checking isAcquiredByCurrentThread(). For ordered locks, however, this // can happen because multiple locks may share the same LockGraphNode. In // this situation, throw an IllegalStateException as defined by contract // described in the documentation of WithExplicitOrdering. Preconditions.checkState( this != acquiredLock, "Attempted to acquire multiple locks with the same rank %s", acquiredLock.getLockName()); if (allowedPriorLocks.containsKey(acquiredLock)) { // The acquisition ordering from "acquiredLock" to "this" has already // been verified as safe. In a properly written application, this is // the common case. return; } PotentialDeadlockException previousDeadlockException = disallowedPriorLocks.get(acquiredLock); if (previousDeadlockException != null) { // Previously determined to be an unsafe lock acquisition. // Create a new PotentialDeadlockException with the same causal chain // (the example cycle) as that of the cached exception. PotentialDeadlockException exception = new PotentialDeadlockException( acquiredLock, this, previousDeadlockException.getConflictingStackTrace()); policy.handlePotentialDeadlock(exception); return; } // Otherwise, it's the first time seeing this lock relationship. Look for // a path from the acquiredLock to this. Set<LockGraphNode> seen = Sets.newIdentityHashSet(); ExampleStackTrace path = acquiredLock.findPathTo(this, seen); if (path == null) { // this can be safely acquired after the acquiredLock. // // Note that there is a race condition here which can result in missing // a cyclic edge: it's possible for two threads to simultaneous find // "safe" edges which together form a cycle. Preventing this race // condition efficiently without _introducing_ deadlock is probably // tricky. For now, just accept the race condition---missing a warning // now and then is still better than having no deadlock detection. allowedPriorLocks.put(acquiredLock, new ExampleStackTrace(acquiredLock, this)); } else { // Unsafe acquisition order detected. Create and cache a // PotentialDeadlockException. PotentialDeadlockException exception = new PotentialDeadlockException(acquiredLock, this, path); disallowedPriorLocks.put(acquiredLock, exception); policy.handlePotentialDeadlock(exception); } } /** * Performs a depth-first traversal of the graph edges defined by each node's {@code * allowedPriorLocks} to find a path between {@code this} and the specified {@code lock}. * * @return If a path was found, a chained {@link ExampleStackTrace} illustrating the path to the * {@code lock}, or {@code null} if no path was found. */ private @Nullable ExampleStackTrace findPathTo(LockGraphNode node, Set<LockGraphNode> seen) { if (!seen.add(this)) { return null; // Already traversed this node. } ExampleStackTrace found = allowedPriorLocks.get(node); if (found != null) { return found; // Found a path ending at the node! } // Recurse the edges. for (Entry<LockGraphNode, ExampleStackTrace> entry : allowedPriorLocks.entrySet()) { LockGraphNode preAcquiredLock = entry.getKey(); found = preAcquiredLock.findPathTo(node, seen); if (found != null) { // One of this node's allowedPriorLocks found a path. Prepend an // ExampleStackTrace(preAcquiredLock, this) to the returned chain of // ExampleStackTraces. ExampleStackTrace path = new ExampleStackTrace(preAcquiredLock, this); path.setStackTrace(entry.getValue().getStackTrace()); path.initCause(found); return path; } } return null; } } /** * CycleDetectingLock implementations must call this method before attempting to acquire the lock. */ private void aboutToAcquire(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get List<LockGraphNode> acquiredLockList = requireNonNull(acquiredLocks.get()); LockGraphNode node = lock.getLockGraphNode(); node.checkAcquiredLocks(policy, acquiredLockList); acquiredLockList.add(node); } } /** * CycleDetectingLock implementations must call this method in a {@code finally} clause after any * attempt to change the lock state, including both lock and unlock attempts. Failure to do so can * result in corrupting the acquireLocks set. */ private static void lockStateChanged(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get List<LockGraphNode> acquiredLockList = requireNonNull(acquiredLocks.get()); LockGraphNode node = lock.getLockGraphNode(); // Iterate in reverse because locks are usually locked/unlocked in a // LIFO order. for (int i = acquiredLockList.size() - 1; i >= 0; i--) { if (acquiredLockList.get(i) == node) { acquiredLockList.remove(i); break; } } } } final class CycleDetectingReentrantLock extends ReentrantLock implements CycleDetectingLock { private final LockGraphNode lockGraphNode; private CycleDetectingReentrantLock(LockGraphNode lockGraphNode, boolean fair) { super(fair); this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode); } ///// CycleDetectingLock methods. ///// @Override public LockGraphNode getLockGraphNode() { return lockGraphNode; } @Override public boolean isAcquiredByCurrentThread() { return isHeldByCurrentThread(); } ///// Overridden ReentrantLock methods. ///// @Override public void lock() { aboutToAcquire(this); try { super.lock(); } finally { lockStateChanged(this); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(this); try { super.lockInterruptibly(); } finally { lockStateChanged(this); } } @Override public boolean tryLock() { aboutToAcquire(this); try { return super.tryLock(); } finally { lockStateChanged(this); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(this); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(this); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(this); } } } final class CycleDetectingReentrantReadWriteLock extends ReentrantReadWriteLock implements CycleDetectingLock { // These ReadLock/WriteLock implementations shadow those in the // ReentrantReadWriteLock superclass. They are simply wrappers around the // internal Sync object, so this is safe since the shadowed locks are never // exposed or used. private final CycleDetectingReentrantReadLock readLock; private final CycleDetectingReentrantWriteLock writeLock; private final LockGraphNode lockGraphNode; private CycleDetectingReentrantReadWriteLock(LockGraphNode lockGraphNode, boolean fair) { super(fair); this.readLock = new CycleDetectingReentrantReadLock(this); this.writeLock = new CycleDetectingReentrantWriteLock(this); this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode); } ///// Overridden ReentrantReadWriteLock methods. ///// @Override public ReadLock readLock() { return readLock; } @Override public WriteLock writeLock() { return writeLock; } ///// CycleDetectingLock methods. ///// @Override public LockGraphNode getLockGraphNode() { return lockGraphNode; } @Override public boolean isAcquiredByCurrentThread() { return isWriteLockedByCurrentThread() || getReadHoldCount() > 0; } } private final class CycleDetectingReentrantReadLock extends ReentrantReadWriteLock.ReadLock { @Weak final CycleDetectingReentrantReadWriteLock readWriteLock; CycleDetectingReentrantReadLock(CycleDetectingReentrantReadWriteLock readWriteLock) { super(readWriteLock); this.readWriteLock = readWriteLock; } @Override public void lock() { aboutToAcquire(readWriteLock); try { super.lock(); } finally { lockStateChanged(readWriteLock); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(readWriteLock); try { super.lockInterruptibly(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock() { aboutToAcquire(readWriteLock); try { return super.tryLock(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(readWriteLock); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(readWriteLock); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(readWriteLock); } } } private final class CycleDetectingReentrantWriteLock extends ReentrantReadWriteLock.WriteLock { @Weak final CycleDetectingReentrantReadWriteLock readWriteLock; CycleDetectingReentrantWriteLock(CycleDetectingReentrantReadWriteLock readWriteLock) { super(readWriteLock); this.readWriteLock = readWriteLock; } @Override public void lock() { aboutToAcquire(readWriteLock); try { super.lock(); } finally { lockStateChanged(readWriteLock); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(readWriteLock); try { super.lockInterruptibly(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock() { aboutToAcquire(readWriteLock); try { return super.tryLock(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(readWriteLock); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(readWriteLock); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(readWriteLock); } } } }
google/java-photoslibrary
36,647
photoslibraryapi/src/main/java/com/google/photos/library/v1/proto/ListMediaItemsResponse.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/photos/library/v1/photos_library.proto package com.google.photos.library.v1.proto; /** * * * <pre> * List of all media items from the user's Google Photos library. * </pre> * * Protobuf type {@code google.photos.library.v1.ListMediaItemsResponse} */ public final class ListMediaItemsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.photos.library.v1.ListMediaItemsResponse) ListMediaItemsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListMediaItemsResponse.newBuilder() to construct. private ListMediaItemsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListMediaItemsResponse() { mediaItems_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListMediaItemsResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.photos.library.v1.proto.LibraryServiceProto .internal_static_google_photos_library_v1_ListMediaItemsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.photos.library.v1.proto.LibraryServiceProto .internal_static_google_photos_library_v1_ListMediaItemsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.photos.library.v1.proto.ListMediaItemsResponse.class, com.google.photos.library.v1.proto.ListMediaItemsResponse.Builder.class); } public static final int MEDIA_ITEMS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.photos.types.proto.MediaItem> mediaItems_; /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ @java.lang.Override public java.util.List<com.google.photos.types.proto.MediaItem> getMediaItemsList() { return mediaItems_; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.photos.types.proto.MediaItemOrBuilder> getMediaItemsOrBuilderList() { return mediaItems_; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ @java.lang.Override public int getMediaItemsCount() { return mediaItems_.size(); } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ @java.lang.Override public com.google.photos.types.proto.MediaItem getMediaItems(int index) { return mediaItems_.get(index); } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ @java.lang.Override public com.google.photos.types.proto.MediaItemOrBuilder getMediaItemsOrBuilder(int index) { return mediaItems_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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 < mediaItems_.size(); i++) { output.writeMessage(1, mediaItems_.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 < mediaItems_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, mediaItems_.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.photos.library.v1.proto.ListMediaItemsResponse)) { return super.equals(obj); } com.google.photos.library.v1.proto.ListMediaItemsResponse other = (com.google.photos.library.v1.proto.ListMediaItemsResponse) obj; if (!getMediaItemsList().equals(other.getMediaItemsList())) 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 (getMediaItemsCount() > 0) { hash = (37 * hash) + MEDIA_ITEMS_FIELD_NUMBER; hash = (53 * hash) + getMediaItemsList().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.photos.library.v1.proto.ListMediaItemsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.photos.library.v1.proto.ListMediaItemsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * List of all media items from the user's Google Photos library. * </pre> * * Protobuf type {@code google.photos.library.v1.ListMediaItemsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.photos.library.v1.ListMediaItemsResponse) com.google.photos.library.v1.proto.ListMediaItemsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.photos.library.v1.proto.LibraryServiceProto .internal_static_google_photos_library_v1_ListMediaItemsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.photos.library.v1.proto.LibraryServiceProto .internal_static_google_photos_library_v1_ListMediaItemsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.photos.library.v1.proto.ListMediaItemsResponse.class, com.google.photos.library.v1.proto.ListMediaItemsResponse.Builder.class); } // Construct using com.google.photos.library.v1.proto.ListMediaItemsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (mediaItemsBuilder_ == null) { mediaItems_ = java.util.Collections.emptyList(); } else { mediaItems_ = null; mediaItemsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.photos.library.v1.proto.LibraryServiceProto .internal_static_google_photos_library_v1_ListMediaItemsResponse_descriptor; } @java.lang.Override public com.google.photos.library.v1.proto.ListMediaItemsResponse getDefaultInstanceForType() { return com.google.photos.library.v1.proto.ListMediaItemsResponse.getDefaultInstance(); } @java.lang.Override public com.google.photos.library.v1.proto.ListMediaItemsResponse build() { com.google.photos.library.v1.proto.ListMediaItemsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.photos.library.v1.proto.ListMediaItemsResponse buildPartial() { com.google.photos.library.v1.proto.ListMediaItemsResponse result = new com.google.photos.library.v1.proto.ListMediaItemsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.photos.library.v1.proto.ListMediaItemsResponse result) { if (mediaItemsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { mediaItems_ = java.util.Collections.unmodifiableList(mediaItems_); bitField0_ = (bitField0_ & ~0x00000001); } result.mediaItems_ = mediaItems_; } else { result.mediaItems_ = mediaItemsBuilder_.build(); } } private void buildPartial0(com.google.photos.library.v1.proto.ListMediaItemsResponse 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.photos.library.v1.proto.ListMediaItemsResponse) { return mergeFrom((com.google.photos.library.v1.proto.ListMediaItemsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.photos.library.v1.proto.ListMediaItemsResponse other) { if (other == com.google.photos.library.v1.proto.ListMediaItemsResponse.getDefaultInstance()) return this; if (mediaItemsBuilder_ == null) { if (!other.mediaItems_.isEmpty()) { if (mediaItems_.isEmpty()) { mediaItems_ = other.mediaItems_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureMediaItemsIsMutable(); mediaItems_.addAll(other.mediaItems_); } onChanged(); } } else { if (!other.mediaItems_.isEmpty()) { if (mediaItemsBuilder_.isEmpty()) { mediaItemsBuilder_.dispose(); mediaItemsBuilder_ = null; mediaItems_ = other.mediaItems_; bitField0_ = (bitField0_ & ~0x00000001); mediaItemsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getMediaItemsFieldBuilder() : null; } else { mediaItemsBuilder_.addAllMessages(other.mediaItems_); } } } 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.photos.types.proto.MediaItem m = input.readMessage( com.google.photos.types.proto.MediaItem.parser(), extensionRegistry); if (mediaItemsBuilder_ == null) { ensureMediaItemsIsMutable(); mediaItems_.add(m); } else { mediaItemsBuilder_.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.photos.types.proto.MediaItem> mediaItems_ = java.util.Collections.emptyList(); private void ensureMediaItemsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { mediaItems_ = new java.util.ArrayList<com.google.photos.types.proto.MediaItem>(mediaItems_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.photos.types.proto.MediaItem, com.google.photos.types.proto.MediaItem.Builder, com.google.photos.types.proto.MediaItemOrBuilder> mediaItemsBuilder_; /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public java.util.List<com.google.photos.types.proto.MediaItem> getMediaItemsList() { if (mediaItemsBuilder_ == null) { return java.util.Collections.unmodifiableList(mediaItems_); } else { return mediaItemsBuilder_.getMessageList(); } } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public int getMediaItemsCount() { if (mediaItemsBuilder_ == null) { return mediaItems_.size(); } else { return mediaItemsBuilder_.getCount(); } } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public com.google.photos.types.proto.MediaItem getMediaItems(int index) { if (mediaItemsBuilder_ == null) { return mediaItems_.get(index); } else { return mediaItemsBuilder_.getMessage(index); } } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder setMediaItems(int index, com.google.photos.types.proto.MediaItem value) { if (mediaItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMediaItemsIsMutable(); mediaItems_.set(index, value); onChanged(); } else { mediaItemsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder setMediaItems( int index, com.google.photos.types.proto.MediaItem.Builder builderForValue) { if (mediaItemsBuilder_ == null) { ensureMediaItemsIsMutable(); mediaItems_.set(index, builderForValue.build()); onChanged(); } else { mediaItemsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder addMediaItems(com.google.photos.types.proto.MediaItem value) { if (mediaItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMediaItemsIsMutable(); mediaItems_.add(value); onChanged(); } else { mediaItemsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder addMediaItems(int index, com.google.photos.types.proto.MediaItem value) { if (mediaItemsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMediaItemsIsMutable(); mediaItems_.add(index, value); onChanged(); } else { mediaItemsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder addMediaItems(com.google.photos.types.proto.MediaItem.Builder builderForValue) { if (mediaItemsBuilder_ == null) { ensureMediaItemsIsMutable(); mediaItems_.add(builderForValue.build()); onChanged(); } else { mediaItemsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder addMediaItems( int index, com.google.photos.types.proto.MediaItem.Builder builderForValue) { if (mediaItemsBuilder_ == null) { ensureMediaItemsIsMutable(); mediaItems_.add(index, builderForValue.build()); onChanged(); } else { mediaItemsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder addAllMediaItems( java.lang.Iterable<? extends com.google.photos.types.proto.MediaItem> values) { if (mediaItemsBuilder_ == null) { ensureMediaItemsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, mediaItems_); onChanged(); } else { mediaItemsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder clearMediaItems() { if (mediaItemsBuilder_ == null) { mediaItems_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { mediaItemsBuilder_.clear(); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public Builder removeMediaItems(int index) { if (mediaItemsBuilder_ == null) { ensureMediaItemsIsMutable(); mediaItems_.remove(index); onChanged(); } else { mediaItemsBuilder_.remove(index); } return this; } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public com.google.photos.types.proto.MediaItem.Builder getMediaItemsBuilder(int index) { return getMediaItemsFieldBuilder().getBuilder(index); } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public com.google.photos.types.proto.MediaItemOrBuilder getMediaItemsOrBuilder(int index) { if (mediaItemsBuilder_ == null) { return mediaItems_.get(index); } else { return mediaItemsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public java.util.List<? extends com.google.photos.types.proto.MediaItemOrBuilder> getMediaItemsOrBuilderList() { if (mediaItemsBuilder_ != null) { return mediaItemsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(mediaItems_); } } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public com.google.photos.types.proto.MediaItem.Builder addMediaItemsBuilder() { return getMediaItemsFieldBuilder() .addBuilder(com.google.photos.types.proto.MediaItem.getDefaultInstance()); } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public com.google.photos.types.proto.MediaItem.Builder addMediaItemsBuilder(int index) { return getMediaItemsFieldBuilder() .addBuilder(index, com.google.photos.types.proto.MediaItem.getDefaultInstance()); } /** * * * <pre> * Output only. List of media items in the user's library. * </pre> * * <code>repeated .google.photos.types.MediaItem media_items = 1;</code> */ public java.util.List<com.google.photos.types.proto.MediaItem.Builder> getMediaItemsBuilderList() { return getMediaItemsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.photos.types.proto.MediaItem, com.google.photos.types.proto.MediaItem.Builder, com.google.photos.types.proto.MediaItemOrBuilder> getMediaItemsFieldBuilder() { if (mediaItemsBuilder_ == null) { mediaItemsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.photos.types.proto.MediaItem, com.google.photos.types.proto.MediaItem.Builder, com.google.photos.types.proto.MediaItemOrBuilder>( mediaItems_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); mediaItems_ = null; } return mediaItemsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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> * Output only. Token to use to get the next set of media items. Its presence * is the only reliable indicator of more media items being available in the * next request. * </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.photos.library.v1.ListMediaItemsResponse) } // @@protoc_insertion_point(class_scope:google.photos.library.v1.ListMediaItemsResponse) private static final com.google.photos.library.v1.proto.ListMediaItemsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.photos.library.v1.proto.ListMediaItemsResponse(); } public static com.google.photos.library.v1.proto.ListMediaItemsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListMediaItemsResponse> PARSER = new com.google.protobuf.AbstractParser<ListMediaItemsResponse>() { @java.lang.Override public ListMediaItemsResponse 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<ListMediaItemsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListMediaItemsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.photos.library.v1.proto.ListMediaItemsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/zookeeper
36,569
zookeeper-server/src/test/java/org/apache/zookeeper/server/watch/WatchManagerTest.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.zookeeper.server.watch; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZKTestCase; import org.apache.zookeeper.metrics.MetricsUtils; import org.apache.zookeeper.server.DumbWatcher; import org.apache.zookeeper.server.ServerCnxn; import org.apache.zookeeper.server.ServerMetrics; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WatchManagerTest extends ZKTestCase { protected static final Logger LOG = LoggerFactory.getLogger(WatchManagerTest.class); private static final String PATH_PREFIX = "/path"; private ConcurrentHashMap<Integer, DumbWatcher> watchers; private Random r; public static Stream<Arguments> data() { return Stream.of( Arguments.of(WatchManager.class.getName()), Arguments.of(WatchManagerOptimized.class.getName())); } @BeforeEach public void setUp() { ServerMetrics.getMetrics().resetAll(); watchers = new ConcurrentHashMap<>(); r = new Random(System.nanoTime()); } public IWatchManager getWatchManager(String className) throws IOException { System.setProperty(WatchManagerFactory.ZOOKEEPER_WATCH_MANAGER_NAME, className); return WatchManagerFactory.createWatchManager(); } public DumbWatcher createOrGetWatcher(int watcherId) { if (!watchers.containsKey(watcherId)) { DumbWatcher watcher = new DumbWatcher(watcherId); watchers.putIfAbsent(watcherId, watcher); } return watchers.get(watcherId); } public class AddWatcherWorker extends Thread { private final IWatchManager manager; private final int paths; private final int watchers; private final AtomicInteger watchesAdded; private volatile boolean stopped = false; public AddWatcherWorker( IWatchManager manager, int paths, int watchers, AtomicInteger watchesAdded) { this.manager = manager; this.paths = paths; this.watchers = watchers; this.watchesAdded = watchesAdded; } @Override public void run() { while (!stopped) { String path = PATH_PREFIX + r.nextInt(paths); Watcher watcher = createOrGetWatcher(r.nextInt(watchers)); if (manager.addWatch(path, watcher)) { watchesAdded.addAndGet(1); } } } public void shutdown() { stopped = true; } } public class WatcherTriggerWorker extends Thread { private final IWatchManager manager; private final int paths; private final AtomicInteger triggeredCount; private volatile boolean stopped = false; public WatcherTriggerWorker( IWatchManager manager, int paths, AtomicInteger triggeredCount) { this.manager = manager; this.paths = paths; this.triggeredCount = triggeredCount; } @Override public void run() { while (!stopped) { String path = PATH_PREFIX + r.nextInt(paths); WatcherOrBitSet s = manager.triggerWatch(path, EventType.NodeDeleted, -1, null); if (s != null) { triggeredCount.addAndGet(s.size()); } try { Thread.sleep(r.nextInt(10)); } catch (InterruptedException e) { } } } public void shutdown() { stopped = true; } } public class RemoveWatcherWorker extends Thread { private final IWatchManager manager; private final int paths; private final int watchers; private final AtomicInteger watchesRemoved; private volatile boolean stopped = false; public RemoveWatcherWorker( IWatchManager manager, int paths, int watchers, AtomicInteger watchesRemoved) { this.manager = manager; this.paths = paths; this.watchers = watchers; this.watchesRemoved = watchesRemoved; } @Override public void run() { while (!stopped) { String path = PATH_PREFIX + r.nextInt(paths); Watcher watcher = createOrGetWatcher(r.nextInt(watchers)); if (manager.removeWatcher(path, watcher)) { watchesRemoved.addAndGet(1); } try { Thread.sleep(r.nextInt(10)); } catch (InterruptedException e) { } } } public void shutdown() { stopped = true; } } public class CreateDeadWatchersWorker extends Thread { private final IWatchManager manager; private final int watchers; private final Set<Watcher> removedWatchers; private volatile boolean stopped = false; public CreateDeadWatchersWorker( IWatchManager manager, int watchers, Set<Watcher> removedWatchers) { this.manager = manager; this.watchers = watchers; this.removedWatchers = removedWatchers; } @Override public void run() { while (!stopped) { DumbWatcher watcher = createOrGetWatcher(r.nextInt(watchers)); watcher.setStale(); manager.removeWatcher(watcher); synchronized (removedWatchers) { removedWatchers.add(watcher); } try { Thread.sleep(r.nextInt(10)); } catch (InterruptedException e) { } } } public void shutdown() { stopped = true; } } /** * Concurrently add and trigger watch, make sure the watches triggered * are the same as the number added. */ @ParameterizedTest @MethodSource("data") @Timeout(value = 90) public void testAddAndTriggerWatcher(String className) throws IOException { IWatchManager manager = getWatchManager(className); int paths = 1; int watchers = 10000; // 1. start 5 workers to trigger watchers on that path // count all the watchers have been fired AtomicInteger watchTriggered = new AtomicInteger(); List<WatcherTriggerWorker> triggerWorkers = new ArrayList<>(); for (int i = 0; i < 5; i++) { WatcherTriggerWorker worker = new WatcherTriggerWorker(manager, paths, watchTriggered); triggerWorkers.add(worker); worker.start(); } // 2. start 5 workers to add different watchers on the same path // count all the watchers being added AtomicInteger watchesAdded = new AtomicInteger(); List<AddWatcherWorker> addWorkers = new ArrayList<>(); for (int i = 0; i < 5; i++) { AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded); addWorkers.add(worker); worker.start(); } while (watchesAdded.get() < 100000) { try { Thread.sleep(100); } catch (InterruptedException e) { } } // 3. stop all the addWorkers for (AddWatcherWorker worker : addWorkers) { worker.shutdown(); } // 4. running the trigger worker a bit longer to make sure // all watchers added are fired try { Thread.sleep(500); } catch (InterruptedException e) { } // 5. stop all triggerWorkers for (WatcherTriggerWorker worker : triggerWorkers) { worker.shutdown(); } // 6. make sure the total watch triggered is same as added assertTrue(watchesAdded.get() > 0); assertEquals(watchesAdded.get(), watchTriggered.get()); } /** * Concurrently add and remove watch, make sure the watches left + * the watches removed are equal to the total added watches. */ @ParameterizedTest @MethodSource("data") @Timeout(value = 90) public void testRemoveWatcherOnPath(String className) throws IOException { IWatchManager manager = getWatchManager(className); int paths = 10; int watchers = 10000; // 1. start 5 workers to remove watchers on those path // record the watchers have been removed AtomicInteger watchesRemoved = new AtomicInteger(); List<RemoveWatcherWorker> removeWorkers = new ArrayList<>(); for (int i = 0; i < 5; i++) { RemoveWatcherWorker worker = new RemoveWatcherWorker(manager, paths, watchers, watchesRemoved); removeWorkers.add(worker); worker.start(); } // 2. start 5 workers to add different watchers on different path // record the watchers have been added AtomicInteger watchesAdded = new AtomicInteger(); List<AddWatcherWorker> addWorkers = new ArrayList<>(); for (int i = 0; i < 5; i++) { AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded); addWorkers.add(worker); worker.start(); } while (watchesAdded.get() < 100000) { try { Thread.sleep(100); } catch (InterruptedException e) { } } // 3. stop all workers for (RemoveWatcherWorker worker : removeWorkers) { worker.shutdown(); } for (AddWatcherWorker worker : addWorkers) { worker.shutdown(); } // 4. sleep for a while to make sure all the thread exited try { Thread.sleep(500); } catch (InterruptedException e) { } // 5. make sure left watches + removed watches = added watches assertTrue(watchesAdded.get() > 0); assertTrue(watchesRemoved.get() > 0); assertTrue(manager.size() > 0); assertEquals(watchesAdded.get(), watchesRemoved.get() + manager.size()); } /** * Test add, contains and remove on generic watch manager. */ @ParameterizedTest @MethodSource("data") public void testAddRemoveWatcher(String className) throws IOException { IWatchManager manager = getWatchManager(className); Watcher watcher1 = new DumbWatcher(); Watcher watcher2 = new DumbWatcher(); // given: add watcher1 to "/node1" manager.addWatch("/node1", watcher1); // then: contains or remove should fail on mismatch path and watcher pair assertFalse(manager.containsWatcher("/node1", watcher2)); assertFalse(manager.containsWatcher("/node2", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher2)); assertFalse(manager.removeWatcher("/node2", watcher1)); // then: contains or remove should succeed on matching path and watcher pair assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.removeWatcher("/node1", watcher1)); // then: contains or remove should fail on removed path and watcher pair assertFalse(manager.containsWatcher("/node1", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher1)); } /** * Test containsWatcher on all pairs, and removeWatcher on mismatch pairs. */ @Test public void testContainsMode() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); Watcher watcher2 = new DumbWatcher(); // given: add watcher1 to "/node1" in persistent mode assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertNotEquals(WatcherMode.PERSISTENT, WatcherMode.DEFAULT_WATCHER_MODE); // then: contains should succeed on watcher1 to "/node1" in persistent and any mode assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.containsWatcher("/node1", watcher1, null)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); // then: contains and remove should fail on mismatch watcher assertFalse(manager.containsWatcher("/node1", watcher2)); assertFalse(manager.containsWatcher("/node1", watcher2, null)); assertFalse(manager.containsWatcher("/node1", watcher2, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher2, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node1", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher2)); assertFalse(manager.removeWatcher("/node1", watcher2, null)); assertFalse(manager.removeWatcher("/node1", watcher2, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher2, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); // then: contains and remove should fail on mismatch path assertFalse(manager.containsWatcher("/node2", watcher1)); assertFalse(manager.containsWatcher("/node2", watcher1, null)); assertFalse(manager.containsWatcher("/node2", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node2", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node2", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node2", watcher1)); assertFalse(manager.removeWatcher("/node2", watcher1, null)); assertFalse(manager.removeWatcher("/node2", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node2", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node2", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // then: contains and remove should fail on mismatch modes assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // when: add watcher1 to "/node1" in remaining modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // then: contains should succeed on watcher to "/node1" in all modes assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.containsWatcher("/node1", watcher1, null)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); } /** * Test repeatedly {@link WatchManager#addWatch(String, Watcher, WatcherMode)}. */ @Test public void testAddModeRepeatedly() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); // given: add watcher1 to "/node1" in all modes manager.addWatch("/node1", watcher1, WatcherMode.STANDARD); manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT); manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE); // when: add watcher1 to "/node1" in these modes repeatedly assertFalse(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // then: contains and remove should work normally on watcher1 to "/node1" assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.containsWatcher("/node1", watcher1, null)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.containsWatcher("/node1", watcher1, null)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.containsWatcher("/node1", watcher1, null)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.containsWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1, null)); assertFalse(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher1, null)); } /** * Test {@link WatchManager#removeWatcher(String, Watcher, WatcherMode)} on one pair should not break others. */ @Test public void testRemoveModeOne() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); Watcher watcher2 = new DumbWatcher(); // given: add watcher1 to "/node1" and watcher2 to "/node2" in all modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.addWatch("/node2", watcher2, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node2", watcher2, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node2", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); // when: remove one pair assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); // then: contains and remove should succeed on other pairs assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.containsWatcher("/node2", watcher2, WatcherMode.STANDARD)); assertTrue(manager.containsWatcher("/node2", watcher2, WatcherMode.PERSISTENT)); assertTrue(manager.containsWatcher("/node2", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.removeWatcher("/node2", watcher2, WatcherMode.STANDARD)); assertTrue(manager.removeWatcher("/node2", watcher2, WatcherMode.PERSISTENT)); assertTrue(manager.removeWatcher("/node2", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); } /** * Test {@link WatchManager#removeWatcher(String, Watcher, WatcherMode)} with {@code null} watcher mode. */ @Test public void testRemoveModeAll() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); // given: add watcher1 to "/node1" in all modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // when: remove watcher1 using null watcher mode assertTrue(manager.removeWatcher("/node1", watcher1, null)); // then: contains and remove should fail on watcher1 to "/node1" in all modes assertFalse(manager.containsWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1, null)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher1, null)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // given: add watcher1 to "/node1" in all modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // then: remove watcher1 without a mode should behave same to removing all modes assertTrue(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1, null)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher1, null)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); } /** * Test {@link WatchManager#removeWatcher(String, Watcher)}. */ @Test public void testRemoveModeAllDefault() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); // given: add watcher1 to "/node1" in all modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // then: remove watcher1 without a mode should behave same to removing all modes assertTrue(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1, null)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher1, null)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); } /** * Test {@link WatchManager#removeWatcher(String, Watcher, WatcherMode)} all modes individually. */ @Test public void testRemoveModeAllIndividually() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); // given: add watcher1 to "/node1" in all modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // when: remove all modes individually assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); // then: contains and remove should fail on watcher1 to "/node1" in all modes assertFalse(manager.containsWatcher("/node1", watcher1)); assertFalse(manager.containsWatcher("/node1", watcher1, null)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertFalse(manager.removeWatcher("/node1", watcher1)); assertFalse(manager.removeWatcher("/node1", watcher1, null)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); } /** * Test {@link WatchManager#removeWatcher(String, Watcher, WatcherMode)} on mismatch pair should break nothing. */ @Test public void testRemoveModeMismatch() { IWatchManager manager = new WatchManager(); Watcher watcher1 = new DumbWatcher(); Watcher watcher2 = new DumbWatcher(); // given: add watcher1 to "/node1" and watcher2 to "/node2" in all modes assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.addWatch("/node2", watcher2, WatcherMode.STANDARD)); assertTrue(manager.addWatch("/node2", watcher2, WatcherMode.PERSISTENT)); assertTrue(manager.addWatch("/node2", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); // when: remove mismatch path and watcher pairs assertFalse(manager.removeWatcher("/node1", watcher2)); assertFalse(manager.removeWatcher("/node1", watcher2, null)); assertFalse(manager.removeWatcher("/node1", watcher2, WatcherMode.STANDARD)); assertFalse(manager.removeWatcher("/node1", watcher2, WatcherMode.PERSISTENT)); assertFalse(manager.removeWatcher("/node1", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); // then: no existing watching pairs should break assertTrue(manager.containsWatcher("/node1", watcher1)); assertTrue(manager.containsWatcher("/node1", watcher1, null)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.STANDARD)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT)); assertTrue(manager.containsWatcher("/node1", watcher1, WatcherMode.PERSISTENT_RECURSIVE)); assertTrue(manager.containsWatcher("/node2", watcher2)); assertTrue(manager.containsWatcher("/node2", watcher2, null)); assertTrue(manager.containsWatcher("/node2", watcher2, WatcherMode.STANDARD)); assertTrue(manager.containsWatcher("/node2", watcher2, WatcherMode.PERSISTENT)); assertTrue(manager.containsWatcher("/node2", watcher2, WatcherMode.PERSISTENT_RECURSIVE)); } /** * Concurrently add watch while close the watcher to simulate the * client connections closed on prod. */ @ParameterizedTest @MethodSource("data") @Timeout(value = 90) public void testDeadWatchers(String className) throws IOException { System.setProperty("zookeeper.watcherCleanThreshold", "10"); System.setProperty("zookeeper.watcherCleanIntervalInSeconds", "1"); IWatchManager manager = getWatchManager(className); int paths = 1; int watchers = 100000; // 1. start 5 workers to randomly mark those watcher as dead // and remove them from watch manager Set<Watcher> deadWatchers = new HashSet<>(); List<CreateDeadWatchersWorker> deadWorkers = new ArrayList<>(); for (int i = 0; i < 5; i++) { CreateDeadWatchersWorker worker = new CreateDeadWatchersWorker(manager, watchers, deadWatchers); deadWorkers.add(worker); worker.start(); } // 2. start 5 workers to add different watchers on the same path AtomicInteger watchesAdded = new AtomicInteger(); List<AddWatcherWorker> addWorkers = new ArrayList<>(); for (int i = 0; i < 5; i++) { AddWatcherWorker worker = new AddWatcherWorker(manager, paths, watchers, watchesAdded); addWorkers.add(worker); worker.start(); } while (watchesAdded.get() < 50000) { try { Thread.sleep(100); } catch (InterruptedException e) { } } // 3. stop all workers for (CreateDeadWatchersWorker worker : deadWorkers) { worker.shutdown(); } for (AddWatcherWorker worker : addWorkers) { worker.shutdown(); } // 4. sleep for a while to make sure all the thread exited // the cleaner may wait as long as CleanerInterval+CleanerInterval/2+1 // So need to sleep as least that long try { Thread.sleep(2000); } catch (InterruptedException e) { } // 5. make sure the dead watchers are not in the existing watchers WatchesReport existingWatchers = manager.getWatches(); for (Watcher w : deadWatchers) { assertFalse(existingWatchers.hasPaths(((ServerCnxn) w).getSessionId())); } } private void checkMetrics(String metricName, long min, long max, double avg, long cnt, long sum) { Map<String, Object> values = MetricsUtils.currentServerMetrics(); assertEquals(min, values.get("min_" + metricName)); assertEquals(max, values.get("max_" + metricName)); assertEquals(avg, (Double) values.get("avg_" + metricName), 0.000001); assertEquals(cnt, values.get("cnt_" + metricName)); assertEquals(sum, values.get("sum_" + metricName)); } private void checkMostRecentWatchedEvent(DumbWatcher watcher, String path, EventType eventType, long zxid) { assertEquals(path, watcher.getMostRecentPath()); assertEquals(eventType, watcher.getMostRecentEventType()); assertEquals(zxid, watcher.getMostRecentZxid()); } @ParameterizedTest @MethodSource("data") public void testWatcherMetrics(String className) throws IOException { IWatchManager manager = getWatchManager(className); ServerMetrics.getMetrics().resetAll(); DumbWatcher watcher1 = new DumbWatcher(1); DumbWatcher watcher2 = new DumbWatcher(2); final String path1 = "/path1"; final String path2 = "/path2"; final String path3 = "/path3"; //both watcher1 and watcher2 are watching path1 manager.addWatch(path1, watcher1); manager.addWatch(path1, watcher2); //path2 is watched by watcher1 manager.addWatch(path2, watcher1); manager.triggerWatch(path3, EventType.NodeCreated, 1, null); //path3 is not being watched so metric is 0 checkMetrics("node_created_watch_count", 0L, 0L, 0D, 0L, 0L); // Watchers shouldn't have received any events yet so the zxid should be -1. checkMostRecentWatchedEvent(watcher1, null, null, -1); checkMostRecentWatchedEvent(watcher2, null, null, -1); //path1 is watched by two watchers so two fired manager.triggerWatch(path1, EventType.NodeCreated, 2, null); checkMetrics("node_created_watch_count", 2L, 2L, 2D, 1L, 2L); checkMostRecentWatchedEvent(watcher1, path1, EventType.NodeCreated, 2); checkMostRecentWatchedEvent(watcher2, path1, EventType.NodeCreated, 2); //path2 is watched by one watcher so one fired now total is 3 manager.triggerWatch(path2, EventType.NodeCreated, 3, null); checkMetrics("node_created_watch_count", 1L, 2L, 1.5D, 2L, 3L); checkMostRecentWatchedEvent(watcher1, path2, EventType.NodeCreated, 3); checkMostRecentWatchedEvent(watcher2, path1, EventType.NodeCreated, 2); //watches on path1 are no longer there so zero fired manager.triggerWatch(path1, EventType.NodeDataChanged, 4, null); checkMetrics("node_changed_watch_count", 0L, 0L, 0D, 0L, 0L); checkMostRecentWatchedEvent(watcher1, path2, EventType.NodeCreated, 3); checkMostRecentWatchedEvent(watcher2, path1, EventType.NodeCreated, 2); //both watcher and watcher are watching path1 manager.addWatch(path1, watcher1); manager.addWatch(path1, watcher2); //path2 is watched by watcher1 manager.addWatch(path2, watcher1); manager.triggerWatch(path1, EventType.NodeDataChanged, 5, null); checkMetrics("node_changed_watch_count", 2L, 2L, 2D, 1L, 2L); checkMostRecentWatchedEvent(watcher1, path1, EventType.NodeDataChanged, 5); checkMostRecentWatchedEvent(watcher2, path1, EventType.NodeDataChanged, 5); manager.triggerWatch(path2, EventType.NodeDeleted, 6, null); checkMetrics("node_deleted_watch_count", 1L, 1L, 1D, 1L, 1L); checkMostRecentWatchedEvent(watcher1, path2, EventType.NodeDeleted, 6); checkMostRecentWatchedEvent(watcher2, path1, EventType.NodeDataChanged, 5); //make sure that node created watch count is not impacted by the fire of other event types checkMetrics("node_created_watch_count", 1L, 2L, 1.5D, 2L, 3L); } }
apache/storm
36,949
external/storm-kafka-client/src/main/java/org/apache/storm/kafka/spout/KafkaSpout.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.storm.kafka.spout; import static org.apache.storm.kafka.spout.FirstPollOffsetStrategy.EARLIEST; import static org.apache.storm.kafka.spout.FirstPollOffsetStrategy.LATEST; import static org.apache.storm.kafka.spout.FirstPollOffsetStrategy.UNCOMMITTED_EARLIEST; import static org.apache.storm.kafka.spout.FirstPollOffsetStrategy.UNCOMMITTED_LATEST; import com.google.common.annotations.VisibleForTesting; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.commons.lang.Validate; import org.apache.kafka.clients.admin.Admin; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRebalanceListener; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.consumer.OffsetAndMetadata; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.InterruptException; import org.apache.kafka.common.errors.RetriableException; import org.apache.storm.kafka.spout.KafkaSpoutConfig.ProcessingGuarantee; import org.apache.storm.kafka.spout.internal.ClientFactory; import org.apache.storm.kafka.spout.internal.ClientFactoryDefault; import org.apache.storm.kafka.spout.internal.CommitMetadataManager; import org.apache.storm.kafka.spout.internal.OffsetManager; import org.apache.storm.kafka.spout.internal.Timer; import org.apache.storm.kafka.spout.metrics2.KafkaOffsetMetricManager; import org.apache.storm.kafka.spout.subscription.TopicAssigner; import org.apache.storm.spout.SpoutOutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichSpout; import org.apache.storm.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KafkaSpout<K, V> extends BaseRichSpout { private static final long serialVersionUID = 4151921085047987154L; //Initial delay for the commit and assignment refresh timers public static final long TIMER_DELAY_MS = 500; private static final Logger LOG = LoggerFactory.getLogger(KafkaSpout.class); // Storm protected SpoutOutputCollector collector; // Kafka private final KafkaSpoutConfig<K, V> kafkaSpoutConfig; private final ClientFactory<K, V> kafkaClientFactory; private final TopicAssigner topicAssigner; private transient Consumer<K, V> consumer; private transient Admin admin; // Bookkeeping // Strategy to determine the fetch offset of the first realized by the spout upon activation private transient FirstPollOffsetStrategy firstPollOffsetStrategy; // Class that has the logic to handle tuple failure. private transient KafkaSpoutRetryService retryService; // Handles tuple events (emit, ack etc.) private transient KafkaTupleListener tupleListener; // timer == null only if the processing guarantee is at-most-once private transient Timer commitTimer; // Initialization is only complete after the first call to KafkaSpoutConsumerRebalanceListener.onPartitionsAssigned() // Tuples that were successfully acked/emitted. These tuples will be committed periodically when the commit timer expires, // or after a consumer rebalance, or during close/deactivate. Always empty if processing guarantee is none or at-most-once. private transient Map<TopicPartition, OffsetManager> offsetManagers; // Tuples that have been emitted but that are "on the wire", i.e. pending being acked or failed. // Always empty if processing guarantee is none or at-most-once private transient Set<KafkaSpoutMessageId> emitted; // Records that have been polled and are queued to be emitted in the nextTuple() call. One record is emitted per nextTuple() private transient Map<TopicPartition, List<ConsumerRecord<K, V>>> waitingToEmit; // Triggers when an assignment should be refreshed private transient Timer refreshAssignmentTimer; private transient TopologyContext context; private transient CommitMetadataManager commitMetadataManager; private transient KafkaOffsetMetricManager<K, V> kafkaOffsetMetricManager; private transient KafkaSpoutConsumerRebalanceListener rebalanceListener; public KafkaSpout(KafkaSpoutConfig<K, V> kafkaSpoutConfig) { this(kafkaSpoutConfig, new ClientFactoryDefault<>(), new TopicAssigner()); } @VisibleForTesting KafkaSpout(KafkaSpoutConfig<K, V> kafkaSpoutConfig, ClientFactory<K, V> kafkaClientFactory, TopicAssigner topicAssigner) { this.kafkaClientFactory = kafkaClientFactory; this.topicAssigner = topicAssigner; this.kafkaSpoutConfig = kafkaSpoutConfig; } @Override public void open(Map<String, Object> conf, TopologyContext context, SpoutOutputCollector collector) { this.context = context; // Spout internals this.collector = collector; // Offset management firstPollOffsetStrategy = kafkaSpoutConfig.getFirstPollOffsetStrategy(); // Retries management retryService = kafkaSpoutConfig.getRetryService(); tupleListener = kafkaSpoutConfig.getTupleListener(); if (kafkaSpoutConfig.getProcessingGuarantee() != KafkaSpoutConfig.ProcessingGuarantee.AT_MOST_ONCE) { // In at-most-once mode the offsets are committed after every poll, and not periodically as controlled by the timer commitTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getOffsetsCommitPeriodMs(), TimeUnit.MILLISECONDS); } refreshAssignmentTimer = new Timer(TIMER_DELAY_MS, kafkaSpoutConfig.getPartitionRefreshPeriodMs(), TimeUnit.MILLISECONDS); offsetManagers = new HashMap<>(); emitted = new HashSet<>(); waitingToEmit = new HashMap<>(); commitMetadataManager = new CommitMetadataManager(context, kafkaSpoutConfig.getProcessingGuarantee()); rebalanceListener = new KafkaSpoutConsumerRebalanceListener(); consumer = kafkaClientFactory.createConsumer(kafkaSpoutConfig.getKafkaProps()); admin = kafkaClientFactory.createAdmin(kafkaSpoutConfig.getKafkaProps()); tupleListener.open(conf, context); this.kafkaOffsetMetricManager = new KafkaOffsetMetricManager<>(() -> Collections.unmodifiableMap(offsetManagers), () -> admin, context); LOG.info("Kafka Spout opened with the following configuration: {}", kafkaSpoutConfig); } private boolean canRegisterMetrics() { try { KafkaConsumer.class.getDeclaredMethod("beginningOffsets", Collection.class); } catch (NoSuchMethodException e) { LOG.warn("Minimum required kafka-clients library version to enable metrics is 0.10.1.0. Disabling spout metrics."); return false; } return true; } private boolean isAtLeastOnceProcessing() { return kafkaSpoutConfig.getProcessingGuarantee() == KafkaSpoutConfig.ProcessingGuarantee.AT_LEAST_ONCE; } // =========== Consumer Rebalance Listener - On the same thread as the caller =========== private class KafkaSpoutConsumerRebalanceListener implements ConsumerRebalanceListener { private Collection<TopicPartition> previousAssignment = new HashSet<>(); @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { previousAssignment = partitions; LOG.info("Partitions revoked. [consumer-group={}, consumer={}, topic-partitions={}]", kafkaSpoutConfig.getConsumerGroupId(), consumer, partitions); if (isAtLeastOnceProcessing()) { commitOffsetsForAckedTuples(); } } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { LOG.info("Partitions reassignment. [task-ID={}, consumer-group={}, consumer={}, topic-partitions={}]", context.getThisTaskId(), kafkaSpoutConfig.getConsumerGroupId(), consumer, partitions); initialize(partitions); tupleListener.onPartitionsReassigned(partitions); } private void initialize(Collection<TopicPartition> partitions) { if (isAtLeastOnceProcessing()) { // remove offsetManagers for all partitions that are no longer assigned to this spout offsetManagers.keySet().retainAll(partitions); retryService.retainAll(partitions); /* * Emitted messages for partitions that are no longer assigned to this spout can't be acked and should not be retried, hence * remove them from emitted collection. */ emitted.removeIf(msgId -> !partitions.contains(msgId.getTopicPartition())); } waitingToEmit.keySet().retainAll(partitions); Set<TopicPartition> newPartitions = new HashSet<>(partitions); // If this partition was previously assigned to this spout, // leave the acked offsets and consumer position as they were to resume where it left off newPartitions.removeAll(previousAssignment); for (TopicPartition newTp : newPartitions) { final Map<TopicPartition, OffsetAndMetadata> committedOffset = consumer.committed(Collections.singleton(newTp)); final long fetchOffset = doSeek(newTp, committedOffset.get(newTp)); LOG.debug("Set consumer position to [{}] for topic-partition [{}] with [{}] and committed offset [{}]", fetchOffset, newTp, firstPollOffsetStrategy, committedOffset); if (isAtLeastOnceProcessing() && !offsetManagers.containsKey(newTp)) { offsetManagers.put(newTp, new OffsetManager(newTp, fetchOffset)); } } LOG.info("Initialization complete"); } /** * Sets the cursor to the location dictated by the first poll strategy and returns the fetch offset. */ private long doSeek(TopicPartition newTp, OffsetAndMetadata committedOffset) { LOG.trace("Seeking offset for topic-partition [{}] with [{}] and committed offset [{}]", newTp, firstPollOffsetStrategy, committedOffset); if (committedOffset != null) { // offset was previously committed for this consumer group and topic-partition, either by this or another topology. if (commitMetadataManager.isOffsetCommittedByThisTopology(newTp, committedOffset, Collections.unmodifiableMap(offsetManagers))) { // Another KafkaSpout instance (of this topology) already committed, therefore FirstPollOffsetStrategy does not apply. consumer.seek(newTp, committedOffset.offset()); } else { // offset was not committed by this topology, therefore FirstPollOffsetStrategy applies // (only when the topology is first deployed). if (firstPollOffsetStrategy.equals(EARLIEST)) { consumer.seekToBeginning(Collections.singleton(newTp)); } else if (firstPollOffsetStrategy.equals(LATEST)) { consumer.seekToEnd(Collections.singleton(newTp)); } else { // Resume polling at the last committed offset, i.e. the first offset that is not marked as processed. consumer.seek(newTp, committedOffset.offset()); } } } else { // no offset commits have ever been done for this consumer group and topic-partition, // so start at the beginning or end depending on FirstPollOffsetStrategy if (firstPollOffsetStrategy.equals(EARLIEST) || firstPollOffsetStrategy.equals(UNCOMMITTED_EARLIEST)) { consumer.seekToBeginning(Collections.singleton(newTp)); } else if (firstPollOffsetStrategy.equals(LATEST) || firstPollOffsetStrategy.equals(UNCOMMITTED_LATEST)) { consumer.seekToEnd(Collections.singleton(newTp)); } } return consumer.position(newTp); } } // ======== Next Tuple ======= @Override public void nextTuple() { try { if (refreshAssignmentTimer.isExpiredResetOnTrue()) { refreshAssignment(); } if (commitTimer != null && commitTimer.isExpiredResetOnTrue()) { if (isAtLeastOnceProcessing()) { commitOffsetsForAckedTuples(); } else if (kafkaSpoutConfig.getProcessingGuarantee() == ProcessingGuarantee.NO_GUARANTEE) { Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = createFetchedOffsetsMetadata(consumer.assignment()); consumer.commitAsync(offsetsToCommit, null); LOG.debug("Committed offsets {} to Kafka", offsetsToCommit); } } PollablePartitionsInfo pollablePartitionsInfo = getPollablePartitionsInfo(); if (pollablePartitionsInfo.shouldPoll()) { try { setWaitingToEmit(pollKafkaBroker(pollablePartitionsInfo)); } catch (RetriableException e) { LOG.error("Failed to poll from kafka.", e); } } emitIfWaitingNotEmitted(); } catch (InterruptException e) { throwKafkaConsumerInterruptedException(); } } private void throwKafkaConsumerInterruptedException() { //Kafka throws their own type of exception when interrupted. //Throw a new Java InterruptedException to ensure Storm can recognize the exception as a reaction to an interrupt. throw new RuntimeException(new InterruptedException("Kafka consumer was interrupted")); } private PollablePartitionsInfo getPollablePartitionsInfo() { if (isWaitingToEmit()) { LOG.debug("Not polling. Tuples waiting to be emitted."); return new PollablePartitionsInfo(Collections.emptySet(), Collections.emptyMap()); } Set<TopicPartition> assignment = consumer.assignment(); if (!isAtLeastOnceProcessing()) { return new PollablePartitionsInfo(assignment, Collections.emptyMap()); } Map<TopicPartition, Long> earliestRetriableOffsets = retryService.earliestRetriableOffsets(); Set<TopicPartition> pollablePartitions = new HashSet<>(); final int maxUncommittedOffsets = kafkaSpoutConfig.getMaxUncommittedOffsets(); for (TopicPartition tp : assignment) { OffsetManager offsetManager = offsetManagers.get(tp); int numUncommittedOffsets = offsetManager.getNumUncommittedOffsets(); if (numUncommittedOffsets < maxUncommittedOffsets) { //Allow poll if the partition is not at the maxUncommittedOffsets limit pollablePartitions.add(tp); } else { long offsetAtLimit = offsetManager.getNthUncommittedOffsetAfterCommittedOffset(maxUncommittedOffsets); Long earliestRetriableOffset = earliestRetriableOffsets.get(tp); if (earliestRetriableOffset != null && earliestRetriableOffset <= offsetAtLimit) { //Allow poll if there are retriable tuples within the maxUncommittedOffsets limit pollablePartitions.add(tp); } else { LOG.debug("Not polling on partition [{}]. It has [{}] uncommitted offsets, which exceeds the limit of [{}]. ", tp, numUncommittedOffsets, maxUncommittedOffsets); } } } return new PollablePartitionsInfo(pollablePartitions, earliestRetriableOffsets); } private boolean isWaitingToEmit() { return waitingToEmit.values().stream() .anyMatch(list -> !list.isEmpty()); } private void setWaitingToEmit(ConsumerRecords<K, V> consumerRecords) { for (TopicPartition tp : consumerRecords.partitions()) { waitingToEmit.put(tp, new LinkedList<>(consumerRecords.records(tp))); } } // ======== poll ========= private ConsumerRecords<K, V> pollKafkaBroker(PollablePartitionsInfo pollablePartitionsInfo) { doSeekRetriableTopicPartitions(pollablePartitionsInfo.pollableEarliestRetriableOffsets); Set<TopicPartition> pausedPartitions = new HashSet<>(consumer.assignment()); pausedPartitions.removeIf(pollablePartitionsInfo.pollablePartitions::contains); try { consumer.pause(pausedPartitions); final ConsumerRecords<K, V> consumerRecords = consumer.poll(Duration.ofMillis(kafkaSpoutConfig.getPollTimeoutMs())); ackRetriableOffsetsIfCompactedAway(pollablePartitionsInfo.pollableEarliestRetriableOffsets, consumerRecords); final int numPolledRecords = consumerRecords.count(); LOG.debug("Polled [{}] records from Kafka", numPolledRecords); if (kafkaSpoutConfig.getProcessingGuarantee() == KafkaSpoutConfig.ProcessingGuarantee.AT_MOST_ONCE) { //Commit polled records immediately to ensure delivery is at-most-once. Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = createFetchedOffsetsMetadata(consumer.assignment()); consumer.commitSync(offsetsToCommit); LOG.debug("Committed offsets {} to Kafka", offsetsToCommit); } return consumerRecords; } finally { consumer.resume(pausedPartitions); } } private void doSeekRetriableTopicPartitions(Map<TopicPartition, Long> pollableEarliestRetriableOffsets) { for (Entry<TopicPartition, Long> retriableTopicPartitionAndOffset : pollableEarliestRetriableOffsets.entrySet()) { //Seek directly to the earliest retriable message for each retriable topic partition consumer.seek(retriableTopicPartitionAndOffset.getKey(), retriableTopicPartitionAndOffset.getValue()); } } private void ackRetriableOffsetsIfCompactedAway(Map<TopicPartition, Long> earliestRetriableOffsets, ConsumerRecords<K, V> consumerRecords) { for (Entry<TopicPartition, Long> entry : earliestRetriableOffsets.entrySet()) { TopicPartition tp = entry.getKey(); List<ConsumerRecord<K, V>> records = consumerRecords.records(tp); if (!records.isEmpty()) { ConsumerRecord<K, V> record = records.get(0); long seekOffset = entry.getValue(); long earliestReceivedOffset = record.offset(); if (seekOffset < earliestReceivedOffset) { //Since we asked for tuples starting at seekOffset, some retriable records must have been compacted away. //Ack up to the first offset received if the record is not already acked or currently in the topology for (long i = seekOffset; i < earliestReceivedOffset; i++) { KafkaSpoutMessageId msgId = retryService.getMessageId(tp, i); if (!offsetManagers.get(tp).contains(msgId) && !emitted.contains(msgId)) { LOG.debug("Record at offset [{}] appears to have been compacted away from topic [{}], marking as acked", i, tp); retryService.remove(msgId); emitted.add(msgId); ack(msgId); } } } } } } // ======== emit ========= private void emitIfWaitingNotEmitted() { Iterator<List<ConsumerRecord<K, V>>> waitingToEmitIter = waitingToEmit.values().iterator(); outerLoop: while (waitingToEmitIter.hasNext()) { List<ConsumerRecord<K, V>> waitingToEmitForTp = waitingToEmitIter.next(); while (!waitingToEmitForTp.isEmpty()) { final boolean emittedTuple = emitOrRetryTuple(waitingToEmitForTp.remove(0)); if (emittedTuple) { break outerLoop; } } waitingToEmitIter.remove(); } } /** * Creates a tuple from the kafka record and emits it if it was never emitted or it is ready to be retried. * * @param record to be emitted * @return true if tuple was emitted. False if tuple has been acked or has been emitted and is pending ack or fail */ private boolean emitOrRetryTuple(ConsumerRecord<K, V> record) { final TopicPartition tp = new TopicPartition(record.topic(), record.partition()); final KafkaSpoutMessageId msgId = retryService.getMessageId(tp, record.offset()); if (offsetManagers.containsKey(tp) && offsetManagers.get(tp).contains(msgId)) { // has been acked LOG.trace("Tuple for record [{}] has already been acked. Skipping", record); } else if (emitted.contains(msgId)) { // has been emitted and it is pending ack or fail LOG.trace("Tuple for record [{}] has already been emitted. Skipping", record); } else { final List<Object> tuple = kafkaSpoutConfig.getTranslator().apply(record); if (isEmitTuple(tuple)) { final boolean isScheduled = retryService.isScheduled(msgId); // not scheduled <=> never failed (i.e. never emitted), or scheduled and ready to be retried if (!isScheduled || retryService.isReady(msgId)) { final String stream = tuple instanceof KafkaTuple ? ((KafkaTuple) tuple).getStream() : Utils.DEFAULT_STREAM_ID; if (!isAtLeastOnceProcessing()) { if (kafkaSpoutConfig.isTupleTrackingEnforced()) { collector.emit(stream, tuple, msgId); LOG.trace("Emitted tuple [{}] for record [{}] with msgId [{}]", tuple, record, msgId); } else { collector.emit(stream, tuple); LOG.trace("Emitted tuple [{}] for record [{}]", tuple, record); } } else { emitted.add(msgId); offsetManagers.get(tp).addToEmitMsgs(msgId.offset()); if (isScheduled) { // Was scheduled for retry and re-emitted, so remove from schedule. retryService.remove(msgId); } collector.emit(stream, tuple, msgId); tupleListener.onEmit(tuple, msgId); LOG.trace("Emitted tuple [{}] for record [{}] with msgId [{}]", tuple, record, msgId); } return true; } } else { /* * if a null tuple is not configured to be emitted, it should be marked as emitted and acked immediately to allow its offset * to be commited to Kafka */ LOG.debug("Not emitting null tuple for record [{}] as defined in configuration.", record); if (isAtLeastOnceProcessing()) { msgId.setNullTuple(true); offsetManagers.get(tp).addToEmitMsgs(msgId.offset()); ack(msgId); } } } return false; } /** * Emits a tuple if it is not a null tuple, or if the spout is configured to emit null tuples. */ private boolean isEmitTuple(List<Object> tuple) { return tuple != null || kafkaSpoutConfig.isEmitNullTuples(); } private Map<TopicPartition, OffsetAndMetadata> createFetchedOffsetsMetadata(Set<TopicPartition> assignedPartitions) { Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>(); for (TopicPartition tp : assignedPartitions) { offsetsToCommit.put(tp, new OffsetAndMetadata(consumer.position(tp), commitMetadataManager.getCommitMetadata())); } return offsetsToCommit; } private void commitOffsetsForAckedTuples() { final Map<TopicPartition, OffsetAndMetadata> nextCommitOffsets = new HashMap<>(); for (Map.Entry<TopicPartition, OffsetManager> tpOffset : offsetManagers.entrySet()) { final OffsetAndMetadata nextCommitOffset = tpOffset.getValue().findNextCommitOffset(commitMetadataManager.getCommitMetadata()); if (nextCommitOffset != null) { nextCommitOffsets.put(tpOffset.getKey(), nextCommitOffset); } } // Commit offsets that are ready to be committed for every topic partition if (!nextCommitOffsets.isEmpty()) { consumer.commitSync(nextCommitOffsets); LOG.debug("Offsets successfully committed to Kafka [{}]", nextCommitOffsets); // Instead of iterating again, it would be possible to commit and update the state for each TopicPartition // in the prior loop, but the multiple network calls should be more expensive than iterating twice over a small loop for (Map.Entry<TopicPartition, OffsetAndMetadata> tpOffset : nextCommitOffsets.entrySet()) { //Update the OffsetManager for each committed partition, and update numUncommittedOffsets final TopicPartition tp = tpOffset.getKey(); long position = consumer.position(tp); long committedOffset = tpOffset.getValue().offset(); if (position < committedOffset) { /* * The position is behind the committed offset. This can happen in some cases, e.g. if a message failed, lots of (more * than max.poll.records) later messages were acked, and the failed message then gets acked. The consumer may only be * part way through "catching up" to where it was when it went back to retry the failed tuple. Skip the consumer forward * to the committed offset. */ LOG.debug("Consumer fell behind committed offset. Catching up. Position was [{}], skipping to [{}]", position, committedOffset); consumer.seek(tp, committedOffset); } /** * In some cases the waitingToEmit list may contain tuples that have just been committed. Drop these. */ List<ConsumerRecord<K, V>> waitingToEmitForTp = waitingToEmit.get(tp); if (waitingToEmitForTp != null) { //Discard the pending records that are already committed waitingToEmit.put(tp, waitingToEmitForTp.stream() .filter(record -> record.offset() >= committedOffset) .collect(Collectors.toCollection(LinkedList::new))); } final OffsetManager offsetManager = offsetManagers.get(tp); offsetManager.commit(tpOffset.getValue()); LOG.debug("[{}] uncommitted offsets for partition [{}] after commit", offsetManager.getNumUncommittedOffsets(), tp); } } else { LOG.trace("No offsets to commit. {}", this); } } // ======== Ack ======= @Override public void ack(Object messageId) { if (!isAtLeastOnceProcessing()) { return; } // Only need to keep track of acked tuples if commits to Kafka are controlled by // tuple acks, which happens only for at-least-once processing semantics final KafkaSpoutMessageId msgId = (KafkaSpoutMessageId) messageId; if (msgId.isNullTuple()) { //a null tuple should be added to the ack list since by definition is a direct ack offsetManagers.get(msgId.getTopicPartition()).addToAckMsgs(msgId); LOG.debug("Received direct ack for message [{}], associated with null tuple", msgId); tupleListener.onAck(msgId); return; } if (!emitted.contains(msgId)) { LOG.debug("Received ack for message [{}], associated with tuple emitted for a ConsumerRecord that " + "came from a topic-partition that this consumer group instance is no longer tracking " + "due to rebalance/partition reassignment. No action taken.", msgId); } else { Validate.isTrue(!retryService.isScheduled(msgId), "The message id " + msgId + " is queued for retry while being acked." + " This should never occur barring errors in the RetryService implementation or the spout code."); offsetManagers.get(msgId.getTopicPartition()).addToAckMsgs(msgId); emitted.remove(msgId); } tupleListener.onAck(msgId); } // ======== Fail ======= @Override public void fail(Object messageId) { if (!isAtLeastOnceProcessing()) { return; } // Only need to keep track of failed tuples if commits to Kafka are controlled by // tuple acks, which happens only for at-least-once processing semantics final KafkaSpoutMessageId msgId = (KafkaSpoutMessageId) messageId; if (!emitted.contains(msgId)) { LOG.debug("Received fail for tuple this spout is no longer tracking." + " Partitions may have been reassigned. Ignoring message [{}]", msgId); return; } Validate.isTrue(!retryService.isScheduled(msgId), "The message id " + msgId + " is queued for retry while being failed." + " This should never occur barring errors in the RetryService implementation or the spout code."); msgId.incrementNumFails(); if (!retryService.schedule(msgId)) { LOG.debug("Reached maximum number of retries. Message [{}] being marked as acked.", msgId); // this tuple should be removed from emitted only inside the ack() method. This is to ensure // that the OffsetManager for that TopicPartition is updated and allows commit progression tupleListener.onMaxRetryReached(msgId); ack(msgId); } else { tupleListener.onRetry(msgId); emitted.remove(msgId); } } // ======== Activate / Deactivate / Close / Declare Outputs ======= @Override public void activate() { try { refreshAssignment(); } catch (InterruptException e) { throwKafkaConsumerInterruptedException(); } } private void refreshAssignment() { Set<TopicPartition> allPartitions = kafkaSpoutConfig.getTopicFilter().getAllSubscribedPartitions(consumer); List<TopicPartition> allPartitionsSorted = new ArrayList<>(allPartitions); Collections.sort(allPartitionsSorted, TopicPartitionComparator.INSTANCE); Set<TopicPartition> assignedPartitions = kafkaSpoutConfig.getTopicPartitioner() .getPartitionsForThisTask(allPartitionsSorted, context); boolean partitionChanged = topicAssigner.assignPartitions(consumer, assignedPartitions, rebalanceListener); if (partitionChanged && canRegisterMetrics()) { LOG.info("Partitions assignments has changed, updating metrics."); kafkaOffsetMetricManager.registerMetricsForNewTopicPartitions(assignedPartitions); } } @Override public void deactivate() { try { commitIfNecessary(); } catch (InterruptException e) { throwKafkaConsumerInterruptedException(); } } @Override public void close() { try { shutdown(); } catch (InterruptException e) { throwKafkaConsumerInterruptedException(); } } private void commitIfNecessary() { if (isAtLeastOnceProcessing()) { commitOffsetsForAckedTuples(); } } private void shutdown() { try { commitIfNecessary(); } finally { //remove resources admin.close(); consumer.close(); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { RecordTranslator<K, V> translator = kafkaSpoutConfig.getTranslator(); for (String stream : translator.streams()) { declarer.declareStream(stream, translator.getFieldsFor(stream)); } } @Override public String toString() { return "KafkaSpout{" + "offsetManagers =" + offsetManagers + ", emitted=" + emitted + "}"; } @Override public Map<String, Object> getComponentConfiguration() { Map<String, Object> configuration = super.getComponentConfiguration(); if (configuration == null) { configuration = new HashMap<>(); } String configKeyPrefix = "config."; configuration.put(configKeyPrefix + "topics", getTopicsString()); configuration.put(configKeyPrefix + "groupid", kafkaSpoutConfig.getConsumerGroupId()); for (Entry<String, Object> conf : kafkaSpoutConfig.getKafkaProps().entrySet()) { if (conf.getValue() != null && isPrimitiveOrWrapper(conf.getValue().getClass())) { configuration.put(configKeyPrefix + conf.getKey(), conf.getValue()); } else { LOG.debug("Dropping Kafka prop '{}' from component configuration", conf.getKey()); } } return configuration; } private boolean isPrimitiveOrWrapper(Class<?> type) { if (type == null) { return false; } return type.isPrimitive() || isWrapper(type); } private boolean isWrapper(Class<?> type) { return type == Double.class || type == Float.class || type == Long.class || type == Integer.class || type == Short.class || type == Character.class || type == Byte.class || type == Boolean.class || type == String.class; } private String getTopicsString() { return kafkaSpoutConfig.getTopicFilter().getTopicsString(); } private static class PollablePartitionsInfo { private final Set<TopicPartition> pollablePartitions; //The subset of earliest retriable offsets that are on pollable partitions private final Map<TopicPartition, Long> pollableEarliestRetriableOffsets; PollablePartitionsInfo(Set<TopicPartition> pollablePartitions, Map<TopicPartition, Long> earliestRetriableOffsets) { this.pollablePartitions = pollablePartitions; this.pollableEarliestRetriableOffsets = earliestRetriableOffsets.entrySet().stream() .filter(entry -> pollablePartitions.contains(entry.getKey())) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); } public boolean shouldPoll() { return !this.pollablePartitions.isEmpty(); } } @VisibleForTesting KafkaOffsetMetricManager<K, V> getKafkaOffsetMetricManager() { return kafkaOffsetMetricManager; } }
googleads/google-ads-java
36,911
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/KeywordPlanIdeaServiceClient.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.ads.googleads.v19.services; import com.google.ads.googleads.v19.services.stub.KeywordPlanIdeaServiceStub; import com.google.ads.googleads.v19.services.stub.KeywordPlanIdeaServiceStubSettings; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; 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.UnaryCallable; 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: Service to generate keyword ideas. * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * GenerateKeywordHistoricalMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordHistoricalMetrics(request); * } * }</pre> * * <p>Note: close() needs to be called on the KeywordPlanIdeaServiceClient 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> GenerateKeywordIdeas</td> * <td><p> Returns a list of keyword ideas. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() [QuotaError]() [RequestError]()</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> generateKeywordIdeas(GenerateKeywordIdeasRequest 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> generateKeywordIdeasPagedCallable() * <li><p> generateKeywordIdeasCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateKeywordHistoricalMetrics</td> * <td><p> Returns a list of keyword historical metrics. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateKeywordHistoricalMetrics(GenerateKeywordHistoricalMetricsRequest 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> generateKeywordHistoricalMetricsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateAdGroupThemes</td> * <td><p> Returns a list of suggested AdGroups and suggested modifications (text, match type) for the given keywords. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateAdGroupThemes(GenerateAdGroupThemesRequest 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> generateAdGroupThemes(String customerId, List&lt;String&gt; keywords, List&lt;String&gt; adGroups) * </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> generateAdGroupThemesCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateKeywordForecastMetrics</td> * <td><p> Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given campaign. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateKeywordForecastMetrics(GenerateKeywordForecastMetricsRequest 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> generateKeywordForecastMetrics(CampaignToForecast campaign) * </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> generateKeywordForecastMetricsCallable() * </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 KeywordPlanIdeaServiceSettings * 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 * KeywordPlanIdeaServiceSettings keywordPlanIdeaServiceSettings = * KeywordPlanIdeaServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create(keywordPlanIdeaServiceSettings); * }</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 * KeywordPlanIdeaServiceSettings keywordPlanIdeaServiceSettings = * KeywordPlanIdeaServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create(keywordPlanIdeaServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class KeywordPlanIdeaServiceClient implements BackgroundResource { private final KeywordPlanIdeaServiceSettings settings; private final KeywordPlanIdeaServiceStub stub; /** Constructs an instance of KeywordPlanIdeaServiceClient with default settings. */ public static final KeywordPlanIdeaServiceClient create() throws IOException { return create(KeywordPlanIdeaServiceSettings.newBuilder().build()); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, 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 KeywordPlanIdeaServiceClient create(KeywordPlanIdeaServiceSettings settings) throws IOException { return new KeywordPlanIdeaServiceClient(settings); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, using the given stub for making calls. * This is for advanced usage - prefer using create(KeywordPlanIdeaServiceSettings). */ public static final KeywordPlanIdeaServiceClient create(KeywordPlanIdeaServiceStub stub) { return new KeywordPlanIdeaServiceClient(stub); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, 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 KeywordPlanIdeaServiceClient(KeywordPlanIdeaServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((KeywordPlanIdeaServiceStubSettings) settings.getStubSettings()).createStub(); } protected KeywordPlanIdeaServiceClient(KeywordPlanIdeaServiceStub stub) { this.settings = null; this.stub = stub; } public final KeywordPlanIdeaServiceSettings getSettings() { return settings; } public KeywordPlanIdeaServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * for (GenerateKeywordIdeaResult element : * keywordPlanIdeaServiceClient.generateKeywordIdeas(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 GenerateKeywordIdeasPagedResponse generateKeywordIdeas( GenerateKeywordIdeasRequest request) { return generateKeywordIdeasPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordIdeaResult> future = * keywordPlanIdeaServiceClient.generateKeywordIdeasPagedCallable().futureCall(request); * // Do something. * for (GenerateKeywordIdeaResult element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<GenerateKeywordIdeasRequest, GenerateKeywordIdeasPagedResponse> generateKeywordIdeasPagedCallable() { return stub.generateKeywordIdeasPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * while (true) { * GenerateKeywordIdeaResponse response = * keywordPlanIdeaServiceClient.generateKeywordIdeasCallable().call(request); * for (GenerateKeywordIdeaResult element : response.getResultsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse> generateKeywordIdeasCallable() { return stub.generateKeywordIdeasCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword historical metrics. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * GenerateKeywordHistoricalMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordHistoricalMetrics(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 GenerateKeywordHistoricalMetricsResponse generateKeywordHistoricalMetrics( GenerateKeywordHistoricalMetricsRequest request) { return generateKeywordHistoricalMetricsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword historical metrics. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordHistoricalMetricsResponse> future = * keywordPlanIdeaServiceClient * .generateKeywordHistoricalMetricsCallable() * .futureCall(request); * // Do something. * GenerateKeywordHistoricalMetricsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable< GenerateKeywordHistoricalMetricsRequest, GenerateKeywordHistoricalMetricsResponse> generateKeywordHistoricalMetricsCallable() { return stub.generateKeywordHistoricalMetricsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * String customerId = "customerId-1581184615"; * List<String> keywords = new ArrayList<>(); * List<String> adGroups = new ArrayList<>(); * GenerateAdGroupThemesResponse response = * keywordPlanIdeaServiceClient.generateAdGroupThemes(customerId, keywords, adGroups); * } * }</pre> * * @param customerId Required. The ID of the customer. * @param keywords Required. A list of keywords to group into the provided AdGroups. * @param adGroups Required. A list of resource names of AdGroups to group keywords into. Resource * name format: `customers/{customer_id}/adGroups/{ad_group_id}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final GenerateAdGroupThemesResponse generateAdGroupThemes( String customerId, List<String> keywords, List<String> adGroups) { GenerateAdGroupThemesRequest request = GenerateAdGroupThemesRequest.newBuilder() .setCustomerId(customerId) .addAllKeywords(keywords) .addAllAdGroups(adGroups) .build(); return generateAdGroupThemes(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateAdGroupThemesRequest request = * GenerateAdGroupThemesRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .addAllAdGroups(new ArrayList<String>()) * .build(); * GenerateAdGroupThemesResponse response = * keywordPlanIdeaServiceClient.generateAdGroupThemes(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 GenerateAdGroupThemesResponse generateAdGroupThemes( GenerateAdGroupThemesRequest request) { return generateAdGroupThemesCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateAdGroupThemesRequest request = * GenerateAdGroupThemesRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .addAllAdGroups(new ArrayList<String>()) * .build(); * ApiFuture<GenerateAdGroupThemesResponse> future = * keywordPlanIdeaServiceClient.generateAdGroupThemesCallable().futureCall(request); * // Do something. * GenerateAdGroupThemesResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<GenerateAdGroupThemesRequest, GenerateAdGroupThemesResponse> generateAdGroupThemesCallable() { return stub.generateAdGroupThemesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * CampaignToForecast campaign = CampaignToForecast.newBuilder().build(); * GenerateKeywordForecastMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(campaign); * } * }</pre> * * @param campaign Required. The campaign used in the forecast. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final GenerateKeywordForecastMetricsResponse generateKeywordForecastMetrics( CampaignToForecast campaign) { GenerateKeywordForecastMetricsRequest request = GenerateKeywordForecastMetricsRequest.newBuilder().setCampaign(campaign).build(); return generateKeywordForecastMetrics(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordForecastMetricsRequest request = * GenerateKeywordForecastMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setCurrencyCode("currencyCode1004773790") * .setForecastPeriod(DateRange.newBuilder().build()) * .setCampaign(CampaignToForecast.newBuilder().build()) * .build(); * GenerateKeywordForecastMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(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 GenerateKeywordForecastMetricsResponse generateKeywordForecastMetrics( GenerateKeywordForecastMetricsRequest request) { return generateKeywordForecastMetricsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordForecastMetricsRequest request = * GenerateKeywordForecastMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setCurrencyCode("currencyCode1004773790") * .setForecastPeriod(DateRange.newBuilder().build()) * .setCampaign(CampaignToForecast.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordForecastMetricsResponse> future = * keywordPlanIdeaServiceClient.generateKeywordForecastMetricsCallable().futureCall(request); * // Do something. * GenerateKeywordForecastMetricsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable< GenerateKeywordForecastMetricsRequest, GenerateKeywordForecastMetricsResponse> generateKeywordForecastMetricsCallable() { return stub.generateKeywordForecastMetricsCallable(); } @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 GenerateKeywordIdeasPagedResponse extends AbstractPagedListResponse< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage, GenerateKeywordIdeasFixedSizeCollection> { public static ApiFuture<GenerateKeywordIdeasPagedResponse> createAsync( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, ApiFuture<GenerateKeywordIdeaResponse> futureResponse) { ApiFuture<GenerateKeywordIdeasPage> futurePage = GenerateKeywordIdeasPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new GenerateKeywordIdeasPagedResponse(input), MoreExecutors.directExecutor()); } private GenerateKeywordIdeasPagedResponse(GenerateKeywordIdeasPage page) { super(page, GenerateKeywordIdeasFixedSizeCollection.createEmptyCollection()); } } public static class GenerateKeywordIdeasPage extends AbstractPage< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage> { private GenerateKeywordIdeasPage( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, GenerateKeywordIdeaResponse response) { super(context, response); } private static GenerateKeywordIdeasPage createEmptyPage() { return new GenerateKeywordIdeasPage(null, null); } @Override protected GenerateKeywordIdeasPage createPage( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, GenerateKeywordIdeaResponse response) { return new GenerateKeywordIdeasPage(context, response); } @Override public ApiFuture<GenerateKeywordIdeasPage> createPageAsync( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, ApiFuture<GenerateKeywordIdeaResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class GenerateKeywordIdeasFixedSizeCollection extends AbstractFixedSizeCollection< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage, GenerateKeywordIdeasFixedSizeCollection> { private GenerateKeywordIdeasFixedSizeCollection( List<GenerateKeywordIdeasPage> pages, int collectionSize) { super(pages, collectionSize); } private static GenerateKeywordIdeasFixedSizeCollection createEmptyCollection() { return new GenerateKeywordIdeasFixedSizeCollection(null, 0); } @Override protected GenerateKeywordIdeasFixedSizeCollection createCollection( List<GenerateKeywordIdeasPage> pages, int collectionSize) { return new GenerateKeywordIdeasFixedSizeCollection(pages, collectionSize); } } }
googleads/google-ads-java
36,911
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/KeywordPlanIdeaServiceClient.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.ads.googleads.v20.services; import com.google.ads.googleads.v20.services.stub.KeywordPlanIdeaServiceStub; import com.google.ads.googleads.v20.services.stub.KeywordPlanIdeaServiceStubSettings; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; 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.UnaryCallable; 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: Service to generate keyword ideas. * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * GenerateKeywordHistoricalMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordHistoricalMetrics(request); * } * }</pre> * * <p>Note: close() needs to be called on the KeywordPlanIdeaServiceClient 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> GenerateKeywordIdeas</td> * <td><p> Returns a list of keyword ideas. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() [QuotaError]() [RequestError]()</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> generateKeywordIdeas(GenerateKeywordIdeasRequest 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> generateKeywordIdeasPagedCallable() * <li><p> generateKeywordIdeasCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateKeywordHistoricalMetrics</td> * <td><p> Returns a list of keyword historical metrics. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateKeywordHistoricalMetrics(GenerateKeywordHistoricalMetricsRequest 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> generateKeywordHistoricalMetricsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateAdGroupThemes</td> * <td><p> Returns a list of suggested AdGroups and suggested modifications (text, match type) for the given keywords. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateAdGroupThemes(GenerateAdGroupThemesRequest 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> generateAdGroupThemes(String customerId, List&lt;String&gt; keywords, List&lt;String&gt; adGroups) * </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> generateAdGroupThemesCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateKeywordForecastMetrics</td> * <td><p> Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given campaign. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateKeywordForecastMetrics(GenerateKeywordForecastMetricsRequest 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> generateKeywordForecastMetrics(CampaignToForecast campaign) * </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> generateKeywordForecastMetricsCallable() * </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 KeywordPlanIdeaServiceSettings * 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 * KeywordPlanIdeaServiceSettings keywordPlanIdeaServiceSettings = * KeywordPlanIdeaServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create(keywordPlanIdeaServiceSettings); * }</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 * KeywordPlanIdeaServiceSettings keywordPlanIdeaServiceSettings = * KeywordPlanIdeaServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create(keywordPlanIdeaServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class KeywordPlanIdeaServiceClient implements BackgroundResource { private final KeywordPlanIdeaServiceSettings settings; private final KeywordPlanIdeaServiceStub stub; /** Constructs an instance of KeywordPlanIdeaServiceClient with default settings. */ public static final KeywordPlanIdeaServiceClient create() throws IOException { return create(KeywordPlanIdeaServiceSettings.newBuilder().build()); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, 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 KeywordPlanIdeaServiceClient create(KeywordPlanIdeaServiceSettings settings) throws IOException { return new KeywordPlanIdeaServiceClient(settings); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, using the given stub for making calls. * This is for advanced usage - prefer using create(KeywordPlanIdeaServiceSettings). */ public static final KeywordPlanIdeaServiceClient create(KeywordPlanIdeaServiceStub stub) { return new KeywordPlanIdeaServiceClient(stub); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, 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 KeywordPlanIdeaServiceClient(KeywordPlanIdeaServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((KeywordPlanIdeaServiceStubSettings) settings.getStubSettings()).createStub(); } protected KeywordPlanIdeaServiceClient(KeywordPlanIdeaServiceStub stub) { this.settings = null; this.stub = stub; } public final KeywordPlanIdeaServiceSettings getSettings() { return settings; } public KeywordPlanIdeaServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * for (GenerateKeywordIdeaResult element : * keywordPlanIdeaServiceClient.generateKeywordIdeas(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 GenerateKeywordIdeasPagedResponse generateKeywordIdeas( GenerateKeywordIdeasRequest request) { return generateKeywordIdeasPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordIdeaResult> future = * keywordPlanIdeaServiceClient.generateKeywordIdeasPagedCallable().futureCall(request); * // Do something. * for (GenerateKeywordIdeaResult element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<GenerateKeywordIdeasRequest, GenerateKeywordIdeasPagedResponse> generateKeywordIdeasPagedCallable() { return stub.generateKeywordIdeasPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * while (true) { * GenerateKeywordIdeaResponse response = * keywordPlanIdeaServiceClient.generateKeywordIdeasCallable().call(request); * for (GenerateKeywordIdeaResult element : response.getResultsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse> generateKeywordIdeasCallable() { return stub.generateKeywordIdeasCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword historical metrics. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * GenerateKeywordHistoricalMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordHistoricalMetrics(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 GenerateKeywordHistoricalMetricsResponse generateKeywordHistoricalMetrics( GenerateKeywordHistoricalMetricsRequest request) { return generateKeywordHistoricalMetricsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword historical metrics. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordHistoricalMetricsResponse> future = * keywordPlanIdeaServiceClient * .generateKeywordHistoricalMetricsCallable() * .futureCall(request); * // Do something. * GenerateKeywordHistoricalMetricsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable< GenerateKeywordHistoricalMetricsRequest, GenerateKeywordHistoricalMetricsResponse> generateKeywordHistoricalMetricsCallable() { return stub.generateKeywordHistoricalMetricsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * String customerId = "customerId-1581184615"; * List<String> keywords = new ArrayList<>(); * List<String> adGroups = new ArrayList<>(); * GenerateAdGroupThemesResponse response = * keywordPlanIdeaServiceClient.generateAdGroupThemes(customerId, keywords, adGroups); * } * }</pre> * * @param customerId Required. The ID of the customer. * @param keywords Required. A list of keywords to group into the provided AdGroups. * @param adGroups Required. A list of resource names of AdGroups to group keywords into. Resource * name format: `customers/{customer_id}/adGroups/{ad_group_id}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final GenerateAdGroupThemesResponse generateAdGroupThemes( String customerId, List<String> keywords, List<String> adGroups) { GenerateAdGroupThemesRequest request = GenerateAdGroupThemesRequest.newBuilder() .setCustomerId(customerId) .addAllKeywords(keywords) .addAllAdGroups(adGroups) .build(); return generateAdGroupThemes(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateAdGroupThemesRequest request = * GenerateAdGroupThemesRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .addAllAdGroups(new ArrayList<String>()) * .build(); * GenerateAdGroupThemesResponse response = * keywordPlanIdeaServiceClient.generateAdGroupThemes(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 GenerateAdGroupThemesResponse generateAdGroupThemes( GenerateAdGroupThemesRequest request) { return generateAdGroupThemesCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateAdGroupThemesRequest request = * GenerateAdGroupThemesRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .addAllAdGroups(new ArrayList<String>()) * .build(); * ApiFuture<GenerateAdGroupThemesResponse> future = * keywordPlanIdeaServiceClient.generateAdGroupThemesCallable().futureCall(request); * // Do something. * GenerateAdGroupThemesResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<GenerateAdGroupThemesRequest, GenerateAdGroupThemesResponse> generateAdGroupThemesCallable() { return stub.generateAdGroupThemesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * CampaignToForecast campaign = CampaignToForecast.newBuilder().build(); * GenerateKeywordForecastMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(campaign); * } * }</pre> * * @param campaign Required. The campaign used in the forecast. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final GenerateKeywordForecastMetricsResponse generateKeywordForecastMetrics( CampaignToForecast campaign) { GenerateKeywordForecastMetricsRequest request = GenerateKeywordForecastMetricsRequest.newBuilder().setCampaign(campaign).build(); return generateKeywordForecastMetrics(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordForecastMetricsRequest request = * GenerateKeywordForecastMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setCurrencyCode("currencyCode1004773790") * .setForecastPeriod(DateRange.newBuilder().build()) * .setCampaign(CampaignToForecast.newBuilder().build()) * .build(); * GenerateKeywordForecastMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(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 GenerateKeywordForecastMetricsResponse generateKeywordForecastMetrics( GenerateKeywordForecastMetricsRequest request) { return generateKeywordForecastMetricsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordForecastMetricsRequest request = * GenerateKeywordForecastMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setCurrencyCode("currencyCode1004773790") * .setForecastPeriod(DateRange.newBuilder().build()) * .setCampaign(CampaignToForecast.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordForecastMetricsResponse> future = * keywordPlanIdeaServiceClient.generateKeywordForecastMetricsCallable().futureCall(request); * // Do something. * GenerateKeywordForecastMetricsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable< GenerateKeywordForecastMetricsRequest, GenerateKeywordForecastMetricsResponse> generateKeywordForecastMetricsCallable() { return stub.generateKeywordForecastMetricsCallable(); } @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 GenerateKeywordIdeasPagedResponse extends AbstractPagedListResponse< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage, GenerateKeywordIdeasFixedSizeCollection> { public static ApiFuture<GenerateKeywordIdeasPagedResponse> createAsync( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, ApiFuture<GenerateKeywordIdeaResponse> futureResponse) { ApiFuture<GenerateKeywordIdeasPage> futurePage = GenerateKeywordIdeasPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new GenerateKeywordIdeasPagedResponse(input), MoreExecutors.directExecutor()); } private GenerateKeywordIdeasPagedResponse(GenerateKeywordIdeasPage page) { super(page, GenerateKeywordIdeasFixedSizeCollection.createEmptyCollection()); } } public static class GenerateKeywordIdeasPage extends AbstractPage< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage> { private GenerateKeywordIdeasPage( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, GenerateKeywordIdeaResponse response) { super(context, response); } private static GenerateKeywordIdeasPage createEmptyPage() { return new GenerateKeywordIdeasPage(null, null); } @Override protected GenerateKeywordIdeasPage createPage( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, GenerateKeywordIdeaResponse response) { return new GenerateKeywordIdeasPage(context, response); } @Override public ApiFuture<GenerateKeywordIdeasPage> createPageAsync( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, ApiFuture<GenerateKeywordIdeaResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class GenerateKeywordIdeasFixedSizeCollection extends AbstractFixedSizeCollection< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage, GenerateKeywordIdeasFixedSizeCollection> { private GenerateKeywordIdeasFixedSizeCollection( List<GenerateKeywordIdeasPage> pages, int collectionSize) { super(pages, collectionSize); } private static GenerateKeywordIdeasFixedSizeCollection createEmptyCollection() { return new GenerateKeywordIdeasFixedSizeCollection(null, 0); } @Override protected GenerateKeywordIdeasFixedSizeCollection createCollection( List<GenerateKeywordIdeasPage> pages, int collectionSize) { return new GenerateKeywordIdeasFixedSizeCollection(pages, collectionSize); } } }
googleads/google-ads-java
36,911
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/KeywordPlanIdeaServiceClient.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.ads.googleads.v21.services; import com.google.ads.googleads.v21.services.stub.KeywordPlanIdeaServiceStub; import com.google.ads.googleads.v21.services.stub.KeywordPlanIdeaServiceStubSettings; import com.google.api.core.ApiFuture; import com.google.api.core.ApiFutures; 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.UnaryCallable; 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: Service to generate keyword ideas. * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * GenerateKeywordHistoricalMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordHistoricalMetrics(request); * } * }</pre> * * <p>Note: close() needs to be called on the KeywordPlanIdeaServiceClient 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> GenerateKeywordIdeas</td> * <td><p> Returns a list of keyword ideas. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() [QuotaError]() [RequestError]()</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> generateKeywordIdeas(GenerateKeywordIdeasRequest 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> generateKeywordIdeasPagedCallable() * <li><p> generateKeywordIdeasCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateKeywordHistoricalMetrics</td> * <td><p> Returns a list of keyword historical metrics. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateKeywordHistoricalMetrics(GenerateKeywordHistoricalMetricsRequest 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> generateKeywordHistoricalMetricsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateAdGroupThemes</td> * <td><p> Returns a list of suggested AdGroups and suggested modifications (text, match type) for the given keywords. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateAdGroupThemes(GenerateAdGroupThemesRequest 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> generateAdGroupThemes(String customerId, List&lt;String&gt; keywords, List&lt;String&gt; adGroups) * </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> generateAdGroupThemesCallable() * </ul> * </td> * </tr> * <tr> * <td><p> GenerateKeywordForecastMetrics</td> * <td><p> Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given campaign. * <p> List of thrown errors: [AuthenticationError]() [AuthorizationError]() [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]()</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> generateKeywordForecastMetrics(GenerateKeywordForecastMetricsRequest 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> generateKeywordForecastMetrics(CampaignToForecast campaign) * </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> generateKeywordForecastMetricsCallable() * </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 KeywordPlanIdeaServiceSettings * 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 * KeywordPlanIdeaServiceSettings keywordPlanIdeaServiceSettings = * KeywordPlanIdeaServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create(keywordPlanIdeaServiceSettings); * }</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 * KeywordPlanIdeaServiceSettings keywordPlanIdeaServiceSettings = * KeywordPlanIdeaServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create(keywordPlanIdeaServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class KeywordPlanIdeaServiceClient implements BackgroundResource { private final KeywordPlanIdeaServiceSettings settings; private final KeywordPlanIdeaServiceStub stub; /** Constructs an instance of KeywordPlanIdeaServiceClient with default settings. */ public static final KeywordPlanIdeaServiceClient create() throws IOException { return create(KeywordPlanIdeaServiceSettings.newBuilder().build()); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, 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 KeywordPlanIdeaServiceClient create(KeywordPlanIdeaServiceSettings settings) throws IOException { return new KeywordPlanIdeaServiceClient(settings); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, using the given stub for making calls. * This is for advanced usage - prefer using create(KeywordPlanIdeaServiceSettings). */ public static final KeywordPlanIdeaServiceClient create(KeywordPlanIdeaServiceStub stub) { return new KeywordPlanIdeaServiceClient(stub); } /** * Constructs an instance of KeywordPlanIdeaServiceClient, 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 KeywordPlanIdeaServiceClient(KeywordPlanIdeaServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((KeywordPlanIdeaServiceStubSettings) settings.getStubSettings()).createStub(); } protected KeywordPlanIdeaServiceClient(KeywordPlanIdeaServiceStub stub) { this.settings = null; this.stub = stub; } public final KeywordPlanIdeaServiceSettings getSettings() { return settings; } public KeywordPlanIdeaServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * for (GenerateKeywordIdeaResult element : * keywordPlanIdeaServiceClient.generateKeywordIdeas(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 GenerateKeywordIdeasPagedResponse generateKeywordIdeas( GenerateKeywordIdeasRequest request) { return generateKeywordIdeasPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordIdeaResult> future = * keywordPlanIdeaServiceClient.generateKeywordIdeasPagedCallable().futureCall(request); * // Do something. * for (GenerateKeywordIdeaResult element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<GenerateKeywordIdeasRequest, GenerateKeywordIdeasPagedResponse> generateKeywordIdeasPagedCallable() { return stub.generateKeywordIdeasPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword ideas. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [KeywordPlanIdeaError]() * [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordIdeasRequest request = * GenerateKeywordIdeasRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setLanguage("language-1613589672") * .addAllGeoTargetConstants(new ArrayList<String>()) * .setIncludeAdultKeywords(true) * .setPageToken("pageToken873572522") * .setPageSize(883849137) * .addAllKeywordAnnotation( * new ArrayList<KeywordPlanKeywordAnnotationEnum.KeywordPlanKeywordAnnotation>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * while (true) { * GenerateKeywordIdeaResponse response = * keywordPlanIdeaServiceClient.generateKeywordIdeasCallable().call(request); * for (GenerateKeywordIdeaResult element : response.getResultsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse> generateKeywordIdeasCallable() { return stub.generateKeywordIdeasCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword historical metrics. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * GenerateKeywordHistoricalMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordHistoricalMetrics(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 GenerateKeywordHistoricalMetricsResponse generateKeywordHistoricalMetrics( GenerateKeywordHistoricalMetricsRequest request) { return generateKeywordHistoricalMetricsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of keyword historical metrics. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordHistoricalMetricsRequest request = * GenerateKeywordHistoricalMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .setLanguage("language-1613589672") * .setIncludeAdultKeywords(true) * .addAllGeoTargetConstants(new ArrayList<String>()) * .setAggregateMetrics(KeywordPlanAggregateMetrics.newBuilder().build()) * .setHistoricalMetricsOptions(HistoricalMetricsOptions.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordHistoricalMetricsResponse> future = * keywordPlanIdeaServiceClient * .generateKeywordHistoricalMetricsCallable() * .futureCall(request); * // Do something. * GenerateKeywordHistoricalMetricsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable< GenerateKeywordHistoricalMetricsRequest, GenerateKeywordHistoricalMetricsResponse> generateKeywordHistoricalMetricsCallable() { return stub.generateKeywordHistoricalMetricsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * String customerId = "customerId-1581184615"; * List<String> keywords = new ArrayList<>(); * List<String> adGroups = new ArrayList<>(); * GenerateAdGroupThemesResponse response = * keywordPlanIdeaServiceClient.generateAdGroupThemes(customerId, keywords, adGroups); * } * }</pre> * * @param customerId Required. The ID of the customer. * @param keywords Required. A list of keywords to group into the provided AdGroups. * @param adGroups Required. A list of resource names of AdGroups to group keywords into. Resource * name format: `customers/{customer_id}/adGroups/{ad_group_id}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final GenerateAdGroupThemesResponse generateAdGroupThemes( String customerId, List<String> keywords, List<String> adGroups) { GenerateAdGroupThemesRequest request = GenerateAdGroupThemesRequest.newBuilder() .setCustomerId(customerId) .addAllKeywords(keywords) .addAllAdGroups(adGroups) .build(); return generateAdGroupThemes(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateAdGroupThemesRequest request = * GenerateAdGroupThemesRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .addAllAdGroups(new ArrayList<String>()) * .build(); * GenerateAdGroupThemesResponse response = * keywordPlanIdeaServiceClient.generateAdGroupThemes(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 GenerateAdGroupThemesResponse generateAdGroupThemes( GenerateAdGroupThemesRequest request) { return generateAdGroupThemesCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns a list of suggested AdGroups and suggested modifications (text, match type) for the * given keywords. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateAdGroupThemesRequest request = * GenerateAdGroupThemesRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .addAllKeywords(new ArrayList<String>()) * .addAllAdGroups(new ArrayList<String>()) * .build(); * ApiFuture<GenerateAdGroupThemesResponse> future = * keywordPlanIdeaServiceClient.generateAdGroupThemesCallable().futureCall(request); * // Do something. * GenerateAdGroupThemesResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<GenerateAdGroupThemesRequest, GenerateAdGroupThemesResponse> generateAdGroupThemesCallable() { return stub.generateAdGroupThemesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * CampaignToForecast campaign = CampaignToForecast.newBuilder().build(); * GenerateKeywordForecastMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(campaign); * } * }</pre> * * @param campaign Required. The campaign used in the forecast. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final GenerateKeywordForecastMetricsResponse generateKeywordForecastMetrics( CampaignToForecast campaign) { GenerateKeywordForecastMetricsRequest request = GenerateKeywordForecastMetricsRequest.newBuilder().setCampaign(campaign).build(); return generateKeywordForecastMetrics(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordForecastMetricsRequest request = * GenerateKeywordForecastMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setCurrencyCode("currencyCode1004773790") * .setForecastPeriod(DateRange.newBuilder().build()) * .setCampaign(CampaignToForecast.newBuilder().build()) * .build(); * GenerateKeywordForecastMetricsResponse response = * keywordPlanIdeaServiceClient.generateKeywordForecastMetrics(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 GenerateKeywordForecastMetricsResponse generateKeywordForecastMetrics( GenerateKeywordForecastMetricsRequest request) { return generateKeywordForecastMetricsCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns metrics (such as impressions, clicks, total cost) of a keyword forecast for the given * campaign. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() * [CollectionSizeError]() [HeaderError]() [InternalError]() [QuotaError]() [RequestError]() * * <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 (KeywordPlanIdeaServiceClient keywordPlanIdeaServiceClient = * KeywordPlanIdeaServiceClient.create()) { * GenerateKeywordForecastMetricsRequest request = * GenerateKeywordForecastMetricsRequest.newBuilder() * .setCustomerId("customerId-1581184615") * .setCurrencyCode("currencyCode1004773790") * .setForecastPeriod(DateRange.newBuilder().build()) * .setCampaign(CampaignToForecast.newBuilder().build()) * .build(); * ApiFuture<GenerateKeywordForecastMetricsResponse> future = * keywordPlanIdeaServiceClient.generateKeywordForecastMetricsCallable().futureCall(request); * // Do something. * GenerateKeywordForecastMetricsResponse response = future.get(); * } * }</pre> */ public final UnaryCallable< GenerateKeywordForecastMetricsRequest, GenerateKeywordForecastMetricsResponse> generateKeywordForecastMetricsCallable() { return stub.generateKeywordForecastMetricsCallable(); } @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 GenerateKeywordIdeasPagedResponse extends AbstractPagedListResponse< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage, GenerateKeywordIdeasFixedSizeCollection> { public static ApiFuture<GenerateKeywordIdeasPagedResponse> createAsync( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, ApiFuture<GenerateKeywordIdeaResponse> futureResponse) { ApiFuture<GenerateKeywordIdeasPage> futurePage = GenerateKeywordIdeasPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new GenerateKeywordIdeasPagedResponse(input), MoreExecutors.directExecutor()); } private GenerateKeywordIdeasPagedResponse(GenerateKeywordIdeasPage page) { super(page, GenerateKeywordIdeasFixedSizeCollection.createEmptyCollection()); } } public static class GenerateKeywordIdeasPage extends AbstractPage< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage> { private GenerateKeywordIdeasPage( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, GenerateKeywordIdeaResponse response) { super(context, response); } private static GenerateKeywordIdeasPage createEmptyPage() { return new GenerateKeywordIdeasPage(null, null); } @Override protected GenerateKeywordIdeasPage createPage( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, GenerateKeywordIdeaResponse response) { return new GenerateKeywordIdeasPage(context, response); } @Override public ApiFuture<GenerateKeywordIdeasPage> createPageAsync( PageContext< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult> context, ApiFuture<GenerateKeywordIdeaResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class GenerateKeywordIdeasFixedSizeCollection extends AbstractFixedSizeCollection< GenerateKeywordIdeasRequest, GenerateKeywordIdeaResponse, GenerateKeywordIdeaResult, GenerateKeywordIdeasPage, GenerateKeywordIdeasFixedSizeCollection> { private GenerateKeywordIdeasFixedSizeCollection( List<GenerateKeywordIdeasPage> pages, int collectionSize) { super(pages, collectionSize); } private static GenerateKeywordIdeasFixedSizeCollection createEmptyCollection() { return new GenerateKeywordIdeasFixedSizeCollection(null, 0); } @Override protected GenerateKeywordIdeasFixedSizeCollection createCollection( List<GenerateKeywordIdeasPage> pages, int collectionSize) { return new GenerateKeywordIdeasFixedSizeCollection(pages, collectionSize); } } }
googleapis/google-api-java-client-services
36,672
clients/google-api-services-readerrevenuesubscriptionlinking/v1/2.0.0/com/google/api/services/readerrevenuesubscriptionlinking/v1/SubscriptionLinking.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.readerrevenuesubscriptionlinking.v1; /** * Service definition for SubscriptionLinking (v1). * * <p> * readerrevenuesubscriptionlinking.googleapis.com API. * </p> * * <p> * For more information about this service, see the * <a href="https://developers.google.com/news/subscribe/subscription-linking/overview" target="_blank">API Documentation</a> * </p> * * <p> * This service uses {@link SubscriptionLinkingRequestInitializer} to initialize global parameters via its * {@link Builder}. * </p> * * @since 1.3 * @author Google, Inc. */ @SuppressWarnings("javadoc") public class SubscriptionLinking extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( (com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 || (com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 && com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1))) || com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION >= 2, "You are currently running with version %s of google-api-client. " + "You need at least version 1.31.1 of google-api-client to run version " + "2.0.0 of the Reader Revenue Subscription Linking 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://readerrevenuesubscriptionlinking.googleapis.com/"; /** * The default encoded mTLS root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.31 */ public static final String DEFAULT_MTLS_ROOT_URL = "https://readerrevenuesubscriptionlinking.mtls.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = ""; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public SubscriptionLinking(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 */ SubscriptionLinking(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 Publications collection. * * <p>The typical use is:</p> * <pre> * {@code SubscriptionLinking readerrevenuesubscriptionlinking = new SubscriptionLinking(...);} * {@code SubscriptionLinking.Publications.List request = readerrevenuesubscriptionlinking.publications().list(parameters ...)} * </pre> * * @return the resource collection */ public Publications publications() { return new Publications(); } /** * The "publications" collection of methods. */ public class Publications { /** * An accessor for creating requests from the Readers collection. * * <p>The typical use is:</p> * <pre> * {@code SubscriptionLinking readerrevenuesubscriptionlinking = new SubscriptionLinking(...);} * {@code SubscriptionLinking.Readers.List request = readerrevenuesubscriptionlinking.readers().list(parameters ...)} * </pre> * * @return the resource collection */ public Readers readers() { return new Readers(); } /** * The "readers" collection of methods. */ public class Readers { /** * Removes a publication reader, effectively severing the association with a Google user. If `force` * is set to true, any entitlements for this reader will also be deleted. (Otherwise, the request * will only work if the reader has no entitlements.) - If the reader does not exist, return * NOT_FOUND. - Return FAILED_PRECONDITION if the force field is false (or unset) and entitlements * are present. * * Create a request for the method "readers.delete". * * This request holds the parameters needed by the readerrevenuesubscriptionlinking server. After * setting any optional parameters, call the {@link Delete#execute()} method to invoke the remote * operation. * * @param name Required. The resource name of the reader. Format: publications/{publication_id}/readers/{ppid} * @return the request */ public Delete delete(java.lang.String name) throws java.io.IOException { Delete result = new Delete(name); initialize(result); return result; } public class Delete extends SubscriptionLinkingRequest<com.google.api.services.readerrevenuesubscriptionlinking.v1.model.DeleteReaderResponse> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^publications/[^/]+/readers/[^/]+$"); /** * Removes a publication reader, effectively severing the association with a Google user. If * `force` is set to true, any entitlements for this reader will also be deleted. (Otherwise, the * request will only work if the reader has no entitlements.) - If the reader does not exist, * return NOT_FOUND. - Return FAILED_PRECONDITION if the force field is false (or unset) and * entitlements are present. * * Create a request for the method "readers.delete". * * This request holds the parameters needed by the the readerrevenuesubscriptionlinking server. * After setting any optional parameters, call the {@link Delete#execute()} method to invoke the * remote operation. <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The resource name of the reader. Format: publications/{publication_id}/readers/{ppid} * @since 1.13 */ protected Delete(java.lang.String name) { super(SubscriptionLinking.this, "DELETE", REST_PATH, null, com.google.api.services.readerrevenuesubscriptionlinking.v1.model.DeleteReaderResponse.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+$"); } } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The resource name of the reader. Format: * publications/{publication_id}/readers/{ppid} */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The resource name of the reader. Format: publications/{publication_id}/readers/{ppid} */ public java.lang.String getName() { return name; } /** * Required. The resource name of the reader. Format: * publications/{publication_id}/readers/{ppid} */ public Delete setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+$"); } this.name = name; return this; } /** If set to true, any entitlements under the reader will also be purged. */ @com.google.api.client.util.Key private java.lang.Boolean force; /** If set to true, any entitlements under the reader will also be purged. */ public java.lang.Boolean getForce() { return force; } /** If set to true, any entitlements under the reader will also be purged. */ public Delete setForce(java.lang.Boolean force) { this.force = force; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a reader of a publication. Returns NOT_FOUND if the reader does not exist. * * Create a request for the method "readers.get". * * This request holds the parameters needed by the readerrevenuesubscriptionlinking server. After * setting any optional parameters, call the {@link Get#execute()} method to invoke the remote * operation. * * @param name Required. The resource name of the reader. Format: publications/{publication_id}/readers/{ppid} * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends SubscriptionLinkingRequest<com.google.api.services.readerrevenuesubscriptionlinking.v1.model.Reader> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^publications/[^/]+/readers/[^/]+$"); /** * Gets a reader of a publication. Returns NOT_FOUND if the reader does not exist. * * Create a request for the method "readers.get". * * This request holds the parameters needed by the the readerrevenuesubscriptionlinking 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 name Required. The resource name of the reader. Format: publications/{publication_id}/readers/{ppid} * @since 1.13 */ protected Get(java.lang.String name) { super(SubscriptionLinking.this, "GET", REST_PATH, null, com.google.api.services.readerrevenuesubscriptionlinking.v1.model.Reader.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+$"); } } @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 resource name of the reader. Format: * publications/{publication_id}/readers/{ppid} */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The resource name of the reader. Format: publications/{publication_id}/readers/{ppid} */ public java.lang.String getName() { return name; } /** * Required. The resource name of the reader. Format: * publications/{publication_id}/readers/{ppid} */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Gets the reader entitlements for a publication reader. - Returns PERMISSION_DENIED if the caller * does not have access. - Returns NOT_FOUND if the reader does not exist. * * Create a request for the method "readers.getEntitlements". * * This request holds the parameters needed by the readerrevenuesubscriptionlinking server. After * setting any optional parameters, call the {@link GetEntitlements#execute()} method to invoke the * remote operation. * * @param name Required. The name of the reader entitlements to retrieve. Format: * publications/{publication_id}/readers/{reader_id}/entitlements * @return the request */ public GetEntitlements getEntitlements(java.lang.String name) throws java.io.IOException { GetEntitlements result = new GetEntitlements(name); initialize(result); return result; } public class GetEntitlements extends SubscriptionLinkingRequest<com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^publications/[^/]+/readers/[^/]+/entitlements$"); /** * Gets the reader entitlements for a publication reader. - Returns PERMISSION_DENIED if the * caller does not have access. - Returns NOT_FOUND if the reader does not exist. * * Create a request for the method "readers.getEntitlements". * * This request holds the parameters needed by the the readerrevenuesubscriptionlinking server. * After setting any optional parameters, call the {@link GetEntitlements#execute()} method to * invoke the remote operation. <p> {@link GetEntitlements#initialize(com.google.api.client.google * apis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @param name Required. The name of the reader entitlements to retrieve. Format: * publications/{publication_id}/readers/{reader_id}/entitlements * @since 1.13 */ protected GetEntitlements(java.lang.String name) { super(SubscriptionLinking.this, "GET", REST_PATH, null, com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+/entitlements$"); } } @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 GetEntitlements set$Xgafv(java.lang.String $Xgafv) { return (GetEntitlements) super.set$Xgafv($Xgafv); } @Override public GetEntitlements setAccessToken(java.lang.String accessToken) { return (GetEntitlements) super.setAccessToken(accessToken); } @Override public GetEntitlements setAlt(java.lang.String alt) { return (GetEntitlements) super.setAlt(alt); } @Override public GetEntitlements setCallback(java.lang.String callback) { return (GetEntitlements) super.setCallback(callback); } @Override public GetEntitlements setFields(java.lang.String fields) { return (GetEntitlements) super.setFields(fields); } @Override public GetEntitlements setKey(java.lang.String key) { return (GetEntitlements) super.setKey(key); } @Override public GetEntitlements setOauthToken(java.lang.String oauthToken) { return (GetEntitlements) super.setOauthToken(oauthToken); } @Override public GetEntitlements setPrettyPrint(java.lang.Boolean prettyPrint) { return (GetEntitlements) super.setPrettyPrint(prettyPrint); } @Override public GetEntitlements setQuotaUser(java.lang.String quotaUser) { return (GetEntitlements) super.setQuotaUser(quotaUser); } @Override public GetEntitlements setUploadType(java.lang.String uploadType) { return (GetEntitlements) super.setUploadType(uploadType); } @Override public GetEntitlements setUploadProtocol(java.lang.String uploadProtocol) { return (GetEntitlements) super.setUploadProtocol(uploadProtocol); } /** * Required. The name of the reader entitlements to retrieve. Format: * publications/{publication_id}/readers/{reader_id}/entitlements */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The name of the reader entitlements to retrieve. Format: publications/{publication_id}/readers/{reader_id}/entitlements */ public java.lang.String getName() { return name; } /** * Required. The name of the reader entitlements to retrieve. Format: * publications/{publication_id}/readers/{reader_id}/entitlements */ public GetEntitlements setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+/entitlements$"); } this.name = name; return this; } @Override public GetEntitlements set(String parameterName, Object value) { return (GetEntitlements) super.set(parameterName, value); } } /** * Updates the reader entitlements for a publication reader. The entire reader entitlements will be * overwritten by the new reader entitlements in the payload, like a PUT. - Returns * PERMISSION_DENIED if the caller does not have access. - Returns NOT_FOUND if the reader does not * exist. * * Create a request for the method "readers.updateEntitlements". * * This request holds the parameters needed by the readerrevenuesubscriptionlinking server. After * setting any optional parameters, call the {@link UpdateEntitlements#execute()} method to invoke * the remote operation. * * @param name Output only. The resource name of the singleton. * @param content the {@link com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements} * @return the request */ public UpdateEntitlements updateEntitlements(java.lang.String name, com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements content) throws java.io.IOException { UpdateEntitlements result = new UpdateEntitlements(name, content); initialize(result); return result; } public class UpdateEntitlements extends SubscriptionLinkingRequest<com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^publications/[^/]+/readers/[^/]+/entitlements$"); /** * Updates the reader entitlements for a publication reader. The entire reader entitlements will * be overwritten by the new reader entitlements in the payload, like a PUT. - Returns * PERMISSION_DENIED if the caller does not have access. - Returns NOT_FOUND if the reader does * not exist. * * Create a request for the method "readers.updateEntitlements". * * This request holds the parameters needed by the the readerrevenuesubscriptionlinking server. * After setting any optional parameters, call the {@link UpdateEntitlements#execute()} method to * invoke the remote operation. <p> {@link UpdateEntitlements#initialize(com.google.api.client.goo * gleapis.services.AbstractGoogleClientRequest)} must be called to initialize this instance * immediately after invoking the constructor. </p> * * @param name Output only. The resource name of the singleton. * @param content the {@link com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements} * @since 1.13 */ protected UpdateEntitlements(java.lang.String name, com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements content) { super(SubscriptionLinking.this, "PATCH", REST_PATH, content, com.google.api.services.readerrevenuesubscriptionlinking.v1.model.ReaderEntitlements.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+/entitlements$"); } } @Override public UpdateEntitlements set$Xgafv(java.lang.String $Xgafv) { return (UpdateEntitlements) super.set$Xgafv($Xgafv); } @Override public UpdateEntitlements setAccessToken(java.lang.String accessToken) { return (UpdateEntitlements) super.setAccessToken(accessToken); } @Override public UpdateEntitlements setAlt(java.lang.String alt) { return (UpdateEntitlements) super.setAlt(alt); } @Override public UpdateEntitlements setCallback(java.lang.String callback) { return (UpdateEntitlements) super.setCallback(callback); } @Override public UpdateEntitlements setFields(java.lang.String fields) { return (UpdateEntitlements) super.setFields(fields); } @Override public UpdateEntitlements setKey(java.lang.String key) { return (UpdateEntitlements) super.setKey(key); } @Override public UpdateEntitlements setOauthToken(java.lang.String oauthToken) { return (UpdateEntitlements) super.setOauthToken(oauthToken); } @Override public UpdateEntitlements setPrettyPrint(java.lang.Boolean prettyPrint) { return (UpdateEntitlements) super.setPrettyPrint(prettyPrint); } @Override public UpdateEntitlements setQuotaUser(java.lang.String quotaUser) { return (UpdateEntitlements) super.setQuotaUser(quotaUser); } @Override public UpdateEntitlements setUploadType(java.lang.String uploadType) { return (UpdateEntitlements) super.setUploadType(uploadType); } @Override public UpdateEntitlements setUploadProtocol(java.lang.String uploadProtocol) { return (UpdateEntitlements) super.setUploadProtocol(uploadProtocol); } /** Output only. The resource name of the singleton. */ @com.google.api.client.util.Key private java.lang.String name; /** Output only. The resource name of the singleton. */ public java.lang.String getName() { return name; } /** Output only. The resource name of the singleton. */ public UpdateEntitlements setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^publications/[^/]+/readers/[^/]+/entitlements$"); } this.name = name; return this; } /** Optional. The list of fields to update. Defaults to all fields. */ @com.google.api.client.util.Key private String updateMask; /** Optional. The list of fields to update. Defaults to all fields. */ public String getUpdateMask() { return updateMask; } /** Optional. The list of fields to update. Defaults to all fields. */ public UpdateEntitlements setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public UpdateEntitlements set(String parameterName, Object value) { return (UpdateEntitlements) super.set(parameterName, value); } } } } /** * Builder for {@link SubscriptionLinking}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) { // If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint. // If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS. // Use the regular endpoint for all other cases. String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT"); useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint; if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) { return DEFAULT_MTLS_ROOT_URL; } return DEFAULT_ROOT_URL; } /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, Builder.chooseEndpoint(transport), DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link SubscriptionLinking}. */ @Override public SubscriptionLinking build() { return new SubscriptionLinking(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 SubscriptionLinkingRequestInitializer}. * * @since 1.12 */ public Builder setSubscriptionLinkingRequestInitializer( SubscriptionLinkingRequestInitializer subscriptionlinkingRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(subscriptionlinkingRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setUniverseDomain(String universeDomain) { return (Builder) super.setUniverseDomain(universeDomain); } } }
googleapis/google-cloud-java
36,529
java-datacatalog/proto-google-cloud-datacatalog-v1/src/main/java/com/google/cloud/datacatalog/v1/ExportTaxonomiesRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datacatalog/v1/policytagmanagerserialization.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datacatalog.v1; /** * * * <pre> * Request message for * [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. * </pre> * * Protobuf type {@code google.cloud.datacatalog.v1.ExportTaxonomiesRequest} */ public final class ExportTaxonomiesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1.ExportTaxonomiesRequest) ExportTaxonomiesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ExportTaxonomiesRequest.newBuilder() to construct. private ExportTaxonomiesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExportTaxonomiesRequest() { parent_ = ""; taxonomies_ = com.google.protobuf.LazyStringArrayList.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ExportTaxonomiesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto .internal_static_google_cloud_datacatalog_v1_ExportTaxonomiesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto .internal_static_google_cloud_datacatalog_v1_ExportTaxonomiesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.class, com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.Builder.class); } private int destinationCase_ = 0; @SuppressWarnings("serial") private java.lang.Object destination_; public enum DestinationCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { SERIALIZED_TAXONOMIES(3), DESTINATION_NOT_SET(0); private final int value; private DestinationCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static DestinationCase valueOf(int value) { return forNumber(value); } public static DestinationCase forNumber(int value) { switch (value) { case 3: return SERIALIZED_TAXONOMIES; case 0: return DESTINATION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public DestinationCase getDestinationCase() { return DestinationCase.forNumber(destinationCase_); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Resource name of the project that the exported taxonomies belong * to. * </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. Resource name of the project that the exported taxonomies belong * to. * </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 TAXONOMIES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private com.google.protobuf.LazyStringArrayList taxonomies_ = com.google.protobuf.LazyStringArrayList.emptyList(); /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return A list containing the taxonomies. */ public com.google.protobuf.ProtocolStringList getTaxonomiesList() { return taxonomies_; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The count of taxonomies. */ public int getTaxonomiesCount() { return taxonomies_.size(); } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the element to return. * @return The taxonomies at the given index. */ public java.lang.String getTaxonomies(int index) { return taxonomies_.get(index); } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the value to return. * @return The bytes of the taxonomies at the given index. */ public com.google.protobuf.ByteString getTaxonomiesBytes(int index) { return taxonomies_.getByteString(index); } public static final int SERIALIZED_TAXONOMIES_FIELD_NUMBER = 3; /** * * * <pre> * Serialized export taxonomies that contain all the policy * tags as nested protocol buffers. * </pre> * * <code>bool serialized_taxonomies = 3;</code> * * @return Whether the serializedTaxonomies field is set. */ @java.lang.Override public boolean hasSerializedTaxonomies() { return destinationCase_ == 3; } /** * * * <pre> * Serialized export taxonomies that contain all the policy * tags as nested protocol buffers. * </pre> * * <code>bool serialized_taxonomies = 3;</code> * * @return The serializedTaxonomies. */ @java.lang.Override public boolean getSerializedTaxonomies() { if (destinationCase_ == 3) { return (java.lang.Boolean) destination_; } return false; } 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_); } for (int i = 0; i < taxonomies_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, taxonomies_.getRaw(i)); } if (destinationCase_ == 3) { output.writeBool(3, (boolean) ((java.lang.Boolean) destination_)); } 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_); } { int dataSize = 0; for (int i = 0; i < taxonomies_.size(); i++) { dataSize += computeStringSizeNoTag(taxonomies_.getRaw(i)); } size += dataSize; size += 1 * getTaxonomiesList().size(); } if (destinationCase_ == 3) { size += com.google.protobuf.CodedOutputStream.computeBoolSize( 3, (boolean) ((java.lang.Boolean) destination_)); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest)) { return super.equals(obj); } com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest other = (com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getTaxonomiesList().equals(other.getTaxonomiesList())) return false; if (!getDestinationCase().equals(other.getDestinationCase())) return false; switch (destinationCase_) { case 3: if (getSerializedTaxonomies() != other.getSerializedTaxonomies()) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (getTaxonomiesCount() > 0) { hash = (37 * hash) + TAXONOMIES_FIELD_NUMBER; hash = (53 * hash) + getTaxonomiesList().hashCode(); } switch (destinationCase_) { case 3: hash = (37 * hash) + SERIALIZED_TAXONOMIES_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSerializedTaxonomies()); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest 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 * [ExportTaxonomies][google.cloud.datacatalog.v1.PolicyTagManagerSerialization.ExportTaxonomies]. * </pre> * * Protobuf type {@code google.cloud.datacatalog.v1.ExportTaxonomiesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1.ExportTaxonomiesRequest) com.google.cloud.datacatalog.v1.ExportTaxonomiesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto .internal_static_google_cloud_datacatalog_v1_ExportTaxonomiesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto .internal_static_google_cloud_datacatalog_v1_ExportTaxonomiesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.class, com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.Builder.class); } // Construct using com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; taxonomies_ = com.google.protobuf.LazyStringArrayList.emptyList(); destinationCase_ = 0; destination_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datacatalog.v1.PolicyTagManagerSerializationProto .internal_static_google_cloud_datacatalog_v1_ExportTaxonomiesRequest_descriptor; } @java.lang.Override public com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest getDefaultInstanceForType() { return com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest build() { com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest buildPartial() { com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest result = new com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { taxonomies_.makeImmutable(); result.taxonomies_ = taxonomies_; } } private void buildPartialOneofs( com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest result) { result.destinationCase_ = destinationCase_; result.destination_ = this.destination_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest) { return mergeFrom((com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest other) { if (other == com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.taxonomies_.isEmpty()) { if (taxonomies_.isEmpty()) { taxonomies_ = other.taxonomies_; bitField0_ |= 0x00000002; } else { ensureTaxonomiesIsMutable(); taxonomies_.addAll(other.taxonomies_); } onChanged(); } switch (other.getDestinationCase()) { case SERIALIZED_TAXONOMIES: { setSerializedTaxonomies(other.getSerializedTaxonomies()); break; } case DESTINATION_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); ensureTaxonomiesIsMutable(); taxonomies_.add(s); break; } // case 18 case 24: { destination_ = input.readBool(); destinationCase_ = 3; 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 destinationCase_ = 0; private java.lang.Object destination_; public DestinationCase getDestinationCase() { return DestinationCase.forNumber(destinationCase_); } public Builder clearDestination() { destinationCase_ = 0; destination_ = null; onChanged(); return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Resource name of the project that the exported taxonomies belong * to. * </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. Resource name of the project that the exported taxonomies belong * to. * </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. Resource name of the project that the exported taxonomies belong * to. * </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. Resource name of the project that the exported taxonomies belong * to. * </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. Resource name of the project that the exported taxonomies belong * to. * </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.protobuf.LazyStringArrayList taxonomies_ = com.google.protobuf.LazyStringArrayList.emptyList(); private void ensureTaxonomiesIsMutable() { if (!taxonomies_.isModifiable()) { taxonomies_ = new com.google.protobuf.LazyStringArrayList(taxonomies_); } bitField0_ |= 0x00000002; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return A list containing the taxonomies. */ public com.google.protobuf.ProtocolStringList getTaxonomiesList() { taxonomies_.makeImmutable(); return taxonomies_; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The count of taxonomies. */ public int getTaxonomiesCount() { return taxonomies_.size(); } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the element to return. * @return The taxonomies at the given index. */ public java.lang.String getTaxonomies(int index) { return taxonomies_.get(index); } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param index The index of the value to return. * @return The bytes of the taxonomies at the given index. */ public com.google.protobuf.ByteString getTaxonomiesBytes(int index) { return taxonomies_.getByteString(index); } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param index The index to set the value at. * @param value The taxonomies to set. * @return This builder for chaining. */ public Builder setTaxonomies(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTaxonomiesIsMutable(); taxonomies_.set(index, value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The taxonomies to add. * @return This builder for chaining. */ public Builder addTaxonomies(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTaxonomiesIsMutable(); taxonomies_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param values The taxonomies to add. * @return This builder for chaining. */ public Builder addAllTaxonomies(java.lang.Iterable<java.lang.String> values) { ensureTaxonomiesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, taxonomies_); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearTaxonomies() { taxonomies_ = com.google.protobuf.LazyStringArrayList.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); ; onChanged(); return this; } /** * * * <pre> * Required. Resource names of the taxonomies to export. * </pre> * * <code> * repeated string taxonomies = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes of the taxonomies to add. * @return This builder for chaining. */ public Builder addTaxonomiesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureTaxonomiesIsMutable(); taxonomies_.add(value); bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Serialized export taxonomies that contain all the policy * tags as nested protocol buffers. * </pre> * * <code>bool serialized_taxonomies = 3;</code> * * @return Whether the serializedTaxonomies field is set. */ public boolean hasSerializedTaxonomies() { return destinationCase_ == 3; } /** * * * <pre> * Serialized export taxonomies that contain all the policy * tags as nested protocol buffers. * </pre> * * <code>bool serialized_taxonomies = 3;</code> * * @return The serializedTaxonomies. */ public boolean getSerializedTaxonomies() { if (destinationCase_ == 3) { return (java.lang.Boolean) destination_; } return false; } /** * * * <pre> * Serialized export taxonomies that contain all the policy * tags as nested protocol buffers. * </pre> * * <code>bool serialized_taxonomies = 3;</code> * * @param value The serializedTaxonomies to set. * @return This builder for chaining. */ public Builder setSerializedTaxonomies(boolean value) { destinationCase_ = 3; destination_ = value; onChanged(); return this; } /** * * * <pre> * Serialized export taxonomies that contain all the policy * tags as nested protocol buffers. * </pre> * * <code>bool serialized_taxonomies = 3;</code> * * @return This builder for chaining. */ public Builder clearSerializedTaxonomies() { if (destinationCase_ == 3) { destinationCase_ = 0; destination_ = null; onChanged(); } return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.datacatalog.v1.ExportTaxonomiesRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1.ExportTaxonomiesRequest) private static final com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest(); } public static com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExportTaxonomiesRequest> PARSER = new com.google.protobuf.AbstractParser<ExportTaxonomiesRequest>() { @java.lang.Override public ExportTaxonomiesRequest 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<ExportTaxonomiesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExportTaxonomiesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datacatalog.v1.ExportTaxonomiesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,581
java-automl/proto-google-cloud-automl-v1beta1/src/main/java/com/google/cloud/automl/v1beta1/ListTableSpecsResponse.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/automl/v1beta1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.automl.v1beta1; /** * * * <pre> * Response message for [AutoMl.ListTableSpecs][google.cloud.automl.v1beta1.AutoMl.ListTableSpecs]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.ListTableSpecsResponse} */ public final class ListTableSpecsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.automl.v1beta1.ListTableSpecsResponse) ListTableSpecsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListTableSpecsResponse.newBuilder() to construct. private ListTableSpecsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListTableSpecsResponse() { tableSpecs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListTableSpecsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListTableSpecsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListTableSpecsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.ListTableSpecsResponse.class, com.google.cloud.automl.v1beta1.ListTableSpecsResponse.Builder.class); } public static final int TABLE_SPECS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.automl.v1beta1.TableSpec> tableSpecs_; /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.automl.v1beta1.TableSpec> getTableSpecsList() { return tableSpecs_; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.automl.v1beta1.TableSpecOrBuilder> getTableSpecsOrBuilderList() { return tableSpecs_; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ @java.lang.Override public int getTableSpecsCount() { return tableSpecs_.size(); } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ @java.lang.Override public com.google.cloud.automl.v1beta1.TableSpec getTableSpecs(int index) { return tableSpecs_.get(index); } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ @java.lang.Override public com.google.cloud.automl.v1beta1.TableSpecOrBuilder getTableSpecsOrBuilder(int index) { return tableSpecs_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < tableSpecs_.size(); i++) { output.writeMessage(1, tableSpecs_.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 < tableSpecs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, tableSpecs_.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.automl.v1beta1.ListTableSpecsResponse)) { return super.equals(obj); } com.google.cloud.automl.v1beta1.ListTableSpecsResponse other = (com.google.cloud.automl.v1beta1.ListTableSpecsResponse) obj; if (!getTableSpecsList().equals(other.getTableSpecsList())) 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 (getTableSpecsCount() > 0) { hash = (37 * hash) + TABLE_SPECS_FIELD_NUMBER; hash = (53 * hash) + getTableSpecsList().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.automl.v1beta1.ListTableSpecsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse 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.automl.v1beta1.ListTableSpecsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse 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.automl.v1beta1.ListTableSpecsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse 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.automl.v1beta1.ListTableSpecsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse 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.automl.v1beta1.ListTableSpecsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse 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.automl.v1beta1.ListTableSpecsResponse 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 [AutoMl.ListTableSpecs][google.cloud.automl.v1beta1.AutoMl.ListTableSpecs]. * </pre> * * Protobuf type {@code google.cloud.automl.v1beta1.ListTableSpecsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.automl.v1beta1.ListTableSpecsResponse) com.google.cloud.automl.v1beta1.ListTableSpecsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListTableSpecsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListTableSpecsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.automl.v1beta1.ListTableSpecsResponse.class, com.google.cloud.automl.v1beta1.ListTableSpecsResponse.Builder.class); } // Construct using com.google.cloud.automl.v1beta1.ListTableSpecsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (tableSpecsBuilder_ == null) { tableSpecs_ = java.util.Collections.emptyList(); } else { tableSpecs_ = null; tableSpecsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.automl.v1beta1.AutoMlProto .internal_static_google_cloud_automl_v1beta1_ListTableSpecsResponse_descriptor; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListTableSpecsResponse getDefaultInstanceForType() { return com.google.cloud.automl.v1beta1.ListTableSpecsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.automl.v1beta1.ListTableSpecsResponse build() { com.google.cloud.automl.v1beta1.ListTableSpecsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListTableSpecsResponse buildPartial() { com.google.cloud.automl.v1beta1.ListTableSpecsResponse result = new com.google.cloud.automl.v1beta1.ListTableSpecsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.automl.v1beta1.ListTableSpecsResponse result) { if (tableSpecsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { tableSpecs_ = java.util.Collections.unmodifiableList(tableSpecs_); bitField0_ = (bitField0_ & ~0x00000001); } result.tableSpecs_ = tableSpecs_; } else { result.tableSpecs_ = tableSpecsBuilder_.build(); } } private void buildPartial0(com.google.cloud.automl.v1beta1.ListTableSpecsResponse 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.automl.v1beta1.ListTableSpecsResponse) { return mergeFrom((com.google.cloud.automl.v1beta1.ListTableSpecsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.automl.v1beta1.ListTableSpecsResponse other) { if (other == com.google.cloud.automl.v1beta1.ListTableSpecsResponse.getDefaultInstance()) return this; if (tableSpecsBuilder_ == null) { if (!other.tableSpecs_.isEmpty()) { if (tableSpecs_.isEmpty()) { tableSpecs_ = other.tableSpecs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTableSpecsIsMutable(); tableSpecs_.addAll(other.tableSpecs_); } onChanged(); } } else { if (!other.tableSpecs_.isEmpty()) { if (tableSpecsBuilder_.isEmpty()) { tableSpecsBuilder_.dispose(); tableSpecsBuilder_ = null; tableSpecs_ = other.tableSpecs_; bitField0_ = (bitField0_ & ~0x00000001); tableSpecsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getTableSpecsFieldBuilder() : null; } else { tableSpecsBuilder_.addAllMessages(other.tableSpecs_); } } } 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.automl.v1beta1.TableSpec m = input.readMessage( com.google.cloud.automl.v1beta1.TableSpec.parser(), extensionRegistry); if (tableSpecsBuilder_ == null) { ensureTableSpecsIsMutable(); tableSpecs_.add(m); } else { tableSpecsBuilder_.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.automl.v1beta1.TableSpec> tableSpecs_ = java.util.Collections.emptyList(); private void ensureTableSpecsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { tableSpecs_ = new java.util.ArrayList<com.google.cloud.automl.v1beta1.TableSpec>(tableSpecs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.automl.v1beta1.TableSpec, com.google.cloud.automl.v1beta1.TableSpec.Builder, com.google.cloud.automl.v1beta1.TableSpecOrBuilder> tableSpecsBuilder_; /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public java.util.List<com.google.cloud.automl.v1beta1.TableSpec> getTableSpecsList() { if (tableSpecsBuilder_ == null) { return java.util.Collections.unmodifiableList(tableSpecs_); } else { return tableSpecsBuilder_.getMessageList(); } } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public int getTableSpecsCount() { if (tableSpecsBuilder_ == null) { return tableSpecs_.size(); } else { return tableSpecsBuilder_.getCount(); } } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.TableSpec getTableSpecs(int index) { if (tableSpecsBuilder_ == null) { return tableSpecs_.get(index); } else { return tableSpecsBuilder_.getMessage(index); } } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder setTableSpecs(int index, com.google.cloud.automl.v1beta1.TableSpec value) { if (tableSpecsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTableSpecsIsMutable(); tableSpecs_.set(index, value); onChanged(); } else { tableSpecsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder setTableSpecs( int index, com.google.cloud.automl.v1beta1.TableSpec.Builder builderForValue) { if (tableSpecsBuilder_ == null) { ensureTableSpecsIsMutable(); tableSpecs_.set(index, builderForValue.build()); onChanged(); } else { tableSpecsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder addTableSpecs(com.google.cloud.automl.v1beta1.TableSpec value) { if (tableSpecsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTableSpecsIsMutable(); tableSpecs_.add(value); onChanged(); } else { tableSpecsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder addTableSpecs(int index, com.google.cloud.automl.v1beta1.TableSpec value) { if (tableSpecsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureTableSpecsIsMutable(); tableSpecs_.add(index, value); onChanged(); } else { tableSpecsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder addTableSpecs( com.google.cloud.automl.v1beta1.TableSpec.Builder builderForValue) { if (tableSpecsBuilder_ == null) { ensureTableSpecsIsMutable(); tableSpecs_.add(builderForValue.build()); onChanged(); } else { tableSpecsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder addTableSpecs( int index, com.google.cloud.automl.v1beta1.TableSpec.Builder builderForValue) { if (tableSpecsBuilder_ == null) { ensureTableSpecsIsMutable(); tableSpecs_.add(index, builderForValue.build()); onChanged(); } else { tableSpecsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder addAllTableSpecs( java.lang.Iterable<? extends com.google.cloud.automl.v1beta1.TableSpec> values) { if (tableSpecsBuilder_ == null) { ensureTableSpecsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, tableSpecs_); onChanged(); } else { tableSpecsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder clearTableSpecs() { if (tableSpecsBuilder_ == null) { tableSpecs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { tableSpecsBuilder_.clear(); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public Builder removeTableSpecs(int index) { if (tableSpecsBuilder_ == null) { ensureTableSpecsIsMutable(); tableSpecs_.remove(index); onChanged(); } else { tableSpecsBuilder_.remove(index); } return this; } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.TableSpec.Builder getTableSpecsBuilder(int index) { return getTableSpecsFieldBuilder().getBuilder(index); } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.TableSpecOrBuilder getTableSpecsOrBuilder(int index) { if (tableSpecsBuilder_ == null) { return tableSpecs_.get(index); } else { return tableSpecsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public java.util.List<? extends com.google.cloud.automl.v1beta1.TableSpecOrBuilder> getTableSpecsOrBuilderList() { if (tableSpecsBuilder_ != null) { return tableSpecsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(tableSpecs_); } } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.TableSpec.Builder addTableSpecsBuilder() { return getTableSpecsFieldBuilder() .addBuilder(com.google.cloud.automl.v1beta1.TableSpec.getDefaultInstance()); } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public com.google.cloud.automl.v1beta1.TableSpec.Builder addTableSpecsBuilder(int index) { return getTableSpecsFieldBuilder() .addBuilder(index, com.google.cloud.automl.v1beta1.TableSpec.getDefaultInstance()); } /** * * * <pre> * The table specs read. * </pre> * * <code>repeated .google.cloud.automl.v1beta1.TableSpec table_specs = 1;</code> */ public java.util.List<com.google.cloud.automl.v1beta1.TableSpec.Builder> getTableSpecsBuilderList() { return getTableSpecsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.automl.v1beta1.TableSpec, com.google.cloud.automl.v1beta1.TableSpec.Builder, com.google.cloud.automl.v1beta1.TableSpecOrBuilder> getTableSpecsFieldBuilder() { if (tableSpecsBuilder_ == null) { tableSpecsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.automl.v1beta1.TableSpec, com.google.cloud.automl.v1beta1.TableSpec.Builder, com.google.cloud.automl.v1beta1.TableSpecOrBuilder>( tableSpecs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); tableSpecs_ = null; } return tableSpecsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve next page of results. * Pass to [ListTableSpecsRequest.page_token][google.cloud.automl.v1beta1.ListTableSpecsRequest.page_token] to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.automl.v1beta1.ListTableSpecsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.automl.v1beta1.ListTableSpecsResponse) private static final com.google.cloud.automl.v1beta1.ListTableSpecsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.automl.v1beta1.ListTableSpecsResponse(); } public static com.google.cloud.automl.v1beta1.ListTableSpecsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListTableSpecsResponse> PARSER = new com.google.protobuf.AbstractParser<ListTableSpecsResponse>() { @java.lang.Override public ListTableSpecsResponse 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<ListTableSpecsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListTableSpecsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.automl.v1beta1.ListTableSpecsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/myfaces
36,531
impl/src/main/java/org/apache/myfaces/renderkit/html/HtmlResponseWriterImpl.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.myfaces.renderkit.html; import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import jakarta.el.ValueExpression; import jakarta.faces.FacesException; import jakarta.faces.component.UIComponent; import jakarta.faces.context.FacesContext; import jakarta.faces.context.ResponseWriter; import jakarta.faces.render.Renderer; import org.apache.myfaces.config.webparameters.MyfacesConfig; import org.apache.myfaces.core.api.shared.ComponentUtils; import org.apache.myfaces.renderkit.ContentTypeUtils; import org.apache.myfaces.renderkit.html.util.UnicodeEncoder; import org.apache.myfaces.util.CommentUtils; import org.apache.myfaces.util.lang.StreamCharBuffer; import org.apache.myfaces.renderkit.html.util.HTML; import org.apache.myfaces.renderkit.html.util.HTMLEncoder; import org.apache.myfaces.core.api.shared.lang.Assert; public class HtmlResponseWriterImpl extends ResponseWriter { private static final Logger log = Logger.getLogger(HtmlResponseWriterImpl.class.getName()); private static final String DEFAULT_CONTENT_TYPE = "text/html"; private static final String DEFAULT_CHARACTER_ENCODING = "ISO-8859-1"; private static final String UTF8 = "UTF-8"; private static final String APPLICATION_XML_CONTENT_TYPE = "application/xml"; private static final String TEXT_XML_CONTENT_TYPE = "text/xml"; private static final String CDATA_START = "<![CDATA[ \n"; private static final String CDATA_START_NO_LINE_RETURN = "<![CDATA["; private static final String COMMENT_START = "<!--\n"; private static final String CDATA_COMMENT_START = "//<![CDATA[ \n"; private static final String CDATA_COMMENT_END = "\n//]]>"; private static final String CDATA_END = "\n]]>"; private static final String CDATA_END_NO_LINE_RETURN = "]]>"; private static final String COMMENT_COMMENT_END = "\n//-->"; private static final String COMMENT_END = "\n-->"; static private final String[][] EMPTY_ELEMENT_ARR = new String[256][]; static private final String[] A_NAMES = new String[] { "area", }; static private final String[] B_NAMES = new String[] { "br", "base", "basefont", }; static private final String[] C_NAMES = new String[] { "col", }; static private final String[] E_NAMES = new String[] { "embed", }; static private final String[] F_NAMES = new String[] { "frame", }; static private final String[] H_NAMES = new String[] { "hr", }; static private final String[] I_NAMES = new String[] { "img", "input", "isindex", }; static private final String[] L_NAMES = new String[] { "link", }; static private final String[] M_NAMES = new String[] { "meta", }; static private final String[] P_NAMES = new String[] { "param", }; static { EMPTY_ELEMENT_ARR['a'] = A_NAMES; EMPTY_ELEMENT_ARR['A'] = A_NAMES; EMPTY_ELEMENT_ARR['b'] = B_NAMES; EMPTY_ELEMENT_ARR['B'] = B_NAMES; EMPTY_ELEMENT_ARR['c'] = C_NAMES; EMPTY_ELEMENT_ARR['C'] = C_NAMES; EMPTY_ELEMENT_ARR['e'] = E_NAMES; EMPTY_ELEMENT_ARR['E'] = E_NAMES; EMPTY_ELEMENT_ARR['f'] = F_NAMES; EMPTY_ELEMENT_ARR['F'] = F_NAMES; EMPTY_ELEMENT_ARR['h'] = H_NAMES; EMPTY_ELEMENT_ARR['H'] = H_NAMES; EMPTY_ELEMENT_ARR['i'] = I_NAMES; EMPTY_ELEMENT_ARR['I'] = I_NAMES; EMPTY_ELEMENT_ARR['l'] = L_NAMES; EMPTY_ELEMENT_ARR['L'] = L_NAMES; EMPTY_ELEMENT_ARR['m'] = M_NAMES; EMPTY_ELEMENT_ARR['M'] = M_NAMES; EMPTY_ELEMENT_ARR['p'] = P_NAMES; EMPTY_ELEMENT_ARR['P'] = P_NAMES; } /** * The writer used as output, or in other words, the one passed on the constructor */ private Writer _outputWriter; /** * The writer we are using to store data. */ private Writer _currentWriter; /** * The writer used to buffer script and style content */ private StreamCharBuffer _buffer; private String _contentType; private String _writerContentTypeMode; /** * This var prevents check if the contentType is for xhtml multiple times. */ private boolean _isXhtmlContentType; /** * Indicate the current response writer should not close automatically html elements * and let the writer close them. */ private boolean _useStraightXml; private String _characterEncoding; private boolean _wrapScriptContentWithXmlCommentTag; private boolean _isUTF8; private String _startElementName; private boolean _isInsideScript = false; private boolean _isStyle = false; private Boolean _isTextArea; private UIComponent _startElementUIComponent; private boolean _startTagOpen; private Map<String, Object> _passThroughAttributesMap; private FacesContext _facesContext; private boolean _cdataOpen; private List<String> _startedChangedElements; private List<Integer> _startedElementsCount; public HtmlResponseWriterImpl(Writer writer, String contentType, String characterEncoding) { this(writer,contentType,characterEncoding,true); } public HtmlResponseWriterImpl(Writer writer, String contentType, String characterEncoding, boolean wrapScriptContentWithXmlCommentTag) { this(writer,contentType, characterEncoding, wrapScriptContentWithXmlCommentTag, contentType != null && ContentTypeUtils.isXHTMLContentType(contentType) ? ContentTypeUtils.XHTML_CONTENT_TYPE : ContentTypeUtils.HTML_CONTENT_TYPE); } public HtmlResponseWriterImpl(Writer writer, String contentType, String characterEncoding, boolean wrapScriptContentWithXmlCommentTag, String writerContentTypeMode) throws FacesException { _outputWriter = writer; //The current writer to be used is the one used as output _currentWriter = _outputWriter; _wrapScriptContentWithXmlCommentTag = wrapScriptContentWithXmlCommentTag; _contentType = contentType; if (_contentType == null) { if (log.isLoggable(Level.FINE)) { log.fine("No content type given, using default content type " + DEFAULT_CONTENT_TYPE); } _contentType = DEFAULT_CONTENT_TYPE; } _writerContentTypeMode = writerContentTypeMode; _isXhtmlContentType = writerContentTypeMode.contains(ContentTypeUtils.XHTML_CONTENT_TYPE); _useStraightXml = _isXhtmlContentType && (_contentType.contains(APPLICATION_XML_CONTENT_TYPE) || _contentType.contains(TEXT_XML_CONTENT_TYPE)); if (characterEncoding == null) { if (log.isLoggable(Level.FINE)) { log.fine("No character encoding given, using default character encoding " + DEFAULT_CHARACTER_ENCODING); } _characterEncoding = DEFAULT_CHARACTER_ENCODING; } else { // canonize to uppercase, that's the standard format _characterEncoding = characterEncoding.toUpperCase(); // Check if encoding is valid by javadoc of RenderKit.createResponseWriter() if (!Charset.isSupported(_characterEncoding)) { throw new IllegalArgumentException("Encoding "+_characterEncoding +" not supported by HtmlResponseWriterImpl"); } } _isUTF8 = UTF8.equals(_characterEncoding); _startedChangedElements = new ArrayList<String>(); _startedElementsCount = new ArrayList<Integer>(); } public static boolean supportsContentType(String contentType) { String[] supportedContentTypes = ContentTypeUtils.getSupportedContentTypes(); for (String supportedContentType : supportedContentTypes) { if (supportedContentType.contains(contentType)) { return true; } } return false; } @Override public String getContentType() { return _contentType; } public String getWriterContentTypeMode() { return _writerContentTypeMode; } @Override public String getCharacterEncoding() { return _characterEncoding; } @Override public void flush() throws IOException { // API doc says we should not flush the underlying writer //_writer.flush(); // but rather clear any values buffered by this ResponseWriter: closeStartTagIfNecessary(); } @Override public void startDocument() { // do nothing } @Override public void endDocument() throws IOException { MyfacesConfig myfacesConfig = MyfacesConfig.getCurrentInstance(FacesContext.getCurrentInstance()); if (myfacesConfig.isEarlyFlushEnabled()) { _currentWriter.flush(); } _facesContext = null; } @Override public void startElement(String name, UIComponent uiComponent) throws IOException { Assert.notNull(name, "name"); closeStartTagIfNecessary(); _currentWriter.write('<'); resetStartedElement(); _startElementName = name; _startElementUIComponent = uiComponent; _startTagOpen = true; _passThroughAttributesMap = _startElementUIComponent != null ? _startElementUIComponent.getPassThroughAttributes(false) : null; if (_passThroughAttributesMap != null) { Object value = _passThroughAttributesMap.get(Renderer.PASSTHROUGH_RENDERER_LOCALNAME_KEY); if (value != null) { if (value instanceof ValueExpression expression) { value = expression.getValue(getFacesContext().getELContext()); } String elementName = value.toString().trim(); if (!name.equals(elementName)) { _startElementName = elementName; _startedChangedElements.add(elementName); _startedElementsCount.add(0); } _currentWriter.write(elementName); } else { _currentWriter.write(name); } } else { _currentWriter.write(name); } if (!_startedElementsCount.isEmpty()) { int i = _startedElementsCount.size()-1; _startedElementsCount.set(i, _startedElementsCount.get(i)+1); } // Each time we start a element, it is necessary to check <script> or <style>, // because we need to buffer all content to post process it later when it reach its end // according to the initialization properties used. if(isScript(_startElementName)) { // handle a <script> start _isInsideScript = true; _isStyle = false; _isTextArea = Boolean.FALSE; } else if (isStyle(_startElementName)) { _isInsideScript = false; _isStyle = true; _isTextArea = Boolean.FALSE; } } @Override public void startCDATA() throws IOException { if (!_cdataOpen) { write(CDATA_START_NO_LINE_RETURN); _cdataOpen = true; } } @Override public void endCDATA() throws IOException { if (_cdataOpen) { write(CDATA_END_NO_LINE_RETURN); _cdataOpen = false; } } private void closeStartTagIfNecessary() throws IOException { if (_startTagOpen) { if (_passThroughAttributesMap != null) { for (Map.Entry<String, Object> entry : _passThroughAttributesMap.entrySet()) { String key = entry.getKey(); if (Renderer.PASSTHROUGH_RENDERER_LOCALNAME_KEY.equals(key)) { // Special attribute stored in passthrough attribute map, // skip rendering continue; } Object value = entry.getValue(); if (value instanceof ValueExpression expression) { value = expression.getValue(getFacesContext().getELContext()); } // encodeAndWriteURIAttribute(key, value, key); // Faces 2.2 In the renderkit javadoc of jsf 2.2 spec says this // (Rendering Pass Through Attributes): // "... The ResponseWriter must ensure that any pass through attributes are // rendered on the outer-most markup element for the component. If there is // a pass through attribute with the same name as a renderer specific // attribute, the pass through attribute takes precedence. Pass through // attributes are rendered as if they were passed to // ResponseWriter.writeURIAttribute(). ..." // Note here it says "as if they were passed", instead say "... attributes are // encoded and rendered as if ...". Black box testing against RI shows that there // is no URI encoding at all in this part, so in this case the best is do the // same here. After all, it is responsibility of the one who set the passthrough // attribute to do the proper encoding in cases when a URI is provided. However, // that does not means the attribute should not be encoded as other attributes. encodeAndWriteAttribute(key, value); } } if (!_useStraightXml && isEmptyElement(_startElementName)) { _currentWriter.write(" />"); // make null, this will cause NullPointer in some invalid element nestings // (better than doing nothing) resetStartedElement(); } else { _currentWriter.write('>'); if (isScript(_startElementName) && (_isXhtmlContentType || _wrapScriptContentWithXmlCommentTag)) { _currentWriter = getInternalBuffer(true).getWriter(); } if (isStyle(_startElementName) && _isXhtmlContentType) { _currentWriter = getInternalBuffer(true).getWriter(); } } _startTagOpen = false; } } private boolean isEmptyElement(String elem) { // =-=AEW Performance? Certainly slower to use a hashtable, // at least if we can't assume the input name is lowercased. // -= Leonardo Uribe =- elem.toLowerCase() internally creates an array, // and the contains() force a call to hashCode(). The array uses simple // char comparison, which at the end is faster and use less memory. // Note this call is very frequent, so at the end it is worth to do it. String[] array = EMPTY_ELEMENT_ARR[elem.charAt(0)]; if (array != null) { for (int i = array.length - 1; i >= 0; i--) { if (elem.equalsIgnoreCase(array[i])) { return true; } } } return false; } private void resetStartedElement() { _startElementName = null; _startElementUIComponent = null; _passThroughAttributesMap = null; _isStyle = false; _isTextArea = null; } @Override public void endElement(String name) throws IOException { Assert.notNull(name, "name"); String elementName = name; if (!_startedElementsCount.isEmpty()) { int i = _startedElementsCount.size()-1; _startedElementsCount.set(i, _startedElementsCount.get(i)-1); if (_startedElementsCount.get(i) == 0) { elementName = _startedChangedElements.get(i); _startedChangedElements.remove(i); _startedElementsCount.remove(i); } } if (log.isLoggable(Level.WARNING)) { if (_startElementName != null && !elementName.equals(_startElementName)) { log.warning("HTML nesting warning on closing " + elementName + ": element " + _startElementName + (_startElementUIComponent==null ? "" : (" rendered by component : " + ComponentUtils.getPathToComponent(_startElementUIComponent))) + " not explicitly closed"); } } if(_startTagOpen) { // we will get here only if no text or attribute was written after the start element was opened // now we close out the started tag - if it is an empty tag, this is then fully closed closeStartTagIfNecessary(); //tag was no empty tag - it has no accompanying end tag now. if(_startElementName!=null) { if (isScript() && (_isXhtmlContentType || _wrapScriptContentWithXmlCommentTag)) { writeScriptContent(); _currentWriter = _outputWriter; } else if (isStyle() && _isXhtmlContentType) { writeStyleContent(); _currentWriter = _outputWriter; } //write closing tag writeEndTag(elementName); } } else { if (!_useStraightXml && isEmptyElement(elementName)) { } else { if (isScript() && (_isXhtmlContentType || _wrapScriptContentWithXmlCommentTag)) { writeScriptContent(); _currentWriter = _outputWriter; } else if (isStyle() && _isXhtmlContentType) { writeStyleContent(); _currentWriter = _outputWriter; } writeEndTag(elementName); } } resetStartedElement(); } private void writeStyleContent() throws IOException { String content = getInternalBuffer().toString(); if(_isXhtmlContentType) { // In xhtml, the content inside <style> tag is PCDATA, but // in html the content is CDATA, so in order to preserve // compatibility we need to wrap the content inside proper // CDATA tags. // Since the response content type is xhtml, we can use // simple CDATA without comments, but note we need to check // when we are using any valid notation (simple CDATA, commented CDATA, xml comment) String trimmedContent = content.trim(); if (trimmedContent.startsWith(CommentUtils.CDATA_SIMPLE_START) && trimmedContent.endsWith( CommentUtils.CDATA_SIMPLE_END)) { _outputWriter.write(content); return; } else if (CommentUtils.isStartMatchWithCommentedCDATA(trimmedContent) && CommentUtils.isEndMatchWithCommentedCDATA(trimmedContent)) { _outputWriter.write(content); return; } else if (trimmedContent.startsWith(CommentUtils.COMMENT_SIMPLE_START) && trimmedContent.endsWith(CommentUtils.COMMENT_SIMPLE_END)) { //Use comment wrap is valid, but for xhtml it is preferred to use CDATA _outputWriter.write(CDATA_START); _outputWriter.write(trimmedContent.substring(4,trimmedContent.length()-3)); _outputWriter.write(CDATA_END); return; } else { _outputWriter.write(CDATA_START); _outputWriter.write(content); _outputWriter.write(CDATA_END); return; } } // If the response is handled as text/html, // it is not necessary to wrap with xml comment tag, // so we can just write the content as is. _outputWriter.write(content); } private void writeScriptContent() throws IOException { String content = getInternalBuffer().toString(); String trimmedContent = null; if(_isXhtmlContentType) { trimmedContent = content.trim(); if ( trimmedContent.startsWith(CommentUtils.COMMENT_SIMPLE_START) && CommentUtils.isEndMatchtWithInlineCommentedXmlCommentTag(trimmedContent)) { // In xhtml use xml comment to wrap is invalid, so it is only required to remove the <!-- // the ending //--> will be parsed as a comment, so it will not be a problem. Let it on the content. if (_cdataOpen) { _outputWriter.write("//\n"); } else { _outputWriter.write(CDATA_COMMENT_START); } _outputWriter.write(trimmedContent.substring(4)); if (_cdataOpen) { _outputWriter.write('\n'); } else { _outputWriter.write(CDATA_COMMENT_END); } return; } else if (CommentUtils.isStartMatchWithCommentedCDATA(trimmedContent) && CommentUtils.isEndMatchWithCommentedCDATA(trimmedContent)) { _outputWriter.write(content); return; } else if (CommentUtils.isStartMatchWithInlineCommentedCDATA(trimmedContent) && CommentUtils.isEndMatchWithInlineCommentedCDATA(trimmedContent)) { _outputWriter.write(content); return; } else { // <script> in xhtml has as content type PCDATA, but in html it is CDATA, // so we need to wrap here to prevent problems. if (_cdataOpen) { _outputWriter.write("//\n"); } else { _outputWriter.write(CDATA_COMMENT_START); } _outputWriter.write(content); if (_cdataOpen) { _outputWriter.write('\n'); } else { _outputWriter.write(CDATA_COMMENT_END); } return; } } else { if (_wrapScriptContentWithXmlCommentTag) { trimmedContent = content.trim(); if ( trimmedContent.startsWith(CommentUtils.COMMENT_SIMPLE_START) && CommentUtils.isEndMatchtWithInlineCommentedXmlCommentTag(trimmedContent)) { _outputWriter.write(content); return; } else if (CommentUtils.isStartMatchWithCommentedCDATA(trimmedContent) && CommentUtils.isEndMatchWithCommentedCDATA(trimmedContent)) { _outputWriter.write(content); return; } else if (CommentUtils.isStartMatchWithInlineCommentedCDATA(trimmedContent) && CommentUtils.isEndMatchWithInlineCommentedCDATA(trimmedContent)) { _outputWriter.write(content); return; } else { _outputWriter.write(COMMENT_START); _outputWriter.write(content); _outputWriter.write(COMMENT_COMMENT_END); return; } } } //If no return, just write everything _outputWriter.write(content); } private void writeEndTag(String name) throws IOException { if (isScript(name)) { // reset _isInsideScript _isInsideScript = false; } else if (isStyle(name)) { _isStyle = false; } _currentWriter.write("</"); _currentWriter.write(name); _currentWriter.write('>'); } @Override public void writeAttribute(String name, Object value, String componentPropertyName) throws IOException { Assert.notNull(name, "name"); if (!_startTagOpen) { throw new IllegalStateException("Must be called before the start element is closed (attribute '" + name + "')"); } // From Faces 2.2 RenderKit javadoc: "... If there is a pass through attribute with the same // name as a renderer specific attribute, the pass through attribute takes precedence. ..." if (_passThroughAttributesMap != null && _passThroughAttributesMap.containsKey(name)) { return; } if (value instanceof Boolean boolean1) { if (boolean1.booleanValue()) { // name as value for XHTML compatibility _currentWriter.write(' '); _currentWriter.write(name); _currentWriter.write("=\""); _currentWriter.write(name); _currentWriter.write('"'); } } else { _currentWriter.write(' '); _currentWriter.write(name); _currentWriter.write("=\""); if (value != null) { HTMLEncoder.encode(_currentWriter, value.toString(), false, false, !_isUTF8); } _currentWriter.write('"'); } } private void encodeAndWriteAttribute(String name, Object value) throws IOException { _currentWriter.write(' '); _currentWriter.write(name); _currentWriter.write("=\""); if (value != null) { HTMLEncoder.encode(_currentWriter, value.toString(), false, false, !_isUTF8); } _currentWriter.write('"'); } @Override public void writeURIAttribute(String name, Object value, String componentPropertyName) throws IOException { Assert.notNull(name, "name"); if (!_startTagOpen) { throw new IllegalStateException("Must be called before the start element is closed (attribute '" + name + "')"); } // From Faces 2.2 RenderKit javadoc: "... If there is a pass through attribute with the same // name as a renderer specific attribute, the pass through attribute takes precedence. ..." if (_passThroughAttributesMap != null && _passThroughAttributesMap.containsKey(name)) { return; } encodeAndWriteURIAttribute(name, value); } private void encodeAndWriteURIAttribute(String name, Object value) throws IOException { String strValue = value.toString(); _currentWriter.write(' '); _currentWriter.write(name); _currentWriter.write("=\""); if (strValue.toLowerCase().startsWith("javascript:")) { HTMLEncoder.encode(_currentWriter, strValue, false, false, !_isUTF8); } else { HTMLEncoder.encodeURIAttribute(_currentWriter, strValue, _characterEncoding); } _currentWriter.write('"'); } @Override public void writeComment(Object value) throws IOException { Assert.notNull(value, "value"); closeStartTagIfNecessary(); _currentWriter.write("<!--"); _currentWriter.write(value.toString()); //TODO: Escaping: must not have "-->" inside! _currentWriter.write("-->"); } @Override public void writeText(Object value, String componentPropertyName) throws IOException { Assert.notNull(value, "value"); closeStartTagIfNecessary(); String strValue = value.toString(); if (isScriptOrStyle()) { // Don't bother encoding anything if chosen character encoding is UTF-8 if (_isUTF8) { _currentWriter.write(strValue); } else { UnicodeEncoder.encode(_currentWriter, strValue); } } else { HTMLEncoder.encode(_currentWriter, strValue, false, false, !_isUTF8); } } @Override public void writeText(char[] cbuf, int off, int len) throws IOException { Assert.notNull(cbuf, "cbuf"); if (cbuf.length < off + len) { throw new IndexOutOfBoundsException((off + len) + " > " + cbuf.length); } closeStartTagIfNecessary(); if (isScriptOrStyle()) { String strValue = new String(cbuf, off, len); // Don't bother encoding anything if chosen character encoding is UTF-8 if (_isUTF8) { _currentWriter.write(strValue); } else { UnicodeEncoder.encode(_currentWriter, strValue); } } else if (isTextarea()) { // For textareas we must *not* map successive spaces to &nbsp or Newlines to <br/> HTMLEncoder.encode(cbuf, off, len, false, false, !_isUTF8, _currentWriter); } else { // We map successive spaces to &nbsp; and Newlines to <br/> HTMLEncoder.encode(cbuf, off, len, true, true, !_isUTF8, _currentWriter); } } private boolean isScriptOrStyle() { return _isStyle || _isInsideScript; } /** * Is the given element a script tag? * @param element * @return */ private boolean isScript(String element) { return (HTML.SCRIPT_ELEM.equalsIgnoreCase(element)); } private boolean isScript() { return _isInsideScript; } private boolean isStyle(String element) { return (HTML.STYLE_ELEM.equalsIgnoreCase(element)); } private boolean isStyle() { return _isStyle; } private boolean isTextarea() { initializeStartedTagInfo(); return _isTextArea != null && _isTextArea; } private void initializeStartedTagInfo() { if (_startElementName != null) { if (_isTextArea == null) { if (_startElementName.equalsIgnoreCase(HTML.TEXTAREA_ELEM)) { _isTextArea = Boolean.TRUE; } else { _isTextArea = Boolean.FALSE; } } } } @Override public ResponseWriter cloneWithWriter(Writer writer) { HtmlResponseWriterImpl newWriter = new HtmlResponseWriterImpl(writer, getContentType(), getCharacterEncoding(), _wrapScriptContentWithXmlCommentTag, _writerContentTypeMode); return newWriter; } // Writer methods @Override public void close() throws IOException { closeStartTagIfNecessary(); _currentWriter.close(); _facesContext = null; } @Override public void write(char[] cbuf, int off, int len) throws IOException { closeStartTagIfNecessary(); // Don't bother encoding anything if chosen character encoding is UTF-8 if (_isUTF8) { _currentWriter.write(cbuf, off, len); } else { UnicodeEncoder.encode(_currentWriter, cbuf, off, len); } } @Override public void write(int c) throws IOException { closeStartTagIfNecessary(); _currentWriter.write(c); } @Override public void write(char[] cbuf) throws IOException { closeStartTagIfNecessary(); // Don't bother encoding anything if chosen character encoding is UTF-8 if (_isUTF8) { _currentWriter.write(cbuf); } else { UnicodeEncoder.encode(_currentWriter, cbuf, 0, cbuf.length); } } @Override public void write(String str) throws IOException { closeStartTagIfNecessary(); // empty string commonly used to force the start tag to be closed. // in such case, do not call down the writer chain if (str != null && str.length() > 0) { // Don't bother encoding anything if chosen character encoding is UTF-8 if (_isUTF8) { _currentWriter.write(str); } else { UnicodeEncoder.encode(_currentWriter, str); } } } @Override public void write(String str, int off, int len) throws IOException { closeStartTagIfNecessary(); // Don't bother encoding anything if chosen character encoding is UTF-8 if (_isUTF8) { _currentWriter.write(str, off, len); } else { UnicodeEncoder.encode(_currentWriter, str, off, len); } } /** * This method ignores the <code>UIComponent</code> provided and simply calls * <code>writeText(Object,String)</code> * @since 1.2 */ @Override public void writeText(Object object, UIComponent component, String string) throws IOException { writeText(object,string); } protected StreamCharBuffer getInternalBuffer() { return getInternalBuffer(false); } protected StreamCharBuffer getInternalBuffer(boolean reset) { if (_buffer == null) { _buffer = new StreamCharBuffer(256, 100); } else if (reset) { _buffer.reset(); } return _buffer; } protected FacesContext getFacesContext() { if (_facesContext == null) { _facesContext = FacesContext.getCurrentInstance(); } return _facesContext; } protected boolean getWrapScriptContentWithXmlCommentTag() { return _wrapScriptContentWithXmlCommentTag; } protected void forceFlush() throws IOException { _currentWriter.flush(); } }
oracle/graal
36,516
truffle/src/com.oracle.truffle.dsl.processor/src/com/oracle/truffle/dsl/processor/java/transform/AbstractCodeWriter.java
/* * Copyright (c) 2012, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.dsl.processor.java.transform; import static com.oracle.truffle.dsl.processor.java.ElementUtils.getQualifiedName; import java.io.IOException; import java.io.Writer; import java.lang.annotation.Repeatable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.FilerException; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.AbstractAnnotationValueVisitor8; import javax.lang.model.util.ElementFilter; import com.oracle.truffle.dsl.processor.ProcessorContext; import com.oracle.truffle.dsl.processor.java.ElementUtils; import com.oracle.truffle.dsl.processor.java.model.CodeElementScanner; import com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement; import com.oracle.truffle.dsl.processor.java.model.CodeImport; import com.oracle.truffle.dsl.processor.java.model.CodeTree; import com.oracle.truffle.dsl.processor.java.model.CodeTreeKind; import com.oracle.truffle.dsl.processor.java.model.CodeTypeElement; import com.oracle.truffle.dsl.processor.java.model.CodeVariableElement; public abstract class AbstractCodeWriter extends CodeElementScanner<Void, Void> { private static final int MAX_LINE_LENGTH = Integer.MAX_VALUE; // line wrapping disabled private static final int LINE_WRAP_INDENTS = 3; private static final int MAX_JAVADOC_LINE_LENGTH = 500; private static final String IDENT_STRING = " "; private static final String LN = System.lineSeparator(); /* unix style */ protected Writer writer; private int indent; private boolean newLine; private int lineLength; private boolean lineWrapping = false; /* Use LINE_WRAP_INDENTS when wrapping lines as long as a line is wrapped. */ private boolean indentLineWrapping = true; private boolean lineWrappingAtWords = false; private String linePrefix; private int maxLineLength = MAX_LINE_LENGTH; private OrganizedImports imports; protected abstract Writer createWriter(CodeTypeElement clazz) throws IOException; @Override public Void visitType(CodeTypeElement e, Void p) { if (e.isTopLevelClass()) { Writer w = null; try { imports = OrganizedImports.organize(e); w = new TrimTrailingSpaceWriter(createWriter(e)); writer = w; writeRootClass(e); } catch (IOException ex) { if (ex instanceof FilerException) { if (ex.getMessage().startsWith("Source file already created")) { // ignore source file already created errors return null; } } throw new RuntimeException(ex); } finally { if (w != null) { try { w.close(); } catch (Throwable e1) { // see eclipse bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=361378 // TODO GR-38632 temporary suppress errors on close. } } writer = null; } } else { writeClassImpl(e); } return null; } private void writeRootClass(CodeTypeElement e) { writeHeader(); if (e.getPackageName() != null && e.getPackageName().length() > 0) { write("package ").write(e.getPackageName()).write(";").writeLn(); writeEmptyLn(); } Set<CodeImport> generateImports = getImports().generateImports(); List<CodeImport> typeImports = new ArrayList<>(); List<CodeImport> staticImports = new ArrayList<>(); for (CodeImport codeImport : generateImports) { if (codeImport.isStaticImport()) { staticImports.add(codeImport); } else { typeImports.add(codeImport); } } Collections.sort(typeImports); Collections.sort(staticImports); for (CodeImport imp : staticImports) { imp.accept(this, null); writeLn(); } if (!staticImports.isEmpty()) { writeEmptyLn(); } for (CodeImport imp : typeImports) { imp.accept(this, null); writeLn(); } if (!typeImports.isEmpty()) { writeEmptyLn(); } writeClassImpl(e); } private String useImport(Element enclosedType, TypeMirror type, boolean rawType) { if (imports != null) { return imports.createTypeReference(enclosedType, type, rawType); } else { return ElementUtils.getSimpleName(type); } } private void writeClassImpl(CodeTypeElement e) { if (e.getDocTree() != null) { visitTree(e.getDocTree(), null, e); } for (AnnotationMirror annotation : e.getAnnotationMirrors()) { visitAnnotation(e, annotation); writeLn(); } writeModifiers(e.getModifiers(), true); if (e.getKind() == ElementKind.ENUM) { write("enum "); } else if (e.getKind() == ElementKind.INTERFACE) { write("interface "); } else { write("class "); } write(e.getSimpleName()); writeTypeParameters(e, e.getTypeParameters()); if (e.getKind() == ElementKind.CLASS) { if (e.getSuperclass() != null && !getQualifiedName(e.getSuperclass()).equals("java.lang.Object")) { write(" extends ").write(useImport(e, e.getSuperclass(), false)); } if (e.getImplements().size() > 0) { write(" implements "); for (int i = 0; i < e.getImplements().size(); i++) { write(useImport(e, e.getImplements().get(i), false)); if (i < e.getImplements().size() - 1) { write(", "); } } } } else if (e.getKind() == ElementKind.INTERFACE) { if (e.getImplements().size() > 0) { write(" extends "); for (int i = 0; i < e.getImplements().size(); i++) { write(useImport(e, e.getImplements().get(i), false)); if (i < e.getImplements().size() - 1) { write(", "); } } } } if (e.getKind() == ElementKind.INTERFACE || e.getKind() == ElementKind.CLASS) { if (e.getModifiers().contains(Modifier.SEALED)) { write(" permits "); String sep = ""; for (TypeMirror permitSubclass : e.getPermittedSubclasses()) { write(sep); write(useImport(e, permitSubclass, false)); sep = ", "; } } } write(" {").writeLn(); writeEmptyLn(); indent(1); List<VariableElement> staticFields = getStaticFields(e); boolean hasStaticFields = false; for (int i = 0; i < staticFields.size(); i++) { VariableElement field = staticFields.get(i); field.accept(this, null); if (e.getKind() == ElementKind.ENUM && i < staticFields.size() - 1) { write(","); writeLn(); } else { write(";"); writeLn(); } hasStaticFields = true; } if (hasStaticFields) { writeEmptyLn(); } boolean hasInstanceFields = false; for (VariableElement field : getInstanceFields(e)) { field.accept(this, null); write(";"); writeLn(); hasInstanceFields = true; } if (hasInstanceFields) { writeEmptyLn(); } for (ExecutableElement method : ElementFilter.constructorsIn(e.getEnclosedElements())) { method.accept(this, null); } for (ExecutableElement method : getInstanceMethods(e)) { method.accept(this, null); } for (ExecutableElement method : getStaticMethods(e)) { method.accept(this, null); } for (TypeElement clazz : e.getInnerClasses()) { clazz.accept(this, null); } dedent(1); write("}"); writeEmptyLn(); } private void writeTypeParameters(Element enclosedType, List<? extends TypeParameterElement> parameters) { if (!parameters.isEmpty()) { write("<"); String sep = ""; for (TypeParameterElement typeParameter : parameters) { write(sep); write(typeParameter.getSimpleName().toString()); if (needsBound(typeParameter)) { write(" extends "); String genericBoundsSep = ""; for (TypeMirror type : typeParameter.getBounds()) { write(genericBoundsSep); write(useImport(enclosedType, type, false)); genericBoundsSep = ", "; } } sep = ", "; } write(">"); } } private static boolean needsBound(TypeParameterElement typeParameter) { var bounds = typeParameter.getBounds(); return switch (bounds.size()) { case 0 -> false; case 1 -> { ProcessorContext ctx = ProcessorContext.getInstance(); yield !ctx.getEnvironment().getTypeUtils().isSameType(bounds.get(0), ctx.getDeclaredType(Object.class)); } default -> true; }; } private static List<VariableElement> getStaticFields(CodeTypeElement clazz) { List<VariableElement> staticFields = new ArrayList<>(); for (VariableElement field : clazz.getFields()) { if (field.getModifiers().contains(Modifier.STATIC)) { staticFields.add(field); } } return staticFields; } private static List<VariableElement> getInstanceFields(CodeTypeElement clazz) { List<VariableElement> instanceFields = new ArrayList<>(); for (VariableElement field : clazz.getFields()) { if (!field.getModifiers().contains(Modifier.STATIC)) { instanceFields.add(field); } } return instanceFields; } private static List<ExecutableElement> getStaticMethods(CodeTypeElement clazz) { List<ExecutableElement> staticMethods = new ArrayList<>(); for (ExecutableElement method : clazz.getMethods()) { if (method.getModifiers().contains(Modifier.STATIC)) { staticMethods.add(method); } } return staticMethods; } private static List<ExecutableElement> getInstanceMethods(CodeTypeElement clazz) { List<ExecutableElement> instanceMethods = new ArrayList<>(); for (ExecutableElement method : clazz.getMethods()) { if (!method.getModifiers().contains(Modifier.STATIC)) { instanceMethods.add(method); } } return instanceMethods; } @Override public Void visitVariable(VariableElement f, Void p) { Element parent = f.getEnclosingElement(); CodeTree init = null; if (f instanceof CodeVariableElement) { CodeVariableElement codeVar = ((CodeVariableElement) f); init = codeVar.getInit(); if (codeVar.getDocTree() != null) { visitTree(codeVar.getDocTree(), null, f); } } for (AnnotationMirror annotation : f.getAnnotationMirrors()) { visitAnnotation(f, annotation); write(" "); } if (parent != null && parent.getKind() == ElementKind.ENUM && f.getModifiers().contains(Modifier.STATIC)) { write(f.getSimpleName()); if (init != null) { write("("); visitTree(init, p, f); write(")"); } } else { writeModifiers(f.getModifiers(), true); boolean varArgs = false; if (parent != null && (parent.getKind() == ElementKind.METHOD || parent.getKind() == ElementKind.CONSTRUCTOR)) { ExecutableElement method = (ExecutableElement) parent; if (method.isVarArgs() && method.getParameters().indexOf(f) == method.getParameters().size() - 1) { varArgs = true; } } TypeMirror varType = f.asType(); if (varArgs) { if (varType.getKind() == TypeKind.ARRAY) { varType = ((ArrayType) varType).getComponentType(); } write(useImport(f, varType, false)); write("..."); } else { write(useImport(f, varType, false)); } write(" "); write(f.getSimpleName()); if (init != null) { write(" = "); visitTree(init, p, f); } } return null; } private void visitAnnotation(Element enclosedElement, AnnotationMirror e) { List<AnnotationMirror> repeatableAnnotations = unpackRepeatable(e); if (repeatableAnnotations != null) { for (AnnotationMirror annotationMirror : repeatableAnnotations) { visitAnnotationImpl(enclosedElement, annotationMirror); } } else { visitAnnotationImpl(enclosedElement, e); } } private void visitAnnotationImpl(Element enclosedElement, AnnotationMirror e) { final ExecutableElement defaultElement = findExecutableElement(e.getAnnotationType(), "value"); Map<? extends ExecutableElement, ? extends AnnotationValue> values = e.getElementValues(); write("@").write(useImport(enclosedElement, e.getAnnotationType(), true)); if (!e.getElementValues().isEmpty()) { write("("); if (defaultElement != null && values.size() == 1 && values.get(defaultElement) != null) { visitAnnotationValue(enclosedElement, values.get(defaultElement)); } else { Set<? extends ExecutableElement> methodsSet = values.keySet(); List<ExecutableElement> methodsList = new ArrayList<>(); for (ExecutableElement method : methodsSet) { if (values.get(method) == null) { continue; } methodsList.add(method); } Collections.sort(methodsList, new Comparator<ExecutableElement>() { @Override public int compare(ExecutableElement o1, ExecutableElement o2) { return o1.getSimpleName().toString().compareTo(o2.getSimpleName().toString()); } }); for (int i = 0; i < methodsList.size(); i++) { ExecutableElement method = methodsList.get(i); AnnotationValue value = values.get(method); write(method.getSimpleName().toString()); write(" = "); visitAnnotationValue(enclosedElement, value); if (i < methodsList.size() - 1) { write(", "); } } } write(")"); } } /** * This method checks whether an annotation can be written as a set of repeatable annotations * instead. Returns a list of elements if it can or <code>null</code> if it can't. */ static List<AnnotationMirror> unpackRepeatable(AnnotationMirror e) { final ExecutableElement defaultElement = findExecutableElement(e.getAnnotationType(), "value"); if (defaultElement == null) { return null; } TypeMirror returnType = defaultElement.getReturnType(); if (returnType.getKind() != TypeKind.ARRAY) { /* * Not an array. Not a repeatable annotation. */ return null; } ArrayType arrayReturnType = (ArrayType) returnType; TypeElement typeElement = ElementUtils.fromTypeMirror(arrayReturnType.getComponentType()); if (typeElement == null) { // just to be robust against not referenced classes. return null; } AnnotationMirror repeatable = ElementUtils.findAnnotationMirror(typeElement.getAnnotationMirrors(), ProcessorContext.getInstance().getType(Repeatable.class)); if (repeatable == null) { /* * Annotation type does not declare repeatable. */ return null; } TypeMirror repeatableType = ElementUtils.getAnnotationValue(TypeMirror.class, repeatable, "value"); if (!ElementUtils.typeEquals(repeatableType, e.getAnnotationType())) { /* * Not the right repeatable type. */ return null; } if (e.getElementValues().size() != 1) { /* * Repeating annotation has more than one attribute. We should not unpack repeatable * annotations to not loose some attributes there. */ return null; } if (!e.getElementValues().containsKey(defaultElement)) { /* * Does not contain the default element. */ return null; } return ElementUtils.getAnnotationValueList(AnnotationMirror.class, e, "value"); } private void visitAnnotationValue(Element enclosedElement, AnnotationValue e) { e.accept(new AnnotationValueWriterVisitor(enclosedElement), null); } private class AnnotationValueWriterVisitor extends AbstractAnnotationValueVisitor8<Void, Void> { private final Element enclosedElement; AnnotationValueWriterVisitor(Element enclosedElement) { this.enclosedElement = enclosedElement; } @Override public Void visitBoolean(boolean b, Void p) { write(Boolean.toString(b)); return null; } @Override public Void visitByte(byte b, Void p) { write(Byte.toString(b)); return null; } @Override public Void visitChar(char c, Void p) { write(Character.toString(c)); return null; } @Override public Void visitDouble(double d, Void p) { write(Double.toString(d)); return null; } @Override public Void visitFloat(float f, Void p) { write(Float.toString(f)); return null; } @Override public Void visitInt(int i, Void p) { write(Integer.toString(i)); return null; } @Override public Void visitLong(long i, Void p) { write(Long.toString(i)); return null; } @Override public Void visitShort(short s, Void p) { write(Short.toString(s)); return null; } @Override public Void visitString(String s, Void p) { write("\""); write(s); write("\""); return null; } @Override public Void visitType(TypeMirror t, Void p) { write(useImport(enclosedElement, t, true)); write(".class"); return null; } @Override public Void visitEnumConstant(VariableElement c, Void p) { write(useImport(enclosedElement, c.asType(), true)); write("."); write(c.getSimpleName().toString()); return null; } @Override public Void visitAnnotation(AnnotationMirror a, Void p) { AbstractCodeWriter.this.visitAnnotation(enclosedElement, a); return null; } @Override public Void visitArray(List<? extends AnnotationValue> vals, Void p) { int size = vals.size(); if (size > 1) { write("{"); } for (int i = 0; i < size; i++) { AnnotationValue value = vals.get(i); AbstractCodeWriter.this.visitAnnotationValue(enclosedElement, value); if (i < size - 1) { write(", "); } } if (size > 1) { write("}"); } return null; } } private static ExecutableElement findExecutableElement(DeclaredType type, String name) { List<? extends ExecutableElement> elements = ElementFilter.methodsIn(type.asElement().getEnclosedElements()); for (ExecutableElement executableElement : elements) { if (executableElement.getSimpleName().toString().equals(name)) { return executableElement; } } return null; } @Override public void visitImport(CodeImport e, Void p) { write("import "); if (e.isStaticImport()) { write("static "); } write(e.getPackageName()); write("."); write(e.getSymbolName()); write(";"); } @Override public Void visitExecutable(CodeExecutableElement e, Void p) { if (e.getDocTree() != null) { visitTree(e.getDocTree(), null, e); } for (AnnotationMirror annotation : e.getAnnotationMirrors()) { visitAnnotation(e, annotation); writeLn(); } writeModifiers(e.getModifiers(), e.getEnclosingClass() == null || !e.getEnclosingClass().getModifiers().contains(Modifier.FINAL)); String name = e.getSimpleName().toString(); if (name.equals("<cinit>") || name.equals("<init>")) { // no name } else { List<TypeParameterElement> typeParameters = e.getTypeParameters(); if (!typeParameters.isEmpty()) { write("<"); for (int i = 0; i < typeParameters.size(); i++) { TypeParameterElement param = typeParameters.get(i); write(param.getSimpleName().toString()); if (needsBound(param)) { write(" extends "); List<? extends TypeMirror> bounds = param.getBounds(); for (int j = 0; j < bounds.size(); j++) { TypeMirror bound = bounds.get(i); write(useImport(e, bound, true)); if (j < bounds.size() - 1) { write(" "); write(", "); } } } if (i < typeParameters.size() - 1) { write(" "); write(", "); } } write("> "); } if (e.getReturnType() != null) { write(useImport(e, e.getReturnType(), false)); write(" "); } write(e.getSimpleName()); write("("); for (int i = 0; i < e.getParameters().size(); i++) { VariableElement param = e.getParameters().get(i); param.accept(this, p); if (i < e.getParameters().size() - 1) { write(", "); } } write(")"); List<TypeMirror> throwables = e.getThrownTypes(); if (throwables.size() > 0) { write(" throws "); for (int i = 0; i < throwables.size(); i++) { write(useImport(e, throwables.get(i), true)); if (i < throwables.size() - 1) { write(", "); } } } } if (e.getModifiers().contains(Modifier.ABSTRACT)) { writeLn(";"); } else if (e.getBodyTree() != null) { writeLn(" {"); indent(1); visitTree(e.getBodyTree(), p, e); dedent(1); writeLn("}"); } else if (e.getBody() != null) { write(" {"); write(e.getBody()); writeLn("}"); } else { writeLn(" {"); writeLn("}"); } writeEmptyLn(); return null; } private OrganizedImports getImports() { if (imports == null) { return OrganizedImports.organize(null); } return imports; } @Override public void visitTree(CodeTree e, Void p, Element enclosingElement) { CodeTreeKind kind = e.getCodeKind(); switch (kind) { case COMMA_GROUP: List<CodeTree> children = e.getEnclosedElements(); if (children != null) { for (int i = 0; i < children.size(); i++) { visitTree(children.get(i), p, enclosingElement); if (i < e.getEnclosedElements().size() - 1) { write(", "); } } } break; case GROUP: super.visitTree(e, p, enclosingElement); break; case INDENT: indent(1); super.visitTree(e, p, enclosingElement); dedent(1); break; case NEW_LINE: writeLn(); break; case STRING: if (e.getString() != null) { String s = e.getString(); if (lineWrappingAtWords) { int index = -1; int start = 0; while ((index = s.indexOf(' ', start)) != -1) { write(s.substring(start, index + 1)); start = index + 1; } if (start < s.length()) { write(s.substring(start, s.length())); } } else { write(e.getString()); } } else { write("null"); } break; case STATIC_FIELD_REFERENCE: if (e.getString() != null) { write(getImports().createStaticFieldReference(enclosingElement, e.getType(), e.getString())); } else { write("null"); } break; case STATIC_METHOD_REFERENCE: if (e.getString() != null) { write(getImports().createStaticMethodReference(enclosingElement, e.getType(), e.getString())); } else { write("null"); } break; case TYPE: write(useImport(enclosingElement, e.getType(), false)); break; case TYPE_LITERAL: write(useImport(enclosingElement, e.getType(), true)); break; case JAVA_DOC: case DOC: write("/*"); if (kind == CodeTreeKind.JAVA_DOC) { write("*"); } write(" "); writeLn(); indentLineWrapping = false; // avoid wrapping indents int prevMaxLineLength = this.maxLineLength; maxLineLength = MAX_JAVADOC_LINE_LENGTH; linePrefix = " * "; lineWrappingAtWords = true; super.visitTree(e, p, enclosingElement); linePrefix = null; lineWrappingAtWords = false; maxLineLength = prevMaxLineLength; indentLineWrapping = true; write(" */"); writeLn(); break; default: assert false; return; } } protected void writeHeader() { // default implementation does nothing } private void writeModifiers(Set<Modifier> modifiers, boolean includeFinal) { if (modifiers != null && !modifiers.isEmpty()) { Modifier[] modArray = modifiers.toArray(new Modifier[modifiers.size()]); Arrays.sort(modArray); for (Modifier mod : modArray) { if (mod == Modifier.FINAL && !includeFinal) { continue; } write(mod.toString()); write(" "); } } } private void indent(int count) { indent += count; } private void dedent(int count) { indent -= count; } private void writeLn() { writeLn(""); } protected void writeLn(String text) { write(text); write(LN); lineLength = 0; newLine = true; if (lineWrapping && indentLineWrapping) { dedent(LINE_WRAP_INDENTS); } lineWrapping = false; } private void writeEmptyLn() { writeLn(); } private AbstractCodeWriter write(Name name) { return write(name.toString()); } private AbstractCodeWriter write(String m) { if (m.isEmpty()) { return this; } try { String s = m; lineLength += s.length(); if (newLine && s != LN) { writeIndent(); newLine = false; } if (lineLength > maxLineLength) { s = wrapLine(s); } writer.write(s); } catch (IOException e) { throw new RuntimeException(e); } return this; } private String wrapLine(String m) throws IOException { assert !m.isEmpty(); char firstCharacter = m.charAt(0); char lastCharacter = m.charAt(m.length() - 1); if (firstCharacter == '\"' && lastCharacter == '\"') { // string line wrapping String string = m.substring(1, m.length() - 1); if (string.isEmpty()) { return m; } // restore original line length lineLength = lineLength - m.length(); int size = 0; for (int i = 0; i < string.length(); i += size) { if (i != 0) { write("+ "); } int nextSize = maxLineLength - lineLength - 2; if (nextSize <= 0) { writeLn(); nextSize = maxLineLength - lineLength - 2; } int end = Math.min(i + nextSize, string.length()); // TODO GR-38632 (CH): fails in normal usage - output ok though // assert lineLength + (end - i) + 2 < maxLineLength; write("\""); write(string.substring(i, end)); write("\""); size = nextSize; } return ""; } else if (!Character.isAlphabetic(firstCharacter) && firstCharacter != '+') { return m; } if (!lineWrapping && indentLineWrapping) { indent(LINE_WRAP_INDENTS); } lineWrapping = true; lineLength = 0; write(LN); writeIndent(); return m; } private void writeIndent() throws IOException { lineLength += indentSize(); for (int i = 0; i < indent; i++) { writer.write(IDENT_STRING); } if (linePrefix != null) { lineLength += linePrefix.length(); writer.write(linePrefix); } } private int indentSize() { return IDENT_STRING.length() * indent; } private static class TrimTrailingSpaceWriter extends Writer { private final Writer delegate; private final StringBuilder buffer = new StringBuilder(); TrimTrailingSpaceWriter(Writer delegate) { this.delegate = delegate; } @Override public void close() throws IOException { this.delegate.close(); } @Override public void flush() throws IOException { this.delegate.flush(); } @Override public void write(char[] cbuf, int off, int len) throws IOException { buffer.append(cbuf, off, len); int newLinePoint = buffer.indexOf(LN); if (newLinePoint != -1) { String lhs = trimTrailing(buffer.substring(0, newLinePoint)); delegate.write(lhs); delegate.write(LN); buffer.delete(0, newLinePoint + LN.length()); } } private static String trimTrailing(String s) { int cut = 0; for (int i = s.length() - 1; i >= 0; i--) { if (Character.isWhitespace(s.charAt(i))) { cut++; } else { break; } } if (cut > 0) { return s.substring(0, s.length() - cut); } return s; } } }
google/guava
36,213
android/guava/src/com/google/common/net/HttpHeaders.java
/* * Copyright (C) 2011 The Guava 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.common.net; import com.google.common.annotations.GwtCompatible; /** * Contains constant definitions for the HTTP header field names. See: * * <ul> * <li><a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> * <li><a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a> * <li><a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616</a> * <li><a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a> * <li><a href="http://www.ietf.org/rfc/rfc5988.txt">RFC 5988</a> * </ul> * * @author Kurt Alfred Kluever * @since 11.0 */ @GwtCompatible public final class HttpHeaders { private HttpHeaders() {} // HTTP Request and Response header fields /** The HTTP {@code Cache-Control} header field name. */ public static final String CACHE_CONTROL = "Cache-Control"; /** The HTTP {@code Content-Length} header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** The HTTP {@code Content-Type} header field name. */ public static final String CONTENT_TYPE = "Content-Type"; /** The HTTP {@code Date} header field name. */ public static final String DATE = "Date"; /** The HTTP {@code Pragma} header field name. */ public static final String PRAGMA = "Pragma"; /** The HTTP {@code Via} header field name. */ public static final String VIA = "Via"; /** The HTTP {@code Warning} header field name. */ public static final String WARNING = "Warning"; // HTTP Request header fields /** The HTTP {@code Accept} header field name. */ public static final String ACCEPT = "Accept"; /** The HTTP {@code Accept-Charset} header field name. */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** The HTTP {@code Accept-Encoding} header field name. */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** The HTTP {@code Accept-Language} header field name. */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** The HTTP {@code Access-Control-Request-Headers} header field name. */ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; /** The HTTP {@code Access-Control-Request-Method} header field name. */ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; /** The HTTP {@code Authorization} header field name. */ public static final String AUTHORIZATION = "Authorization"; /** The HTTP {@code Connection} header field name. */ public static final String CONNECTION = "Connection"; /** The HTTP {@code Cookie} header field name. */ public static final String COOKIE = "Cookie"; /** * The HTTP <a href="https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header">{@code * Cross-Origin-Resource-Policy}</a> header field name. * * @since 28.0 */ public static final String CROSS_ORIGIN_RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc8470">{@code Early-Data}</a> header * field name. * * @since 27.0 */ public static final String EARLY_DATA = "Early-Data"; /** The HTTP {@code Expect} header field name. */ public static final String EXPECT = "Expect"; /** The HTTP {@code From} header field name. */ public static final String FROM = "From"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc7239">{@code Forwarded}</a> header * field name. * * @since 20.0 */ public static final String FORWARDED = "Forwarded"; /** * The HTTP {@code Follow-Only-When-Prerender-Shown} header field name. * * @since 17.0 */ public static final String FOLLOW_ONLY_WHEN_PRERENDER_SHOWN = "Follow-Only-When-Prerender-Shown"; /** The HTTP {@code Host} header field name. */ public static final String HOST = "Host"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc7540#section-3.2.1">{@code * HTTP2-Settings} </a> header field name. * * @since 24.0 */ public static final String HTTP2_SETTINGS = "HTTP2-Settings"; /** The HTTP {@code If-Match} header field name. */ public static final String IF_MATCH = "If-Match"; /** The HTTP {@code If-Modified-Since} header field name. */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** The HTTP {@code If-None-Match} header field name. */ public static final String IF_NONE_MATCH = "If-None-Match"; /** The HTTP {@code If-Range} header field name. */ public static final String IF_RANGE = "If-Range"; /** The HTTP {@code If-Unmodified-Since} header field name. */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** The HTTP {@code Last-Event-ID} header field name. */ public static final String LAST_EVENT_ID = "Last-Event-ID"; /** The HTTP {@code Max-Forwards} header field name. */ public static final String MAX_FORWARDS = "Max-Forwards"; /** The HTTP {@code Origin} header field name. */ public static final String ORIGIN = "Origin"; /** * The HTTP <a href="https://github.com/WICG/origin-isolation">{@code Origin-Isolation}</a> header * field name. * * @since 30.1 */ public static final String ORIGIN_ISOLATION = "Origin-Isolation"; /** The HTTP {@code Proxy-Authorization} header field name. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** The HTTP {@code Range} header field name. */ public static final String RANGE = "Range"; /** The HTTP {@code Referer} header field name. */ public static final String REFERER = "Referer"; /** * The HTTP <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> header * field name. * * @since 23.4 */ public static final String REFERRER_POLICY = "Referrer-Policy"; /** * Values for the <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> * header. * * @since 23.4 */ public static final class ReferrerPolicyValues { private ReferrerPolicyValues() {} public static final String NO_REFERRER = "no-referrer"; public static final String NO_REFFERER_WHEN_DOWNGRADE = "no-referrer-when-downgrade"; public static final String SAME_ORIGIN = "same-origin"; public static final String ORIGIN = "origin"; public static final String STRICT_ORIGIN = "strict-origin"; public static final String ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin"; public static final String STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"; public static final String UNSAFE_URL = "unsafe-url"; } /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER = "Service-Worker"; /** The HTTP {@code TE} header field name. */ public static final String TE = "TE"; /** The HTTP {@code Upgrade} header field name. */ public static final String UPGRADE = "Upgrade"; /** * The HTTP <a href="https://w3c.github.io/webappsec-upgrade-insecure-requests/#preference">{@code * Upgrade-Insecure-Requests}</a> header field name. * * @since 28.1 */ public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; /** The HTTP {@code User-Agent} header field name. */ public static final String USER_AGENT = "User-Agent"; // HTTP Response header fields /** The HTTP {@code Accept-Ranges} header field name. */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** The HTTP {@code Access-Control-Allow-Headers} header field name. */ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; /** The HTTP {@code Access-Control-Allow-Methods} header field name. */ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; /** The HTTP {@code Access-Control-Allow-Origin} header field name. */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; /** * The HTTP <a href="https://wicg.github.io/private-network-access/#headers">{@code * Access-Control-Allow-Private-Network}</a> header field name. * * @since 31.1 */ public static final String ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK = "Access-Control-Allow-Private-Network"; /** The HTTP {@code Access-Control-Allow-Credentials} header field name. */ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; /** The HTTP {@code Access-Control-Expose-Headers} header field name. */ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; /** The HTTP {@code Access-Control-Max-Age} header field name. */ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; /** The HTTP {@code Age} header field name. */ public static final String AGE = "Age"; /** The HTTP {@code Allow} header field name. */ public static final String ALLOW = "Allow"; /** The HTTP {@code Content-Disposition} header field name. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; /** The HTTP {@code Content-Encoding} header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** The HTTP {@code Content-Language} header field name. */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** The HTTP {@code Content-Location} header field name. */ public static final String CONTENT_LOCATION = "Content-Location"; /** The HTTP {@code Content-MD5} header field name. */ public static final String CONTENT_MD5 = "Content-MD5"; /** The HTTP {@code Content-Range} header field name. */ public static final String CONTENT_RANGE = "Content-Range"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-header-field">{@code * Content-Security-Policy}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-report-only-header-field"> * {@code Content-Security-Policy-Report-Only}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-Content-Security-Policy} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Firefox until * version 23 and the Internet Explorer version 10. Please, use {@link #CONTENT_SECURITY_POLICY} * to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY = "X-Content-Security-Policy"; /** * The HTTP nonstandard {@code X-Content-Security-Policy-Report-Only} header field name. It was * introduced in <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the * Firefox until version 23 and the Internet Explorer version 10. Please, use {@link * #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY_REPORT_ONLY = "X-Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-WebKit-CSP} header field name. It was introduced in <a * href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP = "X-WebKit-CSP"; /** * The HTTP nonstandard {@code X-WebKit-CSP-Report-Only} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP_REPORT_ONLY = "X-WebKit-CSP-Report-Only"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP">{@code * Cross-Origin-Embedder-Policy}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP-RO">{@code * Cross-Origin-Embedder-Policy-Report-Only}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY = "Cross-Origin-Embedder-Policy-Report-Only"; /** * The HTTP Cross-Origin-Opener-Policy header field name. * * @since 28.2 */ public static final String CROSS_ORIGIN_OPENER_POLICY = "Cross-Origin-Opener-Policy"; /** The HTTP {@code ETag} header field name. */ public static final String ETAG = "ETag"; /** The HTTP {@code Expires} header field name. */ public static final String EXPIRES = "Expires"; /** The HTTP {@code Last-Modified} header field name. */ public static final String LAST_MODIFIED = "Last-Modified"; /** The HTTP {@code Link} header field name. */ public static final String LINK = "Link"; /** The HTTP {@code Location} header field name. */ public static final String LOCATION = "Location"; /** * The HTTP {@code Keep-Alive} header field name. * * @since 31.0 */ public static final String KEEP_ALIVE = "Keep-Alive"; /** * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/no-vary-search.md">{@code * No-Vary-Seearch}</a> header field name. * * @since 32.0.0 */ public static final String NO_VARY_SEARCH = "No-Vary-Search"; /** * The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code Origin-Trial}</a> * header field name. * * @since 27.1 */ public static final String ORIGIN_TRIAL = "Origin-Trial"; /** The HTTP {@code P3P} header field name. Limited browser support. */ public static final String P3P = "P3P"; /** The HTTP {@code Proxy-Authenticate} header field name. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** The HTTP {@code Refresh} header field name. Non-standard header supported by most browsers. */ public static final String REFRESH = "Refresh"; /** * The HTTP <a href="https://www.w3.org/TR/reporting/">{@code Report-To}</a> header field name. * * @since 27.1 */ public static final String REPORT_TO = "Report-To"; /** The HTTP {@code Retry-After} header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** The HTTP {@code Server} header field name. */ public static final String SERVER = "Server"; /** * The HTTP <a href="https://www.w3.org/TR/server-timing/">{@code Server-Timing}</a> header field * name. * * @since 23.6 */ public static final String SERVER_TIMING = "Server-Timing"; /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker-Allowed}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER_ALLOWED = "Service-Worker-Allowed"; /** The HTTP {@code Set-Cookie} header field name. */ public static final String SET_COOKIE = "Set-Cookie"; /** The HTTP {@code Set-Cookie2} header field name. */ public static final String SET_COOKIE2 = "Set-Cookie2"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/SourceMap">{@code * SourceMap}</a> header field name. * * @since 27.1 */ public static final String SOURCE_MAP = "SourceMap"; /** * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/opt-in.md">{@code * Supports-Loading-Mode}</a> header field name. This can be used to specify, for example, <a * href="https://developer.chrome.com/docs/privacy-sandbox/fenced-frame/#server-opt-in">fenced * frames</a>. * * @since 32.0.0 */ public static final String SUPPORTS_LOADING_MODE = "Supports-Loading-Mode"; /** * The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">{@code * Strict-Transport-Security}</a> header field name. * * @since 15.0 */ public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; /** * The HTTP <a href="http://www.w3.org/TR/resource-timing/#cross-origin-resources">{@code * Timing-Allow-Origin}</a> header field name. * * @since 15.0 */ public static final String TIMING_ALLOW_ORIGIN = "Timing-Allow-Origin"; /** The HTTP {@code Trailer} header field name. */ public static final String TRAILER = "Trailer"; /** The HTTP {@code Transfer-Encoding} header field name. */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** The HTTP {@code Vary} header field name. */ public static final String VARY = "Vary"; /** The HTTP {@code WWW-Authenticate} header field name. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; // Common, non-standard HTTP header fields /** The HTTP {@code DNT} header field name. */ public static final String DNT = "DNT"; /** The HTTP {@code X-Content-Type-Options} header field name. */ public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-IP}</a> header field name. Header used for VAST requests to provide the IP address of * the device on whose behalf the request is being made. * * @since 31.0 */ public static final String X_DEVICE_IP = "X-Device-IP"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Referer}</a> header field name. Header used for VAST requests to provide the {@link * #REFERER} header value that the on-behalf-of client would have used when making a request * itself. * * @since 31.0 */ public static final String X_DEVICE_REFERER = "X-Device-Referer"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Accept-Language}</a> header field name. Header used for VAST requests to provide the * {@link #ACCEPT_LANGUAGE} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_ACCEPT_LANGUAGE = "X-Device-Accept-Language"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Requested-With}</a> header field name. Header used for VAST requests to provide the * {@link #X_REQUESTED_WITH} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_REQUESTED_WITH = "X-Device-Requested-With"; /** The HTTP {@code X-Do-Not-Track} header field name. */ public static final String X_DO_NOT_TRACK = "X-Do-Not-Track"; /** The HTTP {@code X-Forwarded-For} header field name (superseded by {@code Forwarded}). */ public static final String X_FORWARDED_FOR = "X-Forwarded-For"; /** The HTTP {@code X-Forwarded-Proto} header field name. */ public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host">{@code * X-Forwarded-Host}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; /** * The HTTP <a * href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html#x-forwarded-port">{@code * X-Forwarded-Port}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_PORT = "X-Forwarded-Port"; /** The HTTP {@code X-Frame-Options} header field name. */ public static final String X_FRAME_OPTIONS = "X-Frame-Options"; /** The HTTP {@code X-Powered-By} header field name. */ public static final String X_POWERED_BY = "X-Powered-By"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS = "Public-Key-Pins"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins-Report-Only}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS_REPORT_ONLY = "Public-Key-Pins-Report-Only"; /** * The HTTP {@code X-Request-ID} header field name. * * @since 30.1 */ public static final String X_REQUEST_ID = "X-Request-ID"; /** The HTTP {@code X-Requested-With} header field name. */ public static final String X_REQUESTED_WITH = "X-Requested-With"; /** The HTTP {@code X-User-IP} header field name. */ public static final String X_USER_IP = "X-User-IP"; /** * The HTTP <a * href="https://learn.microsoft.com/en-us/archive/blogs/ieinternals/internet-explorer-and-custom-http-headers#:~:text=X%2DDownload%2DOptions">{@code * X-Download-Options}</a> header field name. * * <p>When the new X-Download-Options header is present with the value {@code noopen}, the user is * prevented from opening a file download directly; instead, they must first save the file * locally. * * @since 24.1 */ public static final String X_DOWNLOAD_OPTIONS = "X-Download-Options"; /** The HTTP {@code X-XSS-Protection} header field name. */ public static final String X_XSS_PROTECTION = "X-XSS-Protection"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control">{@code * X-DNS-Prefetch-Control}</a> header controls DNS prefetch behavior. Value can be "on" or "off". * By default, DNS prefetching is "on" for HTTP pages and "off" for HTTPS pages. */ public static final String X_DNS_PREFETCH_CONTROL = "X-DNS-Prefetch-Control"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-From}</a> header field name. * * @since 19.0 */ public static final String PING_FROM = "Ping-From"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-To}</a> header field name. * * @since 19.0 */ public static final String PING_TO = "Ping-To"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * Purpose}</a> header field name. * * @since 28.0 */ public static final String PURPOSE = "Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Purpose}</a> header field name. * * @since 28.0 */ public static final String X_PURPOSE = "X-Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Moz}</a> header field name. * * @since 28.0 */ public static final String X_MOZ = "X-Moz"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Device-Memory">{@code * Device-Memory}</a> header field name. * * @since 31.0 */ public static final String DEVICE_MEMORY = "Device-Memory"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Downlink">{@code * Downlink}</a> header field name. * * @since 31.0 */ public static final String DOWNLINK = "Downlink"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ECT">{@code * ECT}</a> header field name. * * @since 31.0 */ public static final String ECT = "ECT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/RTT">{@code * RTT}</a> header field name. * * @since 31.0 */ public static final String RTT = "RTT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data">{@code * Save-Data}</a> header field name. * * @since 31.0 */ public static final String SAVE_DATA = "Save-Data"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Viewport-Width">{@code * Viewport-Width}</a> header field name. * * @since 31.0 */ public static final String VIEWPORT_WIDTH = "Viewport-Width"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Width">{@code * Width}</a> header field name. * * @since 31.0 */ public static final String WIDTH = "Width"; /** * The HTTP <a href="https://www.w3.org/TR/permissions-policy-1/">{@code Permissions-Policy}</a> * header field name. * * @since 31.0 */ public static final String PERMISSIONS_POLICY = "Permissions-Policy"; /** * The HTTP <a * href="https://w3c.github.io/webappsec-permissions-policy/#permissions-policy-report-only-http-header-field">{@code * Permissions-Policy-Report-Only}</a> header field name. * * @since 33.2.0 */ public static final String PERMISSIONS_POLICY_REPORT_ONLY = "Permissions-Policy-Report-Only"; /** * The HTTP <a * href="https://wicg.github.io/user-preference-media-features-headers/#sec-ch-prefers-color-scheme">{@code * Sec-CH-Prefers-Color-Scheme}</a> header field name. * * <p>This header is experimental. * * @since 31.0 */ public static final String SEC_CH_PREFERS_COLOR_SCHEME = "Sec-CH-Prefers-Color-Scheme"; /** * The HTTP <a * href="https://www.rfc-editor.org/rfc/rfc8942#name-the-accept-ch-response-head">{@code * Accept-CH}</a> header field name. * * @since 31.0 */ public static final String ACCEPT_CH = "Accept-CH"; /** * The HTTP <a * href="https://datatracker.ietf.org/doc/html/draft-davidben-http-client-hint-reliability-03.txt#section-3">{@code * Critical-CH}</a> header field name. * * @since 31.0 */ public static final String CRITICAL_CH = "Critical-CH"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua">{@code Sec-CH-UA}</a> * header field name. * * @since 30.0 */ public static final String SEC_CH_UA = "Sec-CH-UA"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-arch">{@code * Sec-CH-UA-Arch}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_ARCH = "Sec-CH-UA-Arch"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-model">{@code * Sec-CH-UA-Model}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MODEL = "Sec-CH-UA-Model"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform">{@code * Sec-CH-UA-Platform}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM = "Sec-CH-UA-Platform"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform-version">{@code * Sec-CH-UA-Platform-Version}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM_VERSION = "Sec-CH-UA-Platform-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @deprecated Prefer {@link SEC_CH_UA_FULL_VERSION_LIST}. * @since 30.0 */ @Deprecated public static final String SEC_CH_UA_FULL_VERSION = "Sec-CH-UA-Full-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version-list">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @since 31.1 */ public static final String SEC_CH_UA_FULL_VERSION_LIST = "Sec-CH-UA-Full-Version-List"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-mobile">{@code * Sec-CH-UA-Mobile}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MOBILE = "Sec-CH-UA-Mobile"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-wow64">{@code * Sec-CH-UA-WoW64}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_UA_WOW64 = "Sec-CH-UA-WoW64"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness">{@code * Sec-CH-UA-Bitness}</a> header field name. * * @since 31.0 */ public static final String SEC_CH_UA_BITNESS = "Sec-CH-UA-Bitness"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factor">{@code * Sec-CH-UA-Form-Factor}</a> header field name. * * @deprecated Prefer {@link SEC_CH_UA_FORM_FACTORS}. * @since 32.0.0 */ @Deprecated public static final String SEC_CH_UA_FORM_FACTOR = "Sec-CH-UA-Form-Factor"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factors">{@code * Sec-CH-UA-Form-Factors}</a> header field name. * * @since 33.3.0 */ public static final String SEC_CH_UA_FORM_FACTORS = "Sec-CH-UA-Form-Factors"; /** * The HTTP <a * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-width">{@code * Sec-CH-Viewport-Width}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_VIEWPORT_WIDTH = "Sec-CH-Viewport-Width"; /** * The HTTP <a * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-height">{@code * Sec-CH-Viewport-Height}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_VIEWPORT_HEIGHT = "Sec-CH-Viewport-Height"; /** * The HTTP <a href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-dpr">{@code * Sec-CH-DPR}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_DPR = "Sec-CH-DPR"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Dest}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_DEST = "Sec-Fetch-Dest"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Mode}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_MODE = "Sec-Fetch-Mode"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Site}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_SITE = "Sec-Fetch-Site"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-User}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_USER = "Sec-Fetch-User"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Metadata}</a> * header field name. * * @since 26.0 */ public static final String SEC_METADATA = "Sec-Metadata"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/draft-ietf-tokbind-https">{@code * Sec-Token-Binding}</a> header field name. * * @since 25.1 */ public static final String SEC_TOKEN_BINDING = "Sec-Token-Binding"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/draft-ietf-tokbind-ttrp">{@code * Sec-Provided-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_PROVIDED_TOKEN_BINDING_ID = "Sec-Provided-Token-Binding-ID"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/draft-ietf-tokbind-ttrp">{@code * Sec-Referred-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_REFERRED_TOKEN_BINDING_ID = "Sec-Referred-Token-Binding-ID"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Accept}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_ACCEPT = "Sec-WebSocket-Accept"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Extensions}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_EXTENSIONS = "Sec-WebSocket-Extensions"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code Sec-WebSocket-Key}</a> * header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_KEY = "Sec-WebSocket-Key"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Protocol}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc6455">{@code * Sec-WebSocket-Version}</a> header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version"; /** * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code * Sec-Browsing-Topics}</a> header field name. * * @since 32.0.0 */ public static final String SEC_BROWSING_TOPICS = "Sec-Browsing-Topics"; /** * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code * Observe-Browsing-Topics}</a> header field name. * * @since 32.0.0 */ public static final String OBSERVE_BROWSING_TOPICS = "Observe-Browsing-Topics"; /** * The HTTP <a * href="https://wicg.github.io/turtledove/#handling-direct-from-seller-signals">{@code * Sec-Ad-Auction-Fetch}</a> header field name. * * @since 33.0.0 */ public static final String SEC_AD_AUCTION_FETCH = "Sec-Ad-Auction-Fetch"; /** * The HTTP <a * href="https://privacycg.github.io/gpc-spec/#the-sec-gpc-header-field-for-http-requests">{@code * Sec-GPC}</a> header field name. * * @since 33.2.0 */ public static final String SEC_GPC = "Sec-GPC"; /** * The HTTP <a * href="https://wicg.github.io/turtledove/#handling-direct-from-seller-signals">{@code * Ad-Auction-Signals}</a> header field name. * * @since 33.0.0 */ public static final String AD_AUCTION_SIGNALS = "Ad-Auction-Signals"; /** * The HTTP <a href="https://wicg.github.io/turtledove/#http-headerdef-ad-auction-allowed">{@code * Ad-Auction-Allowed}</a> header field name. * * @since 33.2.0 */ public static final String AD_AUCTION_ALLOWED = "Ad-Auction-Allowed"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc8586">{@code CDN-Loop}</a> header * field name. * * @since 28.0 */ public static final String CDN_LOOP = "CDN-Loop"; /** * The HTTP <a href="https://datatracker.ietf.org/doc/html/rfc7838#page-8">{@code Alt-Svc}</a> * header field name. * * @since 33.4.0 */ public static final String ALT_SVC = "Alt-Svc"; }
googleapis/google-cloud-java
36,645
java-telcoautomation/proto-google-cloud-telcoautomation-v1/src/main/java/com/google/cloud/telcoautomation/v1/UpdateHydratedDeploymentRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/telcoautomation/v1/telcoautomation.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.telcoautomation.v1; /** * * * <pre> * Request object for `UpdateHydratedDeployment`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest} */ public final class UpdateHydratedDeploymentRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest) UpdateHydratedDeploymentRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateHydratedDeploymentRequest.newBuilder() to construct. private UpdateHydratedDeploymentRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateHydratedDeploymentRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateHydratedDeploymentRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_UpdateHydratedDeploymentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_UpdateHydratedDeploymentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest.class, com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest.Builder.class); } private int bitField0_; public static final int HYDRATED_DEPLOYMENT_FIELD_NUMBER = 1; private com.google.cloud.telcoautomation.v1.HydratedDeployment hydratedDeployment_; /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the hydratedDeployment field is set. */ @java.lang.Override public boolean hasHydratedDeployment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The hydratedDeployment. */ @java.lang.Override public com.google.cloud.telcoautomation.v1.HydratedDeployment getHydratedDeployment() { return hydratedDeployment_ == null ? com.google.cloud.telcoautomation.v1.HydratedDeployment.getDefaultInstance() : hydratedDeployment_; } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.telcoautomation.v1.HydratedDeploymentOrBuilder getHydratedDeploymentOrBuilder() { return hydratedDeployment_ == null ? com.google.cloud.telcoautomation.v1.HydratedDeployment.getDefaultInstance() : hydratedDeployment_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The list of fields to update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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, getHydratedDeployment()); } 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, getHydratedDeployment()); } 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.telcoautomation.v1.UpdateHydratedDeploymentRequest)) { return super.equals(obj); } com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest other = (com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest) obj; if (hasHydratedDeployment() != other.hasHydratedDeployment()) return false; if (hasHydratedDeployment()) { if (!getHydratedDeployment().equals(other.getHydratedDeployment())) 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 (hasHydratedDeployment()) { hash = (37 * hash) + HYDRATED_DEPLOYMENT_FIELD_NUMBER; hash = (53 * hash) + getHydratedDeployment().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.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest 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 `UpdateHydratedDeployment`. * </pre> * * Protobuf type {@code google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest) com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_UpdateHydratedDeploymentRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_UpdateHydratedDeploymentRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest.class, com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest.Builder.class); } // Construct using // com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getHydratedDeploymentFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; hydratedDeployment_ = null; if (hydratedDeploymentBuilder_ != null) { hydratedDeploymentBuilder_.dispose(); hydratedDeploymentBuilder_ = 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.telcoautomation.v1.TelcoautomationProto .internal_static_google_cloud_telcoautomation_v1_UpdateHydratedDeploymentRequest_descriptor; } @java.lang.Override public com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest getDefaultInstanceForType() { return com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest build() { com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest buildPartial() { com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest result = new com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.hydratedDeployment_ = hydratedDeploymentBuilder_ == null ? hydratedDeployment_ : hydratedDeploymentBuilder_.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.telcoautomation.v1.UpdateHydratedDeploymentRequest) { return mergeFrom( (com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest other) { if (other == com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest .getDefaultInstance()) return this; if (other.hasHydratedDeployment()) { mergeHydratedDeployment(other.getHydratedDeployment()); } 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( getHydratedDeploymentFieldBuilder().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.telcoautomation.v1.HydratedDeployment hydratedDeployment_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1.HydratedDeployment, com.google.cloud.telcoautomation.v1.HydratedDeployment.Builder, com.google.cloud.telcoautomation.v1.HydratedDeploymentOrBuilder> hydratedDeploymentBuilder_; /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the hydratedDeployment field is set. */ public boolean hasHydratedDeployment() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The hydratedDeployment. */ public com.google.cloud.telcoautomation.v1.HydratedDeployment getHydratedDeployment() { if (hydratedDeploymentBuilder_ == null) { return hydratedDeployment_ == null ? com.google.cloud.telcoautomation.v1.HydratedDeployment.getDefaultInstance() : hydratedDeployment_; } else { return hydratedDeploymentBuilder_.getMessage(); } } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setHydratedDeployment( com.google.cloud.telcoautomation.v1.HydratedDeployment value) { if (hydratedDeploymentBuilder_ == null) { if (value == null) { throw new NullPointerException(); } hydratedDeployment_ = value; } else { hydratedDeploymentBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setHydratedDeployment( com.google.cloud.telcoautomation.v1.HydratedDeployment.Builder builderForValue) { if (hydratedDeploymentBuilder_ == null) { hydratedDeployment_ = builderForValue.build(); } else { hydratedDeploymentBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeHydratedDeployment( com.google.cloud.telcoautomation.v1.HydratedDeployment value) { if (hydratedDeploymentBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && hydratedDeployment_ != null && hydratedDeployment_ != com.google.cloud.telcoautomation.v1.HydratedDeployment.getDefaultInstance()) { getHydratedDeploymentBuilder().mergeFrom(value); } else { hydratedDeployment_ = value; } } else { hydratedDeploymentBuilder_.mergeFrom(value); } if (hydratedDeployment_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearHydratedDeployment() { bitField0_ = (bitField0_ & ~0x00000001); hydratedDeployment_ = null; if (hydratedDeploymentBuilder_ != null) { hydratedDeploymentBuilder_.dispose(); hydratedDeploymentBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.telcoautomation.v1.HydratedDeployment.Builder getHydratedDeploymentBuilder() { bitField0_ |= 0x00000001; onChanged(); return getHydratedDeploymentFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.telcoautomation.v1.HydratedDeploymentOrBuilder getHydratedDeploymentOrBuilder() { if (hydratedDeploymentBuilder_ != null) { return hydratedDeploymentBuilder_.getMessageOrBuilder(); } else { return hydratedDeployment_ == null ? com.google.cloud.telcoautomation.v1.HydratedDeployment.getDefaultInstance() : hydratedDeployment_; } } /** * * * <pre> * Required. The hydrated deployment to update. * </pre> * * <code> * .google.cloud.telcoautomation.v1.HydratedDeployment hydrated_deployment = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1.HydratedDeployment, com.google.cloud.telcoautomation.v1.HydratedDeployment.Builder, com.google.cloud.telcoautomation.v1.HydratedDeploymentOrBuilder> getHydratedDeploymentFieldBuilder() { if (hydratedDeploymentBuilder_ == null) { hydratedDeploymentBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.telcoautomation.v1.HydratedDeployment, com.google.cloud.telcoautomation.v1.HydratedDeployment.Builder, com.google.cloud.telcoautomation.v1.HydratedDeploymentOrBuilder>( getHydratedDeployment(), getParentForChildren(), isClean()); hydratedDeployment_ = null; } return hydratedDeploymentBuilder_; } 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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </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 update. Update mask supports a special * value `*` which fully replaces (equivalent to PUT) the resource provided. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest) } // @@protoc_insertion_point(class_scope:google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest) private static final com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest(); } public static com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateHydratedDeploymentRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateHydratedDeploymentRequest>() { @java.lang.Override public UpdateHydratedDeploymentRequest 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<UpdateHydratedDeploymentRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateHydratedDeploymentRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.telcoautomation.v1.UpdateHydratedDeploymentRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/guava
36,805
android/guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
/* * Copyright (C) 2011 The Guava 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.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newArrayListWithCapacity; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.j2objc.annotations.Weak; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import org.jspecify.annotations.Nullable; /** * The {@code CycleDetectingLockFactory} creates {@link ReentrantLock} instances and {@link * ReentrantReadWriteLock} instances that detect potential deadlock by checking for cycles in lock * acquisition order. * * <p>Potential deadlocks detected when calling the {@code lock()}, {@code lockInterruptibly()}, or * {@code tryLock()} methods will result in the execution of the {@link Policy} specified when * creating the factory. The currently available policies are: * * <ul> * <li>DISABLED * <li>WARN * <li>THROW * </ul> * * <p>The locks created by a factory instance will detect lock acquisition cycles with locks created * by other {@code CycleDetectingLockFactory} instances (except those with {@code Policy.DISABLED}). * A lock's behavior when a cycle is detected, however, is defined by the {@code Policy} of the * factory that created it. This allows detection of cycles across components while delegating * control over lock behavior to individual components. * * <p>Applications are encouraged to use a {@code CycleDetectingLockFactory} to create any locks for * which external/unmanaged code is executed while the lock is held. (See caveats under * <strong>Performance</strong>). * * <p><strong>Cycle Detection</strong> * * <p>Deadlocks can arise when locks are acquired in an order that forms a cycle. In a simple * example involving two locks and two threads, deadlock occurs when one thread acquires Lock A, and * then Lock B, while another thread acquires Lock B, and then Lock A: * * <pre> * Thread1: acquire(LockA) --X acquire(LockB) * Thread2: acquire(LockB) --X acquire(LockA) * </pre> * * <p>Neither thread will progress because each is waiting for the other. In more complex * applications, cycles can arise from interactions among more than 2 locks: * * <pre> * Thread1: acquire(LockA) --X acquire(LockB) * Thread2: acquire(LockB) --X acquire(LockC) * ... * ThreadN: acquire(LockN) --X acquire(LockA) * </pre> * * <p>The implementation detects cycles by constructing a directed graph in which each lock * represents a node and each edge represents an acquisition ordering between two locks. * * <ul> * <li>Each lock adds (and removes) itself to/from a ThreadLocal Set of acquired locks when the * Thread acquires its first hold (and releases its last remaining hold). * <li>Before the lock is acquired, the lock is checked against the current set of acquired * locks---to each of the acquired locks, an edge from the soon-to-be-acquired lock is either * verified or created. * <li>If a new edge needs to be created, the outgoing edges of the acquired locks are traversed * to check for a cycle that reaches the lock to be acquired. If no cycle is detected, a new * "safe" edge is created. * <li>If a cycle is detected, an "unsafe" (cyclic) edge is created to represent a potential * deadlock situation, and the appropriate Policy is executed. * </ul> * * <p>Note that detection of potential deadlock does not necessarily indicate that deadlock will * happen, as it is possible that higher level application logic prevents the cyclic lock * acquisition from occurring. One example of a false positive is: * * <pre> * LockA -&gt; LockB -&gt; LockC * LockA -&gt; LockC -&gt; LockB * </pre> * * <p><strong>ReadWriteLocks</strong> * * <p>While {@code ReadWriteLock} instances have different properties and can form cycles without * potential deadlock, this class treats {@code ReadWriteLock} instances as equivalent to * traditional exclusive locks. Although this increases the false positives that the locks detect * (i.e. cycles that will not actually result in deadlock), it simplifies the algorithm and * implementation considerably. The assumption is that a user of this factory wishes to eliminate * any cyclic acquisition ordering. * * <p><strong>Explicit Lock Acquisition Ordering</strong> * * <p>The {@link CycleDetectingLockFactory.WithExplicitOrdering} class can be used to enforce an * application-specific ordering in addition to performing general cycle detection. * * <p><strong>Garbage Collection</strong> * * <p>In order to allow proper garbage collection of unused locks, the edges of the lock graph are * weak references. * * <p><strong>Performance</strong> * * <p>The extra bookkeeping done by cycle detecting locks comes at some cost to performance. * Benchmarks (as of December 2011) show that: * * <ul> * <li>for an unnested {@code lock()} and {@code unlock()}, a cycle detecting lock takes 38ns as * opposed to the 24ns taken by a plain lock. * <li>for nested locking, the cost increases with the depth of the nesting: * <ul> * <li>2 levels: average of 64ns per lock()/unlock() * <li>3 levels: average of 77ns per lock()/unlock() * <li>4 levels: average of 99ns per lock()/unlock() * <li>5 levels: average of 103ns per lock()/unlock() * <li>10 levels: average of 184ns per lock()/unlock() * <li>20 levels: average of 393ns per lock()/unlock() * </ul> * </ul> * * <p>As such, the CycleDetectingLockFactory may not be suitable for performance-critical * applications which involve tightly-looped or deeply-nested locking algorithms. * * @author Darick Tong * @since 13.0 */ @J2ktIncompatible @GwtIncompatible public class CycleDetectingLockFactory { /** * Encapsulates the action to be taken when a potential deadlock is encountered. Clients can use * one of the predefined {@link Policies} or specify a custom implementation. Implementations must * be thread-safe. * * @since 13.0 */ public interface Policy { /** * Called when a potential deadlock is encountered. Implementations can throw the given {@code * exception} and/or execute other desired logic. * * <p>Note that the method will be called even upon an invocation of {@code tryLock()}. Although * {@code tryLock()} technically recovers from deadlock by eventually timing out, this behavior * is chosen based on the assumption that it is the application's wish to prohibit any cyclical * lock acquisitions. */ void handlePotentialDeadlock(PotentialDeadlockException exception); } /** * Pre-defined {@link Policy} implementations. * * @since 13.0 */ public enum Policies implements Policy { /** * When potential deadlock is detected, this policy results in the throwing of the {@code * PotentialDeadlockException} indicating the potential deadlock, which includes stack traces * illustrating the cycle in lock acquisition order. */ THROW { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { throw e; } }, /** * When potential deadlock is detected, this policy results in the logging of a {@link * Level#SEVERE} message indicating the potential deadlock, which includes stack traces * illustrating the cycle in lock acquisition order. */ WARN { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { logger.get().log(Level.SEVERE, "Detected potential deadlock", e); } }, /** * Disables cycle detection. This option causes the factory to return unmodified lock * implementations provided by the JDK, and is provided to allow applications to easily * parameterize when cycle detection is enabled. * * <p>Note that locks created by a factory with this policy will <em>not</em> participate the * cycle detection performed by locks created by other factories. */ DISABLED { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) {} }; } /** Creates a new factory with the specified policy. */ public static CycleDetectingLockFactory newInstance(Policy policy) { return new CycleDetectingLockFactory(policy); } /** Equivalent to {@code newReentrantLock(lockName, false)}. */ public ReentrantLock newReentrantLock(String lockName) { return newReentrantLock(lockName, false); } /** * Creates a {@link ReentrantLock} with the given fairness policy. The {@code lockName} is used in * the warning or exception output to help identify the locks involved in the detected deadlock. */ public ReentrantLock newReentrantLock(String lockName, boolean fair) { return policy == Policies.DISABLED ? new ReentrantLock(fair) : new CycleDetectingReentrantLock(new LockGraphNode(lockName), fair); } /** Equivalent to {@code newReentrantReadWriteLock(lockName, false)}. */ public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName) { return newReentrantReadWriteLock(lockName, false); } /** * Creates a {@link ReentrantReadWriteLock} with the given fairness policy. The {@code lockName} * is used in the warning or exception output to help identify the locks involved in the detected * deadlock. */ public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName, boolean fair) { return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair) : new CycleDetectingReentrantReadWriteLock(new LockGraphNode(lockName), fair); } // A static mapping from an Enum type to its set of LockGraphNodes. private static final ConcurrentMap< Class<? extends Enum<?>>, Map<? extends Enum<?>, LockGraphNode>> lockGraphNodesPerType = new MapMaker().weakKeys().makeMap(); /** Creates a {@code CycleDetectingLockFactory.WithExplicitOrdering<E>}. */ public static <E extends Enum<E>> WithExplicitOrdering<E> newInstanceWithExplicitOrdering( Class<E> enumClass, Policy policy) { // createNodes maps each enumClass to a Map with the corresponding enum key // type. checkNotNull(enumClass); checkNotNull(policy); @SuppressWarnings("unchecked") Map<E, LockGraphNode> lockGraphNodes = (Map<E, LockGraphNode>) getOrCreateNodes(enumClass); return new WithExplicitOrdering<>(policy, lockGraphNodes); } @SuppressWarnings("unchecked") private static <E extends Enum<E>> Map<? extends E, LockGraphNode> getOrCreateNodes( Class<E> clazz) { Map<E, LockGraphNode> existing = (Map<E, LockGraphNode>) lockGraphNodesPerType.get(clazz); if (existing != null) { return existing; } Map<E, LockGraphNode> created = createNodes(clazz); existing = (Map<E, LockGraphNode>) lockGraphNodesPerType.putIfAbsent(clazz, created); return MoreObjects.firstNonNull(existing, created); } /** * For a given Enum type, creates an immutable map from each of the Enum's values to a * corresponding LockGraphNode, with the {@code allowedPriorLocks} and {@code * disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the * associated Enum values. */ @VisibleForTesting static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) { EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz); E[] keys = clazz.getEnumConstants(); int numKeys = keys.length; ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys); // Create a LockGraphNode for each enum value. for (E key : keys) { LockGraphNode node = new LockGraphNode(getLockName(key)); nodes.add(node); map.put(key, node); } // Pre-populate all allowedPriorLocks with nodes of smaller ordinal. for (int i = 1; i < numKeys; i++) { nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i)); } // Pre-populate all disallowedPriorLocks with nodes of larger ordinal. for (int i = 0; i < numKeys - 1; i++) { nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys)); } return Collections.unmodifiableMap(map); } /** * For the given Enum value {@code rank}, returns the value's {@code "EnumClass.name"}, which is * used in exception and warning output. */ private static String getLockName(Enum<?> rank) { return rank.getDeclaringClass().getSimpleName() + "." + rank.name(); } /** * A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the additional enforcement of * an application-specified ordering of lock acquisitions. The application defines the allowed * ordering with an {@code Enum} whose values each correspond to a lock type. The order in which * the values are declared dictates the allowed order of lock acquisition. In other words, locks * corresponding to smaller values of {@link Enum#ordinal()} should only be acquired before locks * with larger ordinals. Example: * * {@snippet : * enum MyLockOrder { * FIRST, SECOND, THIRD; * } * * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(Policies.THROW); * * Lock lock1 = factory.newReentrantLock(MyLockOrder.FIRST); * Lock lock2 = factory.newReentrantLock(MyLockOrder.SECOND); * Lock lock3 = factory.newReentrantLock(MyLockOrder.THIRD); * * lock1.lock(); * lock3.lock(); * lock2.lock(); // will throw an IllegalStateException * } * * <p>As with all locks created by instances of {@code CycleDetectingLockFactory} explicitly * ordered locks participate in general cycle detection with all other cycle detecting locks, and * a lock's behavior when detecting a cyclic lock acquisition is defined by the {@code Policy} of * the factory that created it. * * <p>Note, however, that although multiple locks can be created for a given Enum value, whether * it be through separate factory instances or through multiple calls to the same factory, * attempting to acquire multiple locks with the same Enum value (within the same thread) will * result in an IllegalStateException regardless of the factory's policy. For example: * * {@snippet : * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory1 = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...); * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory2 = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...); * * Lock lockA = factory1.newReentrantLock(MyLockOrder.FIRST); * Lock lockB = factory1.newReentrantLock(MyLockOrder.FIRST); * Lock lockC = factory2.newReentrantLock(MyLockOrder.FIRST); * * lockA.lock(); * * lockB.lock(); // will throw an IllegalStateException * lockC.lock(); // will throw an IllegalStateException * * lockA.lock(); // reentrant acquisition is okay * } * * <p>It is the responsibility of the application to ensure that multiple lock instances with the * same rank are never acquired in the same thread. * * @param <E> The Enum type representing the explicit lock ordering. * @since 13.0 */ public static final class WithExplicitOrdering<E extends Enum<E>> extends CycleDetectingLockFactory { private final Map<E, LockGraphNode> lockGraphNodes; @VisibleForTesting WithExplicitOrdering(Policy policy, Map<E, LockGraphNode> lockGraphNodes) { super(policy); this.lockGraphNodes = lockGraphNodes; } /** Equivalent to {@code newReentrantLock(rank, false)}. */ public ReentrantLock newReentrantLock(E rank) { return newReentrantLock(rank, false); } /** * Creates a {@link ReentrantLock} with the given fairness policy and rank. The values returned * by {@link Enum#getDeclaringClass()} and {@link Enum#name()} are used to describe the lock in * warning or exception output. * * @throws IllegalStateException If the factory has already created a {@code Lock} with the * specified rank. */ public ReentrantLock newReentrantLock(E rank, boolean fair) { return policy == Policies.DISABLED ? new ReentrantLock(fair) // requireNonNull is safe because createNodes inserts an entry for every E. // (If the caller passes `null` for the `rank` parameter, this will throw, but that's OK.) : new CycleDetectingReentrantLock(requireNonNull(lockGraphNodes.get(rank)), fair); } /** Equivalent to {@code newReentrantReadWriteLock(rank, false)}. */ public ReentrantReadWriteLock newReentrantReadWriteLock(E rank) { return newReentrantReadWriteLock(rank, false); } /** * Creates a {@link ReentrantReadWriteLock} with the given fairness policy and rank. The values * returned by {@link Enum#getDeclaringClass()} and {@link Enum#name()} are used to describe the * lock in warning or exception output. * * @throws IllegalStateException If the factory has already created a {@code Lock} with the * specified rank. */ public ReentrantReadWriteLock newReentrantReadWriteLock(E rank, boolean fair) { return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair) // requireNonNull is safe because createNodes inserts an entry for every E. // (If the caller passes `null` for the `rank` parameter, this will throw, but that's OK.) : new CycleDetectingReentrantReadWriteLock( requireNonNull(lockGraphNodes.get(rank)), fair); } } //////// Implementation ///////// private static final LazyLogger logger = new LazyLogger(CycleDetectingLockFactory.class); final Policy policy; private CycleDetectingLockFactory(Policy policy) { this.policy = checkNotNull(policy); } /** * Tracks the currently acquired locks for each Thread, kept up to date by calls to {@link * #aboutToAcquire(CycleDetectingLock)} and {@link #lockStateChanged(CycleDetectingLock)}. */ // This is logically a Set, but an ArrayList is used to minimize the amount // of allocation done on lock()/unlock(). private static final ThreadLocal<List<LockGraphNode>> acquiredLocks = new ThreadLocal<List<LockGraphNode>>() { @Override protected List<LockGraphNode> initialValue() { return newArrayListWithCapacity(3); } }; /** * A Throwable used to record a stack trace that illustrates an example of a specific lock * acquisition ordering. The top of the stack trace is truncated such that it starts with the * acquisition of the lock in question, e.g. * * <pre> * com...ExampleStackTrace: LockB -&gt; LockC * at com...CycleDetectingReentrantLock.lock(CycleDetectingLockFactory.java:443) * at ... * at ... * at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123) * </pre> */ private static class ExampleStackTrace extends IllegalStateException { static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; static final ImmutableSet<String> EXCLUDED_CLASS_NAMES = ImmutableSet.of( CycleDetectingLockFactory.class.getName(), ExampleStackTrace.class.getName(), LockGraphNode.class.getName()); ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) { super(node1.getLockName() + " -> " + node2.getLockName()); StackTraceElement[] origStackTrace = getStackTrace(); for (int i = 0, n = origStackTrace.length; i < n; i++) { if (WithExplicitOrdering.class.getName().equals(origStackTrace[i].getClassName())) { // For pre-populated disallowedPriorLocks edges, omit the stack trace. setStackTrace(EMPTY_STACK_TRACE); break; } if (!EXCLUDED_CLASS_NAMES.contains(origStackTrace[i].getClassName())) { setStackTrace(Arrays.copyOfRange(origStackTrace, i, n)); break; } } } } /** * Represents a detected cycle in lock acquisition ordering. The exception includes a causal chain * of {@code ExampleStackTrace} instances to illustrate the cycle, e.g. * * <pre> * com....PotentialDeadlockException: Potential Deadlock from LockC -&gt; ReadWriteA * at ... * at ... * Caused by: com...ExampleStackTrace: LockB -&gt; LockC * at ... * at ... * Caused by: com...ExampleStackTrace: ReadWriteA -&gt; LockB * at ... * at ... * </pre> * * <p>Instances are logged for the {@code Policies.WARN}, and thrown for {@code Policies.THROW}. * * @since 13.0 */ public static final class PotentialDeadlockException extends ExampleStackTrace { private final ExampleStackTrace conflictingStackTrace; private PotentialDeadlockException( LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) { super(node1, node2); this.conflictingStackTrace = conflictingStackTrace; initCause(conflictingStackTrace); } public ExampleStackTrace getConflictingStackTrace() { return conflictingStackTrace; } /** * Appends the chain of messages from the {@code conflictingStackTrace} to the original {@code * message}. */ @Override public String getMessage() { // requireNonNull is safe because ExampleStackTrace sets a non-null message. StringBuilder message = new StringBuilder(requireNonNull(super.getMessage())); for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) { message.append(", ").append(t.getMessage()); } return message.toString(); } } /** * Internal Lock implementations implement the {@code CycleDetectingLock} interface, allowing the * detection logic to treat all locks in the same manner. */ private interface CycleDetectingLock { /** * @return the {@link LockGraphNode} associated with this lock. */ LockGraphNode getLockGraphNode(); /** * @return {@code true} if the current thread has acquired this lock. */ boolean isAcquiredByCurrentThread(); } /** * A {@code LockGraphNode} associated with each lock instance keeps track of the directed edges in * the lock acquisition graph. */ private static final class LockGraphNode { /** * The map tracking the locks that are known to be acquired before this lock, each associated * with an example stack trace. Locks are weakly keyed to allow proper garbage collection when * they are no longer referenced. */ final Map<LockGraphNode, ExampleStackTrace> allowedPriorLocks = new MapMaker().weakKeys().makeMap(); /** * The map tracking lock nodes that can cause a lock acquisition cycle if acquired before this * node. */ final Map<LockGraphNode, PotentialDeadlockException> disallowedPriorLocks = new MapMaker().weakKeys().makeMap(); final String lockName; LockGraphNode(String lockName) { this.lockName = Preconditions.checkNotNull(lockName); } String getLockName() { return lockName; } void checkAcquiredLocks(Policy policy, List<LockGraphNode> acquiredLocks) { for (LockGraphNode acquiredLock : acquiredLocks) { checkAcquiredLock(policy, acquiredLock); } } /** * Checks the acquisition-ordering between {@code this}, which is about to be acquired, and the * specified {@code acquiredLock}. * * <p>When this method returns, the {@code acquiredLock} should be in either the {@code * preAcquireLocks} map, for the case in which it is safe to acquire {@code this} after the * {@code acquiredLock}, or in the {@code disallowedPriorLocks} map, in which case it is not * safe. */ void checkAcquiredLock(Policy policy, LockGraphNode acquiredLock) { // checkAcquiredLock() should never be invoked by a lock that has already // been acquired. For unordered locks, aboutToAcquire() ensures this by // checking isAcquiredByCurrentThread(). For ordered locks, however, this // can happen because multiple locks may share the same LockGraphNode. In // this situation, throw an IllegalStateException as defined by contract // described in the documentation of WithExplicitOrdering. Preconditions.checkState( this != acquiredLock, "Attempted to acquire multiple locks with the same rank %s", acquiredLock.getLockName()); if (allowedPriorLocks.containsKey(acquiredLock)) { // The acquisition ordering from "acquiredLock" to "this" has already // been verified as safe. In a properly written application, this is // the common case. return; } PotentialDeadlockException previousDeadlockException = disallowedPriorLocks.get(acquiredLock); if (previousDeadlockException != null) { // Previously determined to be an unsafe lock acquisition. // Create a new PotentialDeadlockException with the same causal chain // (the example cycle) as that of the cached exception. PotentialDeadlockException exception = new PotentialDeadlockException( acquiredLock, this, previousDeadlockException.getConflictingStackTrace()); policy.handlePotentialDeadlock(exception); return; } // Otherwise, it's the first time seeing this lock relationship. Look for // a path from the acquiredLock to this. Set<LockGraphNode> seen = Sets.newIdentityHashSet(); ExampleStackTrace path = acquiredLock.findPathTo(this, seen); if (path == null) { // this can be safely acquired after the acquiredLock. // // Note that there is a race condition here which can result in missing // a cyclic edge: it's possible for two threads to simultaneous find // "safe" edges which together form a cycle. Preventing this race // condition efficiently without _introducing_ deadlock is probably // tricky. For now, just accept the race condition---missing a warning // now and then is still better than having no deadlock detection. allowedPriorLocks.put(acquiredLock, new ExampleStackTrace(acquiredLock, this)); } else { // Unsafe acquisition order detected. Create and cache a // PotentialDeadlockException. PotentialDeadlockException exception = new PotentialDeadlockException(acquiredLock, this, path); disallowedPriorLocks.put(acquiredLock, exception); policy.handlePotentialDeadlock(exception); } } /** * Performs a depth-first traversal of the graph edges defined by each node's {@code * allowedPriorLocks} to find a path between {@code this} and the specified {@code lock}. * * @return If a path was found, a chained {@link ExampleStackTrace} illustrating the path to the * {@code lock}, or {@code null} if no path was found. */ private @Nullable ExampleStackTrace findPathTo(LockGraphNode node, Set<LockGraphNode> seen) { if (!seen.add(this)) { return null; // Already traversed this node. } ExampleStackTrace found = allowedPriorLocks.get(node); if (found != null) { return found; // Found a path ending at the node! } // Recurse the edges. for (Entry<LockGraphNode, ExampleStackTrace> entry : allowedPriorLocks.entrySet()) { LockGraphNode preAcquiredLock = entry.getKey(); found = preAcquiredLock.findPathTo(node, seen); if (found != null) { // One of this node's allowedPriorLocks found a path. Prepend an // ExampleStackTrace(preAcquiredLock, this) to the returned chain of // ExampleStackTraces. ExampleStackTrace path = new ExampleStackTrace(preAcquiredLock, this); path.setStackTrace(entry.getValue().getStackTrace()); path.initCause(found); return path; } } return null; } } /** * CycleDetectingLock implementations must call this method before attempting to acquire the lock. */ private void aboutToAcquire(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get List<LockGraphNode> acquiredLockList = requireNonNull(acquiredLocks.get()); LockGraphNode node = lock.getLockGraphNode(); node.checkAcquiredLocks(policy, acquiredLockList); acquiredLockList.add(node); } } /** * CycleDetectingLock implementations must call this method in a {@code finally} clause after any * attempt to change the lock state, including both lock and unlock attempts. Failure to do so can * result in corrupting the acquireLocks set. */ private static void lockStateChanged(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get List<LockGraphNode> acquiredLockList = requireNonNull(acquiredLocks.get()); LockGraphNode node = lock.getLockGraphNode(); // Iterate in reverse because locks are usually locked/unlocked in a // LIFO order. for (int i = acquiredLockList.size() - 1; i >= 0; i--) { if (acquiredLockList.get(i) == node) { acquiredLockList.remove(i); break; } } } } final class CycleDetectingReentrantLock extends ReentrantLock implements CycleDetectingLock { private final LockGraphNode lockGraphNode; private CycleDetectingReentrantLock(LockGraphNode lockGraphNode, boolean fair) { super(fair); this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode); } ///// CycleDetectingLock methods. ///// @Override public LockGraphNode getLockGraphNode() { return lockGraphNode; } @Override public boolean isAcquiredByCurrentThread() { return isHeldByCurrentThread(); } ///// Overridden ReentrantLock methods. ///// @Override public void lock() { aboutToAcquire(this); try { super.lock(); } finally { lockStateChanged(this); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(this); try { super.lockInterruptibly(); } finally { lockStateChanged(this); } } @Override public boolean tryLock() { aboutToAcquire(this); try { return super.tryLock(); } finally { lockStateChanged(this); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(this); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(this); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(this); } } } final class CycleDetectingReentrantReadWriteLock extends ReentrantReadWriteLock implements CycleDetectingLock { // These ReadLock/WriteLock implementations shadow those in the // ReentrantReadWriteLock superclass. They are simply wrappers around the // internal Sync object, so this is safe since the shadowed locks are never // exposed or used. private final CycleDetectingReentrantReadLock readLock; private final CycleDetectingReentrantWriteLock writeLock; private final LockGraphNode lockGraphNode; private CycleDetectingReentrantReadWriteLock(LockGraphNode lockGraphNode, boolean fair) { super(fair); this.readLock = new CycleDetectingReentrantReadLock(this); this.writeLock = new CycleDetectingReentrantWriteLock(this); this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode); } ///// Overridden ReentrantReadWriteLock methods. ///// @Override public ReadLock readLock() { return readLock; } @Override public WriteLock writeLock() { return writeLock; } ///// CycleDetectingLock methods. ///// @Override public LockGraphNode getLockGraphNode() { return lockGraphNode; } @Override public boolean isAcquiredByCurrentThread() { return isWriteLockedByCurrentThread() || getReadHoldCount() > 0; } } private final class CycleDetectingReentrantReadLock extends ReentrantReadWriteLock.ReadLock { @Weak final CycleDetectingReentrantReadWriteLock readWriteLock; CycleDetectingReentrantReadLock(CycleDetectingReentrantReadWriteLock readWriteLock) { super(readWriteLock); this.readWriteLock = readWriteLock; } @Override public void lock() { aboutToAcquire(readWriteLock); try { super.lock(); } finally { lockStateChanged(readWriteLock); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(readWriteLock); try { super.lockInterruptibly(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock() { aboutToAcquire(readWriteLock); try { return super.tryLock(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(readWriteLock); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(readWriteLock); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(readWriteLock); } } } private final class CycleDetectingReentrantWriteLock extends ReentrantReadWriteLock.WriteLock { @Weak final CycleDetectingReentrantReadWriteLock readWriteLock; CycleDetectingReentrantWriteLock(CycleDetectingReentrantReadWriteLock readWriteLock) { super(readWriteLock); this.readWriteLock = readWriteLock; } @Override public void lock() { aboutToAcquire(readWriteLock); try { super.lock(); } finally { lockStateChanged(readWriteLock); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(readWriteLock); try { super.lockInterruptibly(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock() { aboutToAcquire(readWriteLock); try { return super.tryLock(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(readWriteLock); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(readWriteLock); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(readWriteLock); } } } }
googleapis/google-cloud-java
36,488
java-shopping-merchant-datasources/proto-google-shopping-merchant-datasources-v1/src/main/java/com/google/shopping/merchant/datasources/v1/DataSourceReference.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/datasources/v1/datasourcetypes.proto // Protobuf Java Version: 3.25.8 package com.google.shopping.merchant.datasources.v1; /** * * * <pre> * Data source reference can be used to manage related data sources within the * data source service. * </pre> * * Protobuf type {@code google.shopping.merchant.datasources.v1.DataSourceReference} */ public final class DataSourceReference extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.shopping.merchant.datasources.v1.DataSourceReference) DataSourceReferenceOrBuilder { private static final long serialVersionUID = 0L; // Use DataSourceReference.newBuilder() to construct. private DataSourceReference(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DataSourceReference() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DataSourceReference(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.datasources.v1.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1_DataSourceReference_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.datasources.v1.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1_DataSourceReference_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.datasources.v1.DataSourceReference.class, com.google.shopping.merchant.datasources.v1.DataSourceReference.Builder.class); } private int dataSourceIdCase_ = 0; @SuppressWarnings("serial") private java.lang.Object dataSourceId_; public enum DataSourceIdCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { SELF(1), PRIMARY_DATA_SOURCE_NAME(3), SUPPLEMENTAL_DATA_SOURCE_NAME(2), DATASOURCEID_NOT_SET(0); private final int value; private DataSourceIdCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static DataSourceIdCase valueOf(int value) { return forNumber(value); } public static DataSourceIdCase forNumber(int value) { switch (value) { case 1: return SELF; case 3: return PRIMARY_DATA_SOURCE_NAME; case 2: return SUPPLEMENTAL_DATA_SOURCE_NAME; case 0: return DATASOURCEID_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public DataSourceIdCase getDataSourceIdCase() { return DataSourceIdCase.forNumber(dataSourceIdCase_); } public static final int SELF_FIELD_NUMBER = 1; /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return Whether the self field is set. */ @java.lang.Override public boolean hasSelf() { return dataSourceIdCase_ == 1; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return The self. */ @java.lang.Override public boolean getSelf() { if (dataSourceIdCase_ == 1) { return (java.lang.Boolean) dataSourceId_; } return false; } public static final int PRIMARY_DATA_SOURCE_NAME_FIELD_NUMBER = 3; /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the primaryDataSourceName field is set. */ public boolean hasPrimaryDataSourceName() { return dataSourceIdCase_ == 3; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The primaryDataSourceName. */ public java.lang.String getPrimaryDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 3) { dataSourceId_ = s; } return s; } } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for primaryDataSourceName. */ public com.google.protobuf.ByteString getPrimaryDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 3) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SUPPLEMENTAL_DATA_SOURCE_NAME_FIELD_NUMBER = 2; /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the supplementalDataSourceName field is set. */ public boolean hasSupplementalDataSourceName() { return dataSourceIdCase_ == 2; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The supplementalDataSourceName. */ public java.lang.String getSupplementalDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 2) { dataSourceId_ = s; } return s; } } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The bytes for supplementalDataSourceName. */ public com.google.protobuf.ByteString getSupplementalDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 2) { dataSourceId_ = 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 (dataSourceIdCase_ == 1) { output.writeBool(1, (boolean) ((java.lang.Boolean) dataSourceId_)); } if (dataSourceIdCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, dataSourceId_); } if (dataSourceIdCase_ == 3) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, dataSourceId_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (dataSourceIdCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeBoolSize( 1, (boolean) ((java.lang.Boolean) dataSourceId_)); } if (dataSourceIdCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, dataSourceId_); } if (dataSourceIdCase_ == 3) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, dataSourceId_); } 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.datasources.v1.DataSourceReference)) { return super.equals(obj); } com.google.shopping.merchant.datasources.v1.DataSourceReference other = (com.google.shopping.merchant.datasources.v1.DataSourceReference) obj; if (!getDataSourceIdCase().equals(other.getDataSourceIdCase())) return false; switch (dataSourceIdCase_) { case 1: if (getSelf() != other.getSelf()) return false; break; case 3: if (!getPrimaryDataSourceName().equals(other.getPrimaryDataSourceName())) return false; break; case 2: if (!getSupplementalDataSourceName().equals(other.getSupplementalDataSourceName())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); switch (dataSourceIdCase_) { case 1: hash = (37 * hash) + SELF_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSelf()); break; case 3: hash = (37 * hash) + PRIMARY_DATA_SOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getPrimaryDataSourceName().hashCode(); break; case 2: hash = (37 * hash) + SUPPLEMENTAL_DATA_SOURCE_NAME_FIELD_NUMBER; hash = (53 * hash) + getSupplementalDataSourceName().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.shopping.merchant.datasources.v1.DataSourceReference parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference 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.datasources.v1.DataSourceReference parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference 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.datasources.v1.DataSourceReference parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference 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.datasources.v1.DataSourceReference parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference 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.datasources.v1.DataSourceReference parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference 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.datasources.v1.DataSourceReference 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> * Data source reference can be used to manage related data sources within the * data source service. * </pre> * * Protobuf type {@code google.shopping.merchant.datasources.v1.DataSourceReference} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.shopping.merchant.datasources.v1.DataSourceReference) com.google.shopping.merchant.datasources.v1.DataSourceReferenceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.shopping.merchant.datasources.v1.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1_DataSourceReference_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.shopping.merchant.datasources.v1.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1_DataSourceReference_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.shopping.merchant.datasources.v1.DataSourceReference.class, com.google.shopping.merchant.datasources.v1.DataSourceReference.Builder.class); } // Construct using com.google.shopping.merchant.datasources.v1.DataSourceReference.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; dataSourceIdCase_ = 0; dataSourceId_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.shopping.merchant.datasources.v1.DatasourcetypesProto .internal_static_google_shopping_merchant_datasources_v1_DataSourceReference_descriptor; } @java.lang.Override public com.google.shopping.merchant.datasources.v1.DataSourceReference getDefaultInstanceForType() { return com.google.shopping.merchant.datasources.v1.DataSourceReference.getDefaultInstance(); } @java.lang.Override public com.google.shopping.merchant.datasources.v1.DataSourceReference build() { com.google.shopping.merchant.datasources.v1.DataSourceReference result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.shopping.merchant.datasources.v1.DataSourceReference buildPartial() { com.google.shopping.merchant.datasources.v1.DataSourceReference result = new com.google.shopping.merchant.datasources.v1.DataSourceReference(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0( com.google.shopping.merchant.datasources.v1.DataSourceReference result) { int from_bitField0_ = bitField0_; } private void buildPartialOneofs( com.google.shopping.merchant.datasources.v1.DataSourceReference result) { result.dataSourceIdCase_ = dataSourceIdCase_; result.dataSourceId_ = this.dataSourceId_; } @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.datasources.v1.DataSourceReference) { return mergeFrom((com.google.shopping.merchant.datasources.v1.DataSourceReference) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.shopping.merchant.datasources.v1.DataSourceReference other) { if (other == com.google.shopping.merchant.datasources.v1.DataSourceReference.getDefaultInstance()) return this; switch (other.getDataSourceIdCase()) { case SELF: { setSelf(other.getSelf()); break; } case PRIMARY_DATA_SOURCE_NAME: { dataSourceIdCase_ = 3; dataSourceId_ = other.dataSourceId_; onChanged(); break; } case SUPPLEMENTAL_DATA_SOURCE_NAME: { dataSourceIdCase_ = 2; dataSourceId_ = other.dataSourceId_; onChanged(); break; } case DATASOURCEID_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { dataSourceId_ = input.readBool(); dataSourceIdCase_ = 1; break; } // case 8 case 18: { java.lang.String s = input.readStringRequireUtf8(); dataSourceIdCase_ = 2; dataSourceId_ = s; break; } // case 18 case 26: { java.lang.String s = input.readStringRequireUtf8(); dataSourceIdCase_ = 3; dataSourceId_ = 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 dataSourceIdCase_ = 0; private java.lang.Object dataSourceId_; public DataSourceIdCase getDataSourceIdCase() { return DataSourceIdCase.forNumber(dataSourceIdCase_); } public Builder clearDataSourceId() { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); return this; } private int bitField0_; /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return Whether the self field is set. */ public boolean hasSelf() { return dataSourceIdCase_ == 1; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return The self. */ public boolean getSelf() { if (dataSourceIdCase_ == 1) { return (java.lang.Boolean) dataSourceId_; } return false; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @param value The self to set. * @return This builder for chaining. */ public Builder setSelf(boolean value) { dataSourceIdCase_ = 1; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Self should be used to reference the primary data source itself. * </pre> * * <code>bool self = 1;</code> * * @return This builder for chaining. */ public Builder clearSelf() { if (dataSourceIdCase_ == 1) { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); } return this; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return Whether the primaryDataSourceName field is set. */ @java.lang.Override public boolean hasPrimaryDataSourceName() { return dataSourceIdCase_ == 3; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The primaryDataSourceName. */ @java.lang.Override public java.lang.String getPrimaryDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 3) { dataSourceId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for primaryDataSourceName. */ @java.lang.Override public com.google.protobuf.ByteString getPrimaryDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 3) { ref = dataSourceId_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 3) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The primaryDataSourceName to set. * @return This builder for chaining. */ public Builder setPrimaryDataSourceName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } dataSourceIdCase_ = 3; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearPrimaryDataSourceName() { if (dataSourceIdCase_ == 3) { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); } return this; } /** * * * <pre> * Optional. The name of the primary data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string primary_data_source_name = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for primaryDataSourceName to set. * @return This builder for chaining. */ public Builder setPrimaryDataSourceNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); dataSourceIdCase_ = 3; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the supplementalDataSourceName field is set. */ @java.lang.Override public boolean hasSupplementalDataSourceName() { return dataSourceIdCase_ == 2; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The supplementalDataSourceName. */ @java.lang.Override public java.lang.String getSupplementalDataSourceName() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (dataSourceIdCase_ == 2) { dataSourceId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The bytes for supplementalDataSourceName. */ @java.lang.Override public com.google.protobuf.ByteString getSupplementalDataSourceNameBytes() { java.lang.Object ref = ""; if (dataSourceIdCase_ == 2) { ref = dataSourceId_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (dataSourceIdCase_ == 2) { dataSourceId_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The supplementalDataSourceName to set. * @return This builder for chaining. */ public Builder setSupplementalDataSourceName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } dataSourceIdCase_ = 2; dataSourceId_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearSupplementalDataSourceName() { if (dataSourceIdCase_ == 2) { dataSourceIdCase_ = 0; dataSourceId_ = null; onChanged(); } return this; } /** * * * <pre> * Optional. The name of the supplemental data source. * Format: * `accounts/{account}/dataSources/{datasource}` * </pre> * * <code>string supplemental_data_source_name = 2 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The bytes for supplementalDataSourceName to set. * @return This builder for chaining. */ public Builder setSupplementalDataSourceNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); dataSourceIdCase_ = 2; dataSourceId_ = 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.shopping.merchant.datasources.v1.DataSourceReference) } // @@protoc_insertion_point(class_scope:google.shopping.merchant.datasources.v1.DataSourceReference) private static final com.google.shopping.merchant.datasources.v1.DataSourceReference DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.shopping.merchant.datasources.v1.DataSourceReference(); } public static com.google.shopping.merchant.datasources.v1.DataSourceReference getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DataSourceReference> PARSER = new com.google.protobuf.AbstractParser<DataSourceReference>() { @java.lang.Override public DataSourceReference 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<DataSourceReference> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DataSourceReference> getParserForType() { return PARSER; } @java.lang.Override public com.google.shopping.merchant.datasources.v1.DataSourceReference getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,800
java-discoveryengine/google-cloud-discoveryengine/src/main/java/com/google/cloud/discoveryengine/v1/CompletionServiceClient.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.discoveryengine.v1; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.httpjson.longrunning.OperationsClient; import com.google.api.gax.longrunning.OperationFuture; import com.google.api.gax.rpc.OperationCallable; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.discoveryengine.v1.stub.CompletionServiceStub; import com.google.cloud.discoveryengine.v1.stub.CompletionServiceStubSettings; import com.google.longrunning.Operation; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service for Auto-Completion. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * CompleteQueryRequest request = * CompleteQueryRequest.newBuilder() * .setDataStore( * DataStoreName.ofProjectLocationDataStoreName( * "[PROJECT]", "[LOCATION]", "[DATA_STORE]") * .toString()) * .setQuery("query107944136") * .setQueryModel("queryModel-184930495") * .setUserPseudoId("userPseudoId-1155274652") * .setIncludeTailSuggestions(true) * .build(); * CompleteQueryResponse response = completionServiceClient.completeQuery(request); * } * }</pre> * * <p>Note: close() needs to be called on the CompletionServiceClient 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> CompleteQuery</td> * <td><p> Completes the specified user input with keyword suggestions.</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> completeQuery(CompleteQueryRequest 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> completeQueryCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ImportSuggestionDenyListEntries</td> * <td><p> Imports all [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] for a DataStore.</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> importSuggestionDenyListEntriesAsync(ImportSuggestionDenyListEntriesRequest 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> importSuggestionDenyListEntriesOperationCallable() * <li><p> importSuggestionDenyListEntriesCallable() * </ul> * </td> * </tr> * <tr> * <td><p> PurgeSuggestionDenyListEntries</td> * <td><p> Permanently deletes all [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] for a DataStore.</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> purgeSuggestionDenyListEntriesAsync(PurgeSuggestionDenyListEntriesRequest 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> purgeSuggestionDenyListEntriesOperationCallable() * <li><p> purgeSuggestionDenyListEntriesCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ImportCompletionSuggestions</td> * <td><p> Imports [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a DataStore.</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> importCompletionSuggestionsAsync(ImportCompletionSuggestionsRequest 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> importCompletionSuggestionsOperationCallable() * <li><p> importCompletionSuggestionsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> PurgeCompletionSuggestions</td> * <td><p> Permanently deletes all [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a DataStore.</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> purgeCompletionSuggestionsAsync(PurgeCompletionSuggestionsRequest 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> purgeCompletionSuggestionsOperationCallable() * <li><p> purgeCompletionSuggestionsCallable() * </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 CompletionServiceSettings 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 * CompletionServiceSettings completionServiceSettings = * CompletionServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * CompletionServiceClient completionServiceClient = * CompletionServiceClient.create(completionServiceSettings); * }</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 * CompletionServiceSettings completionServiceSettings = * CompletionServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * CompletionServiceClient completionServiceClient = * CompletionServiceClient.create(completionServiceSettings); * }</pre> * * <p>To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over * the wire: * * <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 * CompletionServiceSettings completionServiceSettings = * CompletionServiceSettings.newHttpJsonBuilder().build(); * CompletionServiceClient completionServiceClient = * CompletionServiceClient.create(completionServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class CompletionServiceClient implements BackgroundResource { private final CompletionServiceSettings settings; private final CompletionServiceStub stub; private final OperationsClient httpJsonOperationsClient; private final com.google.longrunning.OperationsClient operationsClient; /** Constructs an instance of CompletionServiceClient with default settings. */ public static final CompletionServiceClient create() throws IOException { return create(CompletionServiceSettings.newBuilder().build()); } /** * Constructs an instance of CompletionServiceClient, 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 CompletionServiceClient create(CompletionServiceSettings settings) throws IOException { return new CompletionServiceClient(settings); } /** * Constructs an instance of CompletionServiceClient, using the given stub for making calls. This * is for advanced usage - prefer using create(CompletionServiceSettings). */ public static final CompletionServiceClient create(CompletionServiceStub stub) { return new CompletionServiceClient(stub); } /** * Constructs an instance of CompletionServiceClient, 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 CompletionServiceClient(CompletionServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((CompletionServiceStubSettings) settings.getStubSettings()).createStub(); this.operationsClient = com.google.longrunning.OperationsClient.create(this.stub.getOperationsStub()); this.httpJsonOperationsClient = OperationsClient.create(this.stub.getHttpJsonOperationsStub()); } protected CompletionServiceClient(CompletionServiceStub stub) { this.settings = null; this.stub = stub; this.operationsClient = com.google.longrunning.OperationsClient.create(this.stub.getOperationsStub()); this.httpJsonOperationsClient = OperationsClient.create(this.stub.getHttpJsonOperationsStub()); } public final CompletionServiceSettings getSettings() { return settings; } public CompletionServiceStub getStub() { return stub; } /** * Returns the OperationsClient that can be used to query the status of a long-running operation * returned by another API method call. */ public final com.google.longrunning.OperationsClient getOperationsClient() { return operationsClient; } /** * Returns the OperationsClient that can be used to query the status of a long-running operation * returned by another API method call. */ @BetaApi public final OperationsClient getHttpJsonOperationsClient() { return httpJsonOperationsClient; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Completes the specified user input with keyword suggestions. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * CompleteQueryRequest request = * CompleteQueryRequest.newBuilder() * .setDataStore( * DataStoreName.ofProjectLocationDataStoreName( * "[PROJECT]", "[LOCATION]", "[DATA_STORE]") * .toString()) * .setQuery("query107944136") * .setQueryModel("queryModel-184930495") * .setUserPseudoId("userPseudoId-1155274652") * .setIncludeTailSuggestions(true) * .build(); * CompleteQueryResponse response = completionServiceClient.completeQuery(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 CompleteQueryResponse completeQuery(CompleteQueryRequest request) { return completeQueryCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Completes the specified user input with keyword suggestions. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * CompleteQueryRequest request = * CompleteQueryRequest.newBuilder() * .setDataStore( * DataStoreName.ofProjectLocationDataStoreName( * "[PROJECT]", "[LOCATION]", "[DATA_STORE]") * .toString()) * .setQuery("query107944136") * .setQueryModel("queryModel-184930495") * .setUserPseudoId("userPseudoId-1155274652") * .setIncludeTailSuggestions(true) * .build(); * ApiFuture<CompleteQueryResponse> future = * completionServiceClient.completeQueryCallable().futureCall(request); * // Do something. * CompleteQueryResponse response = future.get(); * } * }</pre> */ public final UnaryCallable<CompleteQueryRequest, CompleteQueryResponse> completeQueryCallable() { return stub.completeQueryCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports all [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] * for a DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * ImportSuggestionDenyListEntriesRequest request = * ImportSuggestionDenyListEntriesRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * ImportSuggestionDenyListEntriesResponse response = * completionServiceClient.importSuggestionDenyListEntriesAsync(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< ImportSuggestionDenyListEntriesResponse, ImportSuggestionDenyListEntriesMetadata> importSuggestionDenyListEntriesAsync(ImportSuggestionDenyListEntriesRequest request) { return importSuggestionDenyListEntriesOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports all [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] * for a DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * ImportSuggestionDenyListEntriesRequest request = * ImportSuggestionDenyListEntriesRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * OperationFuture< * ImportSuggestionDenyListEntriesResponse, ImportSuggestionDenyListEntriesMetadata> * future = * completionServiceClient * .importSuggestionDenyListEntriesOperationCallable() * .futureCall(request); * // Do something. * ImportSuggestionDenyListEntriesResponse response = future.get(); * } * }</pre> */ public final OperationCallable< ImportSuggestionDenyListEntriesRequest, ImportSuggestionDenyListEntriesResponse, ImportSuggestionDenyListEntriesMetadata> importSuggestionDenyListEntriesOperationCallable() { return stub.importSuggestionDenyListEntriesOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports all [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] * for a DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * ImportSuggestionDenyListEntriesRequest request = * ImportSuggestionDenyListEntriesRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * ApiFuture<Operation> future = * completionServiceClient.importSuggestionDenyListEntriesCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<ImportSuggestionDenyListEntriesRequest, Operation> importSuggestionDenyListEntriesCallable() { return stub.importSuggestionDenyListEntriesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Permanently deletes all * [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] for a * DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * PurgeSuggestionDenyListEntriesRequest request = * PurgeSuggestionDenyListEntriesRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * PurgeSuggestionDenyListEntriesResponse response = * completionServiceClient.purgeSuggestionDenyListEntriesAsync(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< PurgeSuggestionDenyListEntriesResponse, PurgeSuggestionDenyListEntriesMetadata> purgeSuggestionDenyListEntriesAsync(PurgeSuggestionDenyListEntriesRequest request) { return purgeSuggestionDenyListEntriesOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Permanently deletes all * [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] for a * DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * PurgeSuggestionDenyListEntriesRequest request = * PurgeSuggestionDenyListEntriesRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * OperationFuture< * PurgeSuggestionDenyListEntriesResponse, PurgeSuggestionDenyListEntriesMetadata> * future = * completionServiceClient * .purgeSuggestionDenyListEntriesOperationCallable() * .futureCall(request); * // Do something. * PurgeSuggestionDenyListEntriesResponse response = future.get(); * } * }</pre> */ public final OperationCallable< PurgeSuggestionDenyListEntriesRequest, PurgeSuggestionDenyListEntriesResponse, PurgeSuggestionDenyListEntriesMetadata> purgeSuggestionDenyListEntriesOperationCallable() { return stub.purgeSuggestionDenyListEntriesOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Permanently deletes all * [SuggestionDenyListEntry][google.cloud.discoveryengine.v1.SuggestionDenyListEntry] for a * DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * PurgeSuggestionDenyListEntriesRequest request = * PurgeSuggestionDenyListEntriesRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * ApiFuture<Operation> future = * completionServiceClient.purgeSuggestionDenyListEntriesCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<PurgeSuggestionDenyListEntriesRequest, Operation> purgeSuggestionDenyListEntriesCallable() { return stub.purgeSuggestionDenyListEntriesCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a * DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * ImportCompletionSuggestionsRequest request = * ImportCompletionSuggestionsRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .setErrorConfig(ImportErrorConfig.newBuilder().build()) * .build(); * ImportCompletionSuggestionsResponse response = * completionServiceClient.importCompletionSuggestionsAsync(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< ImportCompletionSuggestionsResponse, ImportCompletionSuggestionsMetadata> importCompletionSuggestionsAsync(ImportCompletionSuggestionsRequest request) { return importCompletionSuggestionsOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a * DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * ImportCompletionSuggestionsRequest request = * ImportCompletionSuggestionsRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .setErrorConfig(ImportErrorConfig.newBuilder().build()) * .build(); * OperationFuture<ImportCompletionSuggestionsResponse, ImportCompletionSuggestionsMetadata> * future = * completionServiceClient * .importCompletionSuggestionsOperationCallable() * .futureCall(request); * // Do something. * ImportCompletionSuggestionsResponse response = future.get(); * } * }</pre> */ public final OperationCallable< ImportCompletionSuggestionsRequest, ImportCompletionSuggestionsResponse, ImportCompletionSuggestionsMetadata> importCompletionSuggestionsOperationCallable() { return stub.importCompletionSuggestionsOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Imports [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a * DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * ImportCompletionSuggestionsRequest request = * ImportCompletionSuggestionsRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .setErrorConfig(ImportErrorConfig.newBuilder().build()) * .build(); * ApiFuture<Operation> future = * completionServiceClient.importCompletionSuggestionsCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<ImportCompletionSuggestionsRequest, Operation> importCompletionSuggestionsCallable() { return stub.importCompletionSuggestionsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Permanently deletes all * [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * PurgeCompletionSuggestionsRequest request = * PurgeCompletionSuggestionsRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * PurgeCompletionSuggestionsResponse response = * completionServiceClient.purgeCompletionSuggestionsAsync(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< PurgeCompletionSuggestionsResponse, PurgeCompletionSuggestionsMetadata> purgeCompletionSuggestionsAsync(PurgeCompletionSuggestionsRequest request) { return purgeCompletionSuggestionsOperationCallable().futureCall(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Permanently deletes all * [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * PurgeCompletionSuggestionsRequest request = * PurgeCompletionSuggestionsRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * OperationFuture<PurgeCompletionSuggestionsResponse, PurgeCompletionSuggestionsMetadata> * future = * completionServiceClient * .purgeCompletionSuggestionsOperationCallable() * .futureCall(request); * // Do something. * PurgeCompletionSuggestionsResponse response = future.get(); * } * }</pre> */ public final OperationCallable< PurgeCompletionSuggestionsRequest, PurgeCompletionSuggestionsResponse, PurgeCompletionSuggestionsMetadata> purgeCompletionSuggestionsOperationCallable() { return stub.purgeCompletionSuggestionsOperationCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Permanently deletes all * [CompletionSuggestion][google.cloud.discoveryengine.v1.CompletionSuggestion]s for a DataStore. * * <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 (CompletionServiceClient completionServiceClient = CompletionServiceClient.create()) { * PurgeCompletionSuggestionsRequest request = * PurgeCompletionSuggestionsRequest.newBuilder() * .setParent( * DataStoreName.ofProjectLocationCollectionDataStoreName( * "[PROJECT]", "[LOCATION]", "[COLLECTION]", "[DATA_STORE]") * .toString()) * .build(); * ApiFuture<Operation> future = * completionServiceClient.purgeCompletionSuggestionsCallable().futureCall(request); * // Do something. * Operation response = future.get(); * } * }</pre> */ public final UnaryCallable<PurgeCompletionSuggestionsRequest, Operation> purgeCompletionSuggestionsCallable() { return stub.purgeCompletionSuggestionsCallable(); } @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); } }
googleapis/google-cloud-java
36,587
java-dataplex/proto-google-cloud-dataplex-v1/src/main/java/com/google/cloud/dataplex/v1/ListEnvironmentsResponse.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/dataplex/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dataplex.v1; /** * * * <pre> * List environments response. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.ListEnvironmentsResponse} */ public final class ListEnvironmentsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dataplex.v1.ListEnvironmentsResponse) ListEnvironmentsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListEnvironmentsResponse.newBuilder() to construct. private ListEnvironmentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEnvironmentsResponse() { environments_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEnvironmentsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.ServiceProto .internal_static_google_cloud_dataplex_v1_ListEnvironmentsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.ServiceProto .internal_static_google_cloud_dataplex_v1_ListEnvironmentsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.ListEnvironmentsResponse.class, com.google.cloud.dataplex.v1.ListEnvironmentsResponse.Builder.class); } public static final int ENVIRONMENTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dataplex.v1.Environment> environments_; /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dataplex.v1.Environment> getEnvironmentsList() { return environments_; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dataplex.v1.EnvironmentOrBuilder> getEnvironmentsOrBuilderList() { return environments_; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ @java.lang.Override public int getEnvironmentsCount() { return environments_.size(); } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ @java.lang.Override public com.google.cloud.dataplex.v1.Environment getEnvironments(int index) { return environments_.get(index); } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ @java.lang.Override public com.google.cloud.dataplex.v1.EnvironmentOrBuilder getEnvironmentsOrBuilder(int index) { return environments_.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 < environments_.size(); i++) { output.writeMessage(1, environments_.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 < environments_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, environments_.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.dataplex.v1.ListEnvironmentsResponse)) { return super.equals(obj); } com.google.cloud.dataplex.v1.ListEnvironmentsResponse other = (com.google.cloud.dataplex.v1.ListEnvironmentsResponse) obj; if (!getEnvironmentsList().equals(other.getEnvironmentsList())) 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 (getEnvironmentsCount() > 0) { hash = (37 * hash) + ENVIRONMENTS_FIELD_NUMBER; hash = (53 * hash) + getEnvironmentsList().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.dataplex.v1.ListEnvironmentsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse 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.dataplex.v1.ListEnvironmentsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse 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.dataplex.v1.ListEnvironmentsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse 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.dataplex.v1.ListEnvironmentsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse 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.dataplex.v1.ListEnvironmentsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse 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.dataplex.v1.ListEnvironmentsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * List environments response. * </pre> * * Protobuf type {@code google.cloud.dataplex.v1.ListEnvironmentsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dataplex.v1.ListEnvironmentsResponse) com.google.cloud.dataplex.v1.ListEnvironmentsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dataplex.v1.ServiceProto .internal_static_google_cloud_dataplex_v1_ListEnvironmentsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dataplex.v1.ServiceProto .internal_static_google_cloud_dataplex_v1_ListEnvironmentsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dataplex.v1.ListEnvironmentsResponse.class, com.google.cloud.dataplex.v1.ListEnvironmentsResponse.Builder.class); } // Construct using com.google.cloud.dataplex.v1.ListEnvironmentsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (environmentsBuilder_ == null) { environments_ = java.util.Collections.emptyList(); } else { environments_ = null; environmentsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dataplex.v1.ServiceProto .internal_static_google_cloud_dataplex_v1_ListEnvironmentsResponse_descriptor; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEnvironmentsResponse getDefaultInstanceForType() { return com.google.cloud.dataplex.v1.ListEnvironmentsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dataplex.v1.ListEnvironmentsResponse build() { com.google.cloud.dataplex.v1.ListEnvironmentsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEnvironmentsResponse buildPartial() { com.google.cloud.dataplex.v1.ListEnvironmentsResponse result = new com.google.cloud.dataplex.v1.ListEnvironmentsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dataplex.v1.ListEnvironmentsResponse result) { if (environmentsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { environments_ = java.util.Collections.unmodifiableList(environments_); bitField0_ = (bitField0_ & ~0x00000001); } result.environments_ = environments_; } else { result.environments_ = environmentsBuilder_.build(); } } private void buildPartial0(com.google.cloud.dataplex.v1.ListEnvironmentsResponse 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.dataplex.v1.ListEnvironmentsResponse) { return mergeFrom((com.google.cloud.dataplex.v1.ListEnvironmentsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dataplex.v1.ListEnvironmentsResponse other) { if (other == com.google.cloud.dataplex.v1.ListEnvironmentsResponse.getDefaultInstance()) return this; if (environmentsBuilder_ == null) { if (!other.environments_.isEmpty()) { if (environments_.isEmpty()) { environments_ = other.environments_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEnvironmentsIsMutable(); environments_.addAll(other.environments_); } onChanged(); } } else { if (!other.environments_.isEmpty()) { if (environmentsBuilder_.isEmpty()) { environmentsBuilder_.dispose(); environmentsBuilder_ = null; environments_ = other.environments_; bitField0_ = (bitField0_ & ~0x00000001); environmentsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEnvironmentsFieldBuilder() : null; } else { environmentsBuilder_.addAllMessages(other.environments_); } } } 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.dataplex.v1.Environment m = input.readMessage( com.google.cloud.dataplex.v1.Environment.parser(), extensionRegistry); if (environmentsBuilder_ == null) { ensureEnvironmentsIsMutable(); environments_.add(m); } else { environmentsBuilder_.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.dataplex.v1.Environment> environments_ = java.util.Collections.emptyList(); private void ensureEnvironmentsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { environments_ = new java.util.ArrayList<com.google.cloud.dataplex.v1.Environment>(environments_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Environment, com.google.cloud.dataplex.v1.Environment.Builder, com.google.cloud.dataplex.v1.EnvironmentOrBuilder> environmentsBuilder_; /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public java.util.List<com.google.cloud.dataplex.v1.Environment> getEnvironmentsList() { if (environmentsBuilder_ == null) { return java.util.Collections.unmodifiableList(environments_); } else { return environmentsBuilder_.getMessageList(); } } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public int getEnvironmentsCount() { if (environmentsBuilder_ == null) { return environments_.size(); } else { return environmentsBuilder_.getCount(); } } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public com.google.cloud.dataplex.v1.Environment getEnvironments(int index) { if (environmentsBuilder_ == null) { return environments_.get(index); } else { return environmentsBuilder_.getMessage(index); } } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder setEnvironments(int index, com.google.cloud.dataplex.v1.Environment value) { if (environmentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEnvironmentsIsMutable(); environments_.set(index, value); onChanged(); } else { environmentsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder setEnvironments( int index, com.google.cloud.dataplex.v1.Environment.Builder builderForValue) { if (environmentsBuilder_ == null) { ensureEnvironmentsIsMutable(); environments_.set(index, builderForValue.build()); onChanged(); } else { environmentsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder addEnvironments(com.google.cloud.dataplex.v1.Environment value) { if (environmentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEnvironmentsIsMutable(); environments_.add(value); onChanged(); } else { environmentsBuilder_.addMessage(value); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder addEnvironments(int index, com.google.cloud.dataplex.v1.Environment value) { if (environmentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEnvironmentsIsMutable(); environments_.add(index, value); onChanged(); } else { environmentsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder addEnvironments( com.google.cloud.dataplex.v1.Environment.Builder builderForValue) { if (environmentsBuilder_ == null) { ensureEnvironmentsIsMutable(); environments_.add(builderForValue.build()); onChanged(); } else { environmentsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder addEnvironments( int index, com.google.cloud.dataplex.v1.Environment.Builder builderForValue) { if (environmentsBuilder_ == null) { ensureEnvironmentsIsMutable(); environments_.add(index, builderForValue.build()); onChanged(); } else { environmentsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder addAllEnvironments( java.lang.Iterable<? extends com.google.cloud.dataplex.v1.Environment> values) { if (environmentsBuilder_ == null) { ensureEnvironmentsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, environments_); onChanged(); } else { environmentsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder clearEnvironments() { if (environmentsBuilder_ == null) { environments_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { environmentsBuilder_.clear(); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public Builder removeEnvironments(int index) { if (environmentsBuilder_ == null) { ensureEnvironmentsIsMutable(); environments_.remove(index); onChanged(); } else { environmentsBuilder_.remove(index); } return this; } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public com.google.cloud.dataplex.v1.Environment.Builder getEnvironmentsBuilder(int index) { return getEnvironmentsFieldBuilder().getBuilder(index); } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public com.google.cloud.dataplex.v1.EnvironmentOrBuilder getEnvironmentsOrBuilder(int index) { if (environmentsBuilder_ == null) { return environments_.get(index); } else { return environmentsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public java.util.List<? extends com.google.cloud.dataplex.v1.EnvironmentOrBuilder> getEnvironmentsOrBuilderList() { if (environmentsBuilder_ != null) { return environmentsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(environments_); } } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public com.google.cloud.dataplex.v1.Environment.Builder addEnvironmentsBuilder() { return getEnvironmentsFieldBuilder() .addBuilder(com.google.cloud.dataplex.v1.Environment.getDefaultInstance()); } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public com.google.cloud.dataplex.v1.Environment.Builder addEnvironmentsBuilder(int index) { return getEnvironmentsFieldBuilder() .addBuilder(index, com.google.cloud.dataplex.v1.Environment.getDefaultInstance()); } /** * * * <pre> * Environments under the given parent lake. * </pre> * * <code>repeated .google.cloud.dataplex.v1.Environment environments = 1;</code> */ public java.util.List<com.google.cloud.dataplex.v1.Environment.Builder> getEnvironmentsBuilderList() { return getEnvironmentsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Environment, com.google.cloud.dataplex.v1.Environment.Builder, com.google.cloud.dataplex.v1.EnvironmentOrBuilder> getEnvironmentsFieldBuilder() { if (environmentsBuilder_ == null) { environmentsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dataplex.v1.Environment, com.google.cloud.dataplex.v1.Environment.Builder, com.google.cloud.dataplex.v1.EnvironmentOrBuilder>( environments_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); environments_ = null; } return environmentsBuilder_; } 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.dataplex.v1.ListEnvironmentsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dataplex.v1.ListEnvironmentsResponse) private static final com.google.cloud.dataplex.v1.ListEnvironmentsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dataplex.v1.ListEnvironmentsResponse(); } public static com.google.cloud.dataplex.v1.ListEnvironmentsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEnvironmentsResponse> PARSER = new com.google.protobuf.AbstractParser<ListEnvironmentsResponse>() { @java.lang.Override public ListEnvironmentsResponse 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<ListEnvironmentsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEnvironmentsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dataplex.v1.ListEnvironmentsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
oracle/graal
36,520
truffle/src/com.oracle.truffle.api.test/src/com/oracle/truffle/api/test/host/TestMemberAccess.java
/* * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.api.test.host; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; import com.oracle.truffle.api.interop.InteropException; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.InvalidArrayIndexException; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.interop.UnknownIdentifierException; import com.oracle.truffle.api.interop.UnsupportedMessageException; import com.oracle.truffle.api.interop.UnsupportedTypeException; import com.oracle.truffle.api.test.host.AsCollectionsTest.ListBasedTO; import com.oracle.truffle.tck.tests.TruffleTestAssumptions; public class TestMemberAccess extends ProxyLanguageEnvTest { private static final InteropLibrary INTEROP = InteropLibrary.getFactory().getUncached(); @BeforeClass public static void runWithWeakEncapsulationOnly() { TruffleTestAssumptions.assumeWeakEncapsulation(); } @Test public void testFields() throws IllegalAccessException, InteropException { TestClass t = new TestClass(); Field[] fields = t.getClass().getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); String name = f.getName(); if (name.startsWith("field")) { boolean isPublic = (f.getModifiers() & Modifier.PUBLIC) != 0; boolean wasUIE = false; try { testForValue(name, f.get(t)); } catch (UnknownIdentifierException e) { if (isPublic) { throw e; } wasUIE = true; } if (!isPublic && !wasUIE) { fail("expected UnknownIdentifierException when accessing field: " + name); } } } } @Test public void testMethods() throws InvocationTargetException, IllegalAccessException, InteropException { TestClass t = new TestClass(); Method[] methods = t.getClass().getDeclaredMethods(); for (Method m : methods) { if (m.getParameterCount() == 0) { m.setAccessible(true); String name = m.getName(); if (name.startsWith("method")) { boolean isPublic = (m.getModifiers() & Modifier.PUBLIC) != 0; boolean wasUIE = false; try { testForValue(name, m.invoke(t)); } catch (UnknownIdentifierException e) { if (isPublic) { throw e; } wasUIE = true; } if (!isPublic && !wasUIE) { fail("expected UnknownIdentifierException when accessing method: " + name); } } } } } @Test public void testAllTypes() throws InteropException { getValueForAllTypesMethod("allTypesMethod"); getValueForAllTypesMethod("allTypesStaticMethod"); } @Test public void testNullParameterJNISig() throws InteropException { Object bo = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Boolean_2", asTruffleObject(null)); assertEquals("Boolean parameter method executed", Boolean.class.getName(), bo); Object by = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Byte_2", asTruffleObject(null)); assertEquals("Byte parameter method executed", Byte.class.getName(), by); Object c = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Character_2", asTruffleObject(null)); assertEquals("Character parameter method executed", Character.class.getName(), c); Object f = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Float_2", asTruffleObject(null)); assertEquals("Float parameter method executed", Float.class.getName(), f); Object d = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Double_2", asTruffleObject(null)); assertEquals("Double parameter method executed", Double.class.getName(), d); Object i = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Integer_2", asTruffleObject(null)); assertEquals("Integer parameter method executed", Integer.class.getName(), i); Object l = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Long_2", asTruffleObject(null)); assertEquals("Long parameter method executed", Long.class.getName(), l); Object s = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_Short_2", asTruffleObject(null)); assertEquals("Short parameter method executed", Short.class.getName(), s); Object st = getValueFromMember("isNull__Ljava_lang_String_2Ljava_lang_String_2", asTruffleObject(null)); assertEquals("String parameter method executed", String.class.getName(), st); } @Test public void testNullParameterSig() throws InteropException { Object bo = getValueFromMember("isNull(java.lang.Boolean)", asTruffleObject(null)); assertEquals("Boolean parameter method executed", Boolean.class.getName(), bo); Object by = getValueFromMember("isNull(java.lang.Byte)", asTruffleObject(null)); assertEquals("Byte parameter method executed", Byte.class.getName(), by); Object c = getValueFromMember("isNull(java.lang.Character)", asTruffleObject(null)); assertEquals("Character parameter method executed", Character.class.getName(), c); Object f = getValueFromMember("isNull(java.lang.Float)", asTruffleObject(null)); assertEquals("Float parameter method executed", Float.class.getName(), f); Object d = getValueFromMember("isNull(java.lang.Double)", asTruffleObject(null)); assertEquals("Double parameter method executed", Double.class.getName(), d); Object i = getValueFromMember("isNull(java.lang.Integer)", asTruffleObject(null)); assertEquals("Integer parameter method executed", Integer.class.getName(), i); Object l = getValueFromMember("isNull(java.lang.Long)", asTruffleObject(null)); assertEquals("Long parameter method executed", Long.class.getName(), l); Object s = getValueFromMember("isNull(java.lang.Short)", asTruffleObject(null)); assertEquals("Short parameter method executed", Short.class.getName(), s); Object st = getValueFromMember("isNull(java.lang.String)", asTruffleObject(null)); assertEquals("String parameter method executed", String.class.getName(), st); } @Test public void testAmbiguousSig() throws InteropException { assertEquals("ambiguous(Object,String)", getValueFromMember("ambiguous(java.lang.Object,java.lang.String)", "arg1", "arg2")); assertEquals("ambiguous(String,Object)", getValueFromMember("ambiguous(java.lang.String,java.lang.Object)", "arg1", "arg2")); try { getValueFromMember("ambiguous", "arg1", "arg2"); fail("should have thrown"); } catch (UnsupportedTypeException ex) { // expected } } @Test public void testAmbiguousSig2() throws InteropException { assertEquals("ambiguous2(int,Object[])", getValueFromMember("ambiguous2(int,java.lang.Object[])", 42, new ListBasedTO(Arrays.asList(43, 44)))); assertEquals("ambiguous2(int,int[])", getValueFromMember("ambiguous2(int,int[])", 42, new ListBasedTO(Arrays.asList(43, 44)))); try { getValueFromMember("ambiguous2", 42, new ListBasedTO(Arrays.asList(43, 44))); fail("should have thrown"); } catch (UnsupportedTypeException ex) { // expected } } @Test public void testKeysAndInternalKeys() throws Exception { TruffleObject testClass = asTruffleHostSymbol(TestClass.class); assertKeys(testClass); } @Test public void testKeysAndInternalKeysOnInstance() throws Exception { TruffleObject instance = asTruffleObject(new TestClass()); assertKeys(instance); } private void assertKeys(TruffleObject obj) throws UnsupportedMessageException { List<?> keys = asJavaObject(List.class, INTEROP.getMembers(obj)); Set<String> foundKeys = new HashSet<>(); for (Object key : keys) { assertTrue("Is string" + key, key instanceof String); String keyName = (String) key; assertEquals("No __ in " + keyName, -1, keyName.indexOf("__")); if (!INTEROP.isMemberInvocable(obj, keyName)) { continue; } foundKeys.add(keyName); } Set<String> foundInternalKeys = new HashSet<>(); List<?> internalKeys = asJavaObject(List.class, INTEROP.getMembers(obj, true)); for (Object key : internalKeys) { assertTrue("Is string" + key, key instanceof String); String keyName = (String) key; if (!keyName.contains("__")) { if (!INTEROP.isMemberInvocable(obj, keyName)) { continue; } assertTrue("Not internal: " + keyName, !INTEROP.isMemberInternal(obj, keyName) || isObjectMethodName(keyName)); boolean found = foundKeys.remove(keyName); assertTrue("Non-internal key has been listed before: " + keyName, found || isObjectMethodName(keyName)); } else { assertTrue("Internal: " + keyName, INTEROP.isMemberInternal(obj, keyName)); foundInternalKeys.add(keyName); } assertTrue("Is invocable " + keyName, INTEROP.isMemberInvocable(obj, keyName)); } assertTrue("All normal keys listed in internal mode too: " + foundKeys, foundKeys.isEmpty()); assertTrue("Unexpected internal keys: " + foundInternalKeys, foundInternalKeys.isEmpty()); } private static boolean isObjectMethodName(String name) { switch (name) { case "notify": case "notifyAll": case "wait": case "hashCode": case "equals": case "toString": case "getClass": return true; default: return false; } } @Test public void testOverloaded1() throws InteropException { assertEquals("boolean", getValueFromMember("isOverloaded", true)); } @Test public void testOverloaded2() throws InteropException { assertEquals(Boolean.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Boolean.TRUE)); } @Test public void testOverloaded3() throws InteropException { assertEquals(byte.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Byte.MAX_VALUE)); } @Test public void testOverloaded4() throws InteropException { assertEquals(Byte.class.getName(), getValueFromMember("isOverloaded", Byte.valueOf(Byte.MAX_VALUE))); } @Test public void testOverloaded5() throws InteropException { assertEquals(char.class.getName(), getValueFromMember("isOverloaded", 'a')); } @Test public void testOverloaded6() throws InteropException { assertEquals(Character.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Character.valueOf('a'))); } @Test public void testOverloaded7() throws InteropException { assertEquals(float.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Float.MAX_VALUE)); } @Test public void testOverloaded8() throws InteropException { assertEquals(Float.class.getName(), getValueFromMember("isOverloaded", Float.valueOf(Float.MAX_VALUE))); } @Test public void testOverloaded9() throws InteropException { assertEquals(double.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Double.MAX_VALUE)); } @Test public void testOverloaded10() throws InteropException { assertEquals(Double.class.getName(), getValueFromMember("isOverloaded", Double.valueOf(Double.MAX_VALUE))); } @Test public void testOverloaded11() throws InteropException { assertEquals(int.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Integer.MAX_VALUE)); } @Test public void testOverloaded12() throws InteropException { assertEquals(Integer.class.getName(), getValueFromMember("isOverloaded", Integer.MAX_VALUE)); } @Test public void testOverloaded13() throws InteropException { assertEquals(long.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Long.MAX_VALUE)); } @Test public void testOverloaded14() throws InteropException { assertEquals(Long.class.getName(), getValueFromMember("isOverloaded", Long.MAX_VALUE)); } @Test public void testOverloaded15() throws InteropException { assertEquals(short.class.getName(), getValueFromMember(TestClass2.class, "isOverloaded", Short.MAX_VALUE)); } @Test public void testOverloaded16() throws InteropException { assertEquals(Short.class.getName(), getValueFromMember("isOverloaded", Short.MAX_VALUE)); } @Test public void testOverloaded17() throws InteropException { assertEquals(String.class.getName(), getValueFromMember("isOverloaded", "testString")); } @Test public void testClassAsArg() throws InteropException { TruffleObject clazz = asTruffleHostSymbol(String.class); assertEquals(String.class.getName(), getValueFromMember("classAsArg", clazz)); } @Test public void testArray() throws InteropException { TruffleObject arrayClass = asTruffleHostSymbol(Array.class); TruffleObject newInstanceMethod = (TruffleObject) INTEROP.readMember(arrayClass, "newInstance"); int arrayLength = 2; TruffleObject stringArray = (TruffleObject) INTEROP.execute(newInstanceMethod, asTruffleHostSymbol(String.class), arrayLength); assertTrue(INTEROP.hasArrayElements(stringArray)); INTEROP.writeArrayElement(stringArray, 0, "foo"); INTEROP.writeArrayElement(stringArray, 1, "bar"); assertEquals(INTEROP.readMember(stringArray, "length"), arrayLength); TruffleObject stringArrayCopy1 = (TruffleObject) INTEROP.invokeMember(stringArray, "clone"); TruffleObject stringArrayCopy2 = (TruffleObject) INTEROP.execute(INTEROP.readMember(stringArray, "clone")); for (int i = 0; i < arrayLength; i++) { assertEquals(INTEROP.readArrayElement(stringArray, i), INTEROP.readArrayElement(stringArrayCopy1, i)); assertEquals(INTEROP.readArrayElement(stringArray, i), INTEROP.readArrayElement(stringArrayCopy2, i)); } INTEROP.writeArrayElement(stringArrayCopy1, 1, "waz"); // Mutate copy assertNotEquals(INTEROP.readArrayElement(stringArray, 1), INTEROP.readArrayElement(stringArrayCopy1, 1)); } @Test public void testArrayOutOfBoundsAccess() throws InteropException { Object[] array = new Object[1]; TruffleObject arrayObject = asTruffleObject(array); assertTrue(INTEROP.hasArrayElements(arrayObject)); INTEROP.readArrayElement(arrayObject, 0); try { INTEROP.readArrayElement(arrayObject, 1); fail(); } catch (InvalidArrayIndexException e) { } } @Test public void testObjectReadIndex() throws InteropException { TruffleObject arrayObject = asTruffleObject(new TestClass()); try { INTEROP.readArrayElement(arrayObject, 0); fail(); } catch (UnsupportedMessageException e) { } } @Test public void testOverloadedConstructor1() throws InteropException { TruffleObject testClass = asTruffleHostSymbol(TestConstructor.class); TruffleObject testObj; testObj = (TruffleObject) INTEROP.instantiate(testClass); assertEquals(void.class.getName(), INTEROP.readMember(testObj, "ctor")); testObj = (TruffleObject) INTEROP.instantiate(testClass, 42); assertEquals(int.class.getName(), INTEROP.readMember(testObj, "ctor")); testObj = (TruffleObject) INTEROP.instantiate(testClass, 4.2f); assertEquals(float.class.getName(), INTEROP.readMember(testObj, "ctor")); } @Test public void testOverloadedConstructor2() throws InteropException { TruffleObject testClass = asTruffleHostSymbol(TestConstructor.class); TruffleObject testObj; testObj = (TruffleObject) INTEROP.instantiate(testClass, (short) 42); assertEquals(int.class.getName(), INTEROP.readMember(testObj, "ctor")); testObj = (TruffleObject) INTEROP.instantiate(testClass, 4.2f); // TODO GR-38632 prioritize conversion from double to float over double to int // assertEquals(float.class.getName(), INTEROP.readMember(testObj, "ctor")); } @Test public void testOverloadedConstructor3() throws InteropException { TruffleObject clazz = asTruffleHostSymbol(TestConstructorException.class); Object testObj = INTEROP.instantiate(clazz, "test", 42); assertTrue(testObj instanceof TruffleObject && env.asHostObject(testObj) instanceof TestConstructorException); assertThrowsExceptionWithCause(() -> INTEROP.instantiate(clazz, "test"), IOException.class); } @Test public void testIterate() throws InteropException { List<Object> l = new ArrayList<>(); l.add("one"); l.add("two"); TruffleObject listObject = asTruffleObject(l); TruffleObject itFunction = (TruffleObject) INTEROP.readMember(listObject, "iterator"); TruffleObject it = (TruffleObject) INTEROP.execute(itFunction); TruffleObject hasNextFunction = (TruffleObject) INTEROP.readMember(it, "hasNext"); List<Object> returned = new ArrayList<>(); while ((boolean) INTEROP.execute(hasNextFunction)) { TruffleObject nextFunction = (TruffleObject) INTEROP.readMember(it, "next"); Object element = INTEROP.execute(nextFunction); returned.add(element); } assertEquals(l.size(), returned.size()); assertEquals(l.get(0), returned.get(0)); assertEquals(l.get(1), returned.get(1)); } @Test public void testMethodThrowsIOException() { assertThrowsExceptionWithCause(() -> getValueFromMember(TestClass2.class, "methodThrowsIOException"), IOException.class); } private void testForValue(String name, Object value) throws InteropException { Object o = getValueFromMember(name); if (value == null) { if (o == null || (o instanceof TruffleObject && INTEROP.isNull(o))) { return; } } assertEquals(value, o); } private Object getValueFromMember(String name, Object... parameters) throws InteropException { return getValueFromMember(TestClass.class, name, parameters); } private Object getValueFromMember(Class<?> javaClazz, String name, Object... parameters) throws InteropException { TruffleObject clazz = asTruffleHostSymbol(javaClazz); Object o = INTEROP.instantiate(clazz); try { o = INTEROP.readMember(o, name); } catch (UnknownIdentifierException e) { o = INTEROP.readMember(clazz, name); } if (o instanceof TruffleObject && INTEROP.isExecutable(o)) { o = INTEROP.execute((TruffleObject) o, parameters); } return o; } private void getValueForAllTypesMethod(String method) throws InteropException { boolean bo = true; byte bt = 127; char c = 'a'; short sh = 1234; int i = Integer.MAX_VALUE; long l = Long.MAX_VALUE; double d = Double.MAX_VALUE; float f = Float.MAX_VALUE; String s = "testString"; Object o = getValueFromMember(method, new Object[]{bo, bt, c, sh, i, l, d, f, s}); assertEquals("" + bo + bt + c + sh + i + l + d + f + s, o); } @SuppressWarnings("unused") public static class TestClass { public static boolean fieldStaticBoolean = true; public static byte fieldStaticByte = Byte.MAX_VALUE; public static char fieldStaticChar = 'a'; public static short fieldStaticShort = Short.MAX_VALUE; public static int fieldStaticInteger = Integer.MAX_VALUE; public static long fieldStaticLong = Long.MAX_VALUE; public static double fieldStaticDouble = 1.1; public static float fieldStaticFloat = 1.1f; public static String fieldStaticString = "a static string"; public boolean fieldBoolean = true; public byte fieldByte = Byte.MAX_VALUE; public char fieldChar = 'a'; public short fieldShort = Short.MAX_VALUE; public int fieldInteger = Integer.MAX_VALUE; public long fieldLong = Long.MAX_VALUE; public double fieldDouble = 1.1; public float fieldFloat = 1.1f; public String fieldString = "a string"; public static Boolean fieldStaticBooleanObject = true; public static Byte fieldStaticByteObject = Byte.MAX_VALUE; public static Character fieldStaticCharObject = 'a'; public static Short fieldStaticShortObject = Short.MAX_VALUE; public static Integer fieldStaticIntegerObject = Integer.MAX_VALUE; public static Long fieldStaticLongObject = Long.MAX_VALUE; public static Double fieldStaticDoubleObject = Double.MAX_VALUE; public static Float fieldStaticFloatObject = Float.MAX_VALUE; public Boolean fieldBooleanObject = true; public Byte fieldByteObject = Byte.MAX_VALUE; public Character fieldCharObject = 'a'; public Short fieldShortObject = Short.MAX_VALUE; public Integer fieldIntegerObject = Integer.MAX_VALUE; public Long fieldLongObject = Long.MAX_VALUE; public Double fieldDoubleObject = Double.MAX_VALUE; public Float fieldFloatObject = Float.MAX_VALUE; public static Double fieldStaticNaNObject = Double.NaN; public static double fieldStaticNaN = Double.NaN; private static String fieldPrivateStaticString = "private static string"; protected static String fieldProtectedStaticString = "protected static string"; static String fieldPackageStaticString = "package static string"; private String fieldPrivateString = "private string"; protected String fieldProtectedString = "protected string"; String fieldPackageString = "package string"; private static int fieldPrivateStaticInt = Integer.MAX_VALUE; protected static int fieldProtectedStaticInt = Integer.MAX_VALUE; static int fieldPackageStaticInt = Integer.MAX_VALUE; private int fieldPrivateInt = Integer.MAX_VALUE; protected int fieldProtectedInt = Integer.MAX_VALUE; int fieldPackageInt = Integer.MAX_VALUE; public static boolean methodStaticBoolean() { return true; } public static byte methodStaticByte() { return Byte.MAX_VALUE; } public static char methodStaticChar() { return 'a'; } public static short methodStaticShort() { return Short.MAX_VALUE; } public static int methodStaticInteger() { return Integer.MAX_VALUE; } public static long methodStaticLong() { return Long.MAX_VALUE; } public static double methodStaticDouble() { return Double.MAX_VALUE; } public static float methodStaticFloat() { return Float.MAX_VALUE; } public static String methodStaticString() { return "a static string"; } public boolean methodBoolean() { return true; } public byte methodByte() { return Byte.MAX_VALUE; } public char methodChar() { return 'a'; } public short methodShort() { return Short.MAX_VALUE; } public int methodInteger() { return Integer.MAX_VALUE; } public long methodLong() { return Long.MAX_VALUE; } public double methodDouble() { return Double.MAX_VALUE; } public float methodFloat() { return Float.MAX_VALUE; } public String methodString() { return "string"; } public static Boolean methodStaticBooleanObject() { return true; } public static Byte methodStaticByteObject() { return Byte.MAX_VALUE; } public static Character methodStaticCharObject() { return 'a'; } public static Short methodStaticShortObject() { return Short.MAX_VALUE; } public static Integer methodStaticIntegerObject() { return Integer.MAX_VALUE; } public static Long methodStaticLongObject() { return Long.MAX_VALUE; } public static Double methodStaticDoubleObject() { return Double.MAX_VALUE; } public static Float methodStaticFloatObject() { return Float.MAX_VALUE; } public Boolean methodBooleanObject() { return true; } public Byte methodByteObject() { return Byte.MAX_VALUE; } public Character methodCharObject() { return 'a'; } public Short methodShortObject() { return Short.MAX_VALUE; } public Integer methodIntegerObject() { return Integer.MAX_VALUE; } public Long methodLongObject() { return Long.MAX_VALUE; } public Double methodDoubleObject() { return Double.MAX_VALUE; } public Float methodFloatObject() { return Float.MAX_VALUE; } public static Object methodStaticReturnsNull() { return null; } public Object methodReturnsNull() { return null; } private static String methodPrivateStaticString() { return fieldPrivateStaticString; } protected static String methodProtectedStaticString() { return fieldProtectedStaticString; } static String methodPackageStaticString() { return fieldPackageStaticString; } private String methodPrivateString() { return fieldPrivateString; } protected String methodProtectedString() { return fieldProtectedString; } String methodPackageString() { return fieldPackageString; } private static int methodPrivateStaticInt() { return fieldPrivateStaticInt; } protected static int methodProtectedStaticInt() { return fieldProtectedStaticInt; } static int methodPackageStaticInt() { return fieldPackageStaticInt; } private int methodPrivateInt() { return fieldPrivateInt; } protected int methodProtectedInt() { return fieldProtectedInt; } int methodPackageInt() { return fieldPackageInt; } public static Object fieldStaticNullObject = null; public Object fieldNullObject = null; public String allTypesMethod(boolean bo, byte bt, char ch, short sh, int in, long lo, double db, float fl, String st) { return "" + bo + bt + ch + sh + in + lo + db + fl + st; } public static Object allTypesStaticMethod(boolean bo, byte bt, char ch, short sh, int in, long lo, double db, float fl, String st) { return "" + bo + bt + ch + sh + in + lo + db + fl + st; } public String isNull(Boolean b) { return b == null ? Boolean.class.getName() : null; } public String isNull(Byte b) { return b == null ? Byte.class.getName() : null; } public String isNull(Character c) { return c == null ? Character.class.getName() : null; } public String isNull(Double d) { return d == null ? Double.class.getName() : null; } public String isNull(Float f) { return f == null ? Float.class.getName() : null; } public String isNull(Integer i) { return i == null ? Integer.class.getName() : null; } public String isNull(Long l) { return l == null ? Long.class.getName() : null; } public String isNull(Short s) { return s == null ? Short.class.getName() : null; } public String isNull(String s) { return s == null ? String.class.getName() : null; } public String isNull(boolean b) { throw new IllegalStateException("should not reach here"); } public String isNull(byte b) { throw new IllegalStateException("should not reach here"); } public String isNull(char c) { throw new IllegalStateException("should not reach here"); } public String isNull(double d) { throw new IllegalStateException("should not reach here"); } public String isNull(float f) { throw new IllegalStateException("should not reach here"); } public String isNull(int i) { throw new IllegalStateException("should not reach here"); } public String isNull(long l) { throw new IllegalStateException("should not reach here"); } public String isNull(short s) { throw new IllegalStateException("should not reach here"); } public String isOverloaded(boolean b) { return boolean.class.getName(); } public String isOverloaded(Byte b) { return Byte.class.getName(); } public String isOverloaded(char c) { return char.class.getName(); } public String isOverloaded(Double d) { return Double.class.getName(); } public String isOverloaded(Float f) { return Float.class.getName(); } public String isOverloaded(Short c) { return Short.class.getName(); } public String isOverloaded(String s) { return String.class.getName(); } public String isOverloaded(Integer i) { return Integer.class.getName(); } public String isOverloaded(Long l) { return Long.class.getName(); } public String classAsArg(Class<?> c) { return c.getName(); } public String ambiguous(Object o, String s) { return "ambiguous(Object,String)"; } public String ambiguous(String s, Object o) { return "ambiguous(String,Object)"; } public String ambiguous2(int x, Object[] xs) { return "ambiguous2(int,Object[])"; } public String ambiguous2(int x, int[] xs) { return "ambiguous2(int,int[])"; } } @SuppressWarnings({"unused", "static-method"}) public static final class TestClass2 { public String isOverloaded(Integer c) { return Integer.class.getName(); } public String isOverloaded(long l) { return long.class.getName(); } public String isOverloaded(Character c) { return Character.class.getName(); } public String isOverloaded(double l) { return double.class.getName(); } public String isOverloaded(Boolean b) { return Boolean.class.getName(); } public String isOverloaded(byte b) { return byte.class.getName(); } public String isOverloaded(float f) { return float.class.getName(); } public String isOverloaded(int c) { return int.class.getName(); } public String isOverloaded(Long l) { return Long.class.getName(); } public String isOverloaded(short c) { return short.class.getName(); } public void methodThrowsIOException() throws IOException { throw new IOException(); } } @SuppressWarnings({"unused"}) public static final class TestConstructor { private int i; private float f; public String ctor; public TestConstructor() { this.ctor = void.class.getName(); } public TestConstructor(int i) { this.i = i; this.ctor = int.class.getName(); } public TestConstructor(float f) { this.f = f; this.ctor = float.class.getName(); } } @SuppressWarnings({"unused"}) public static class TestConstructorException { public TestConstructorException(String s) throws IOException { throw new IOException(); } public TestConstructorException(String s, int i) { } } public interface CallUnderscore { // Checkstyle: stop Object create__Lcom_oracle_truffle_api_interop_java_test_Test_1Underscore_2(); Object copy__Lcom_oracle_truffle_api_interop_java_test_Test_1Underscore_2Lcom_oracle_truffle_api_interop_java_test_Test_1Underscore_2(Object orig); // Checkstyle: resume } }
oracle/graal
36,884
truffle/src/com.oracle.truffle.api.test/src/com/oracle/truffle/api/test/polyglot/MultiThreadedLanguageTest.java
/* * Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The Universal Permissive License (UPL), Version 1.0 * * Subject to the condition set forth below, permission is hereby granted to any * person obtaining a copy of this software, associated documentation and/or * data (collectively the "Software"), free of charge and under any and all * copyright rights in the Software, and any and all patent rights owned or * freely licensable by each licensor hereunder covering either (i) the * unmodified Software as contributed to or provided by such licensor, or (ii) * the Larger Works (as defined below), to deal in both * * (a) the Software, and * * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if * one is included with the Software each a "Larger Work" to which the Software * is contributed by such licensors), * * without restriction, including without limitation the rights to copy, create * derivative works of, display, perform, and distribute the Software and make, * use, sell, offer for sale, import, export, have made, and have sold the * Software and the Larger Work(s), and to sublicense the foregoing rights on * either these or other terms. * * This license is subject to the following condition: * * The above copyright notice and either this complete permission notice or at a * minimum a reference to the UPL must be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.oracle.truffle.api.test.polyglot; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Function; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Engine; import org.graalvm.polyglot.PolyglotException; import org.graalvm.polyglot.Value; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.oracle.truffle.api.TruffleContext; import com.oracle.truffle.api.TruffleLanguage.Env; import com.oracle.truffle.api.test.polyglot.MultiThreadedLanguage.LanguageContext; import com.oracle.truffle.api.test.polyglot.MultiThreadedLanguage.ThreadRequest; import com.oracle.truffle.tck.tests.TruffleTestAssumptions; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @SuppressWarnings("hiding") @RunWith(Parameterized.class) public class MultiThreadedLanguageTest extends AbstractThreadedPolyglotTest { @BeforeClass public static void runWithWeakEncapsulationOnly() { TruffleTestAssumptions.assumeWeakEncapsulation(); } private static Value eval(Context context, Function<Env, Object> f) { MultiThreadedLanguage.runinside.set(f); try { return context.eval(MultiThreadedLanguage.ID, ""); } finally { MultiThreadedLanguage.runinside.set(null); } } @Test public void testNoThreadAllowed() { Context context = Context.create(MultiThreadedLanguage.ID); MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return false; }; try { context.initialize(MultiThreadedLanguage.ID); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().contains("Single threaded access requested by thread ")); } try { eval(context, (env) -> null); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().contains("Single threaded access requested by thread ")); } try { eval(context, (env) -> null); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().contains("Single threaded access requested by thread ")); } // allow again so we can close MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return true; }; context.close(); } private static void assertMultiThreadedError(Value value, Consumer<Value> valueConsumer) { try { valueConsumer.accept(value); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage(), e.getMessage().contains("Multi threaded access requested by thread ")); } } private static void assertUnsupportedOrNoError(Value value, Consumer<Value> valueConsumer) { try { valueConsumer.accept(value); } catch (UnsupportedOperationException e) { } catch (ClassCastException e) { } catch (IllegalArgumentException e) { } catch (NullPointerException e) { } } @Test public void testSingleThreading() throws InterruptedException, ExecutionException { Context context = Context.create(MultiThreadedLanguage.ID); AtomicReference<ThreadRequest> lastIsAllowedRequest = new AtomicReference<>(null); MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { lastIsAllowedRequest.set(req); return req.singleThreaded; }; ExecutorService executor = createExecutor(1, vthreads); assertEquals(0, initializeCount.get()); assertNull(lastInitializeRequest.get()); Value value = eval(context, (env) -> new Object()); assertEquals(1, initializeCount.get()); assertEquals(true, lastIsAllowedRequest.get().singleThreaded); assertSame(Thread.currentThread(), lastInitializeRequest.get().thread); assertSame(Thread.currentThread(), lastIsAllowedRequest.get().thread); CountDownLatch latch = new CountDownLatch(1); Completable<Value> future = evalAndWait(executor, context, true, latch, (ev) -> MultiThreadedLanguage.getContext()); latch.await(); assertEquals(2, initializeCount.get()); assertEquals(true, lastIsAllowedRequest.get().singleThreaded); assertSame(threads.iterator().next(), lastInitializeRequest.get().thread); assertSame(threads.iterator().next(), lastIsAllowedRequest.get().thread); assertEquals(0, disposeCount.get()); assertNull(lastDisposeRequest.get()); try { eval(context, (env) -> null); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage(), e.getMessage().contains("Multi threaded access requested by thread ")); } assertMultiThreadedError(value, Value::execute); assertMultiThreadedError(value, Value::isBoolean); // assertMultiThreadedError(value, Value::isHostObject); assertMultiThreadedError(value, Value::isNativePointer); assertMultiThreadedError(value, Value::isNull); assertMultiThreadedError(value, Value::isNumber); assertMultiThreadedError(value, Value::isString); assertMultiThreadedError(value, Value::isMetaObject); assertMultiThreadedError(value, Value::isTime); assertMultiThreadedError(value, Value::isTimeZone); assertMultiThreadedError(value, Value::isDate); assertMultiThreadedError(value, Value::isInstant); assertMultiThreadedError(value, Value::isException); assertMultiThreadedError(value, Value::fitsInByte); assertMultiThreadedError(value, Value::fitsInShort); assertMultiThreadedError(value, Value::fitsInInt); assertMultiThreadedError(value, Value::fitsInLong); assertMultiThreadedError(value, Value::fitsInFloat); assertMultiThreadedError(value, Value::fitsInDouble); // assertMultiThreadedError(value, Value::asHostObject); assertMultiThreadedError(value, Value::asBoolean); assertMultiThreadedError(value, Value::asByte); assertMultiThreadedError(value, Value::asShort); assertMultiThreadedError(value, Value::asInt); assertMultiThreadedError(value, Value::asLong); assertMultiThreadedError(value, Value::asFloat); assertMultiThreadedError(value, Value::asDouble); assertMultiThreadedError(value, Value::asNativePointer); assertMultiThreadedError(value, Value::asString); assertMultiThreadedError(value, Value::getArraySize); assertMultiThreadedError(value, Value::getMemberKeys); assertMultiThreadedError(value, Value::getMetaObject); assertMultiThreadedError(value, Value::asInstant); assertMultiThreadedError(value, Value::asDate); assertMultiThreadedError(value, Value::asTimeZone); assertMultiThreadedError(value, Value::asTime); assertMultiThreadedError(value, Value::getMetaQualifiedName); assertMultiThreadedError(value, Value::getMetaSimpleName); assertMultiThreadedError(value, Value::throwException); assertMultiThreadedError(value, (v) -> v.isMetaInstance("")); assertMultiThreadedError(value, (v) -> v.getMember("")); assertMultiThreadedError(value, (v) -> v.putMember("", null)); assertMultiThreadedError(value, (v) -> v.removeMember("")); assertMultiThreadedError(value, (v) -> v.hasMember("")); assertMultiThreadedError(value, (v) -> v.canExecute()); assertMultiThreadedError(value, (v) -> v.getArraySize()); assertMultiThreadedError(value, (v) -> v.getArrayElement(0)); assertMultiThreadedError(value, (v) -> v.removeArrayElement(0)); assertMultiThreadedError(value, (v) -> v.setArrayElement(0, null)); assertEquals(2, initializeCount.get()); assertSame(Thread.currentThread(), lastIsAllowedRequest.get().thread); assertEquals(false, lastIsAllowedRequest.get().singleThreaded); assertEquals(0, disposeCount.get()); assertNull(lastDisposeRequest.get()); // cannot close still running try { context.close(); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage(), e.getMessage().contains("The context is currently executing on another thread. Set cancelIfExecuting to true to stop the execution on this thread.")); } assertSame(Thread.currentThread(), lastIsAllowedRequest.get().thread); assertEquals(false, lastIsAllowedRequest.get().singleThreaded); future.complete(); assertNotNull(future.get()); // closing the context must call dispose for the one thread // that returned true on initialize. context.close(); assertEquals(2, initializeCount.get()); assertEquals(2, disposeCount.get()); assertTrue(lastDisposeRequest.get().thread == Thread.currentThread() || lastDisposeRequest.get().thread == threads.iterator().next()); // cleanup executor assertTrue(executor.shutdownNow().isEmpty()); } @Test public void testMultiThreading() throws InterruptedException, ExecutionException { AtomicReference<ThreadRequest> lastIsAllowedRequest = new AtomicReference<>(null); MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { lastIsAllowedRequest.set(req); return true; }; final int threadCount = 10; final int outerLoop = 10; final int innerLoop = 100; ExecutorService executor = createExecutor(threadCount, vthreads); for (int outerIter = 0; outerIter < outerLoop; outerIter++) { resetData(); Context context = Context.create(MultiThreadedLanguage.ID); assertEquals(0, initializeCount.get()); assertNull(lastInitializeRequest.get()); List<Completable<Value>> results = new ArrayList<>(); for (int iteration = 0; iteration < innerLoop; iteration++) { CountDownLatch latch = iteration == 0 ? new CountDownLatch(threadCount) : null; Value value = eval(context, (env) -> new Object()); for (int i = 0; i < threadCount; i++) { results.add(evalAndWait(executor, context, iteration == 0, latch, (ev) -> MultiThreadedLanguage.getContext())); } assertUnsupportedOrNoError(value, Value::execute); assertUnsupportedOrNoError(value, Value::isBoolean); assertUnsupportedOrNoError(value, Value::isHostObject); assertUnsupportedOrNoError(value, Value::isNativePointer); assertUnsupportedOrNoError(value, Value::isNull); assertUnsupportedOrNoError(value, Value::isNumber); assertUnsupportedOrNoError(value, Value::isString); assertUnsupportedOrNoError(value, Value::fitsInByte); assertUnsupportedOrNoError(value, Value::fitsInDouble); assertUnsupportedOrNoError(value, Value::fitsInFloat); assertUnsupportedOrNoError(value, Value::fitsInInt); assertUnsupportedOrNoError(value, Value::fitsInLong); assertUnsupportedOrNoError(value, Value::asBoolean); assertUnsupportedOrNoError(value, Value::asByte); assertUnsupportedOrNoError(value, Value::asDouble); assertUnsupportedOrNoError(value, Value::asFloat); assertUnsupportedOrNoError(value, Value::asHostObject); assertUnsupportedOrNoError(value, Value::asInt); assertUnsupportedOrNoError(value, Value::asLong); assertUnsupportedOrNoError(value, Value::asNativePointer); assertUnsupportedOrNoError(value, Value::asString); assertUnsupportedOrNoError(value, Value::getArraySize); assertUnsupportedOrNoError(value, Value::getMemberKeys); assertUnsupportedOrNoError(value, Value::getMetaObject); assertUnsupportedOrNoError(value, (v) -> v.getMember("")); assertUnsupportedOrNoError(value, (v) -> v.putMember("", null)); assertUnsupportedOrNoError(value, (v) -> v.hasMember("")); assertUnsupportedOrNoError(value, (v) -> v.canExecute()); assertUnsupportedOrNoError(value, (v) -> v.getArraySize()); assertUnsupportedOrNoError(value, (v) -> v.getArrayElement(0)); assertUnsupportedOrNoError(value, (v) -> v.setArrayElement(0, null)); // we need to wait for them once to ensure every thread is initialized if (iteration == 0) { latch.await(); for (Completable<Value> future : results) { future.complete(); } } } for (Completable<Value> future : results) { Object languageContext = future.get().asHostObject(); assertSame(MultiThreadedLanguage.langContext, languageContext); } assertEquals(threadCount + 1, initializeCount.get()); assertEquals(1, initializeMultiThreadingCount.get()); assertEquals(false, lastIsAllowedRequest.get().singleThreaded); context.close(); // main thread gets initialized after close as well assertEquals(false, lastIsAllowedRequest.get().singleThreaded); assertEquals(1, initializeMultiThreadingCount.get()); assertEquals(threadCount + 1, initializeCount.get()); assertEquals(threadCount + 1, disposeCount.get()); } assertTrue(executor.shutdownNow().isEmpty()); } @Test public void testAccessTruffleContextPolyglotThread() throws Throwable { MultiThreadedLanguage.isThreadAccessAllowed = (req) -> true; Engine engine = Engine.create(); AtomicReference<Throwable> seenError = new AtomicReference<>(); Context context = Context.newBuilder().allowCreateThread(true).engine(engine).build(); eval(context, new Function<Env, Object>() { public Object apply(Env env) { List<Thread> createdThreads = new ArrayList<>(); ExecutorService service = Executors.newFixedThreadPool(10, (r) -> { Thread t = env.newTruffleThreadBuilder(r).virtual(vthreads).build(); t.setUncaughtExceptionHandler((thread, e) -> seenError.set(e)); createdThreads.add(t); return t; }); TruffleContext innerContext = env.newInnerContextBuilder().initializeCreatorContext(true).inheritAllAccess(true).build(); List<Future<LanguageContext>> futures = new ArrayList<>(); List<Future<LanguageContext>> innerContextFutures = new ArrayList<>(); for (int i = 0; i < 100; i++) { innerContextFutures.add(service.submit(() -> { Object prev = innerContext.enter(null); try { return MultiThreadedLanguage.getContext(); } finally { innerContext.leave(null, prev); } })); } for (int i = 0; i < 100; i++) { futures.add(service.submit(() -> { return MultiThreadedLanguage.getContext(); })); } try { for (Future<LanguageContext> future : futures) { assertSame(MultiThreadedLanguage.getContext(), future.get()); } LanguageContext innerLanguageContext; Object prev = innerContext.enter(null); innerLanguageContext = MultiThreadedLanguage.getContext(); innerContext.leave(null, prev); for (Future<LanguageContext> future : innerContextFutures) { assertSame(innerLanguageContext, future.get()); } innerContext.close(); } catch (InterruptedException e1) { throw new AssertionError(e1); } catch (ExecutionException e1) { throw new AssertionError(e1); } service.shutdown(); /* * We need to join all threads as unfortunately the executor service does not * guarantee that all threads are immediately shutdown. */ try { for (Thread t : createdThreads) { t.join(1000); } } catch (InterruptedException e1) { throw new AssertionError(e1); } return MultiThreadedLanguage.getContext(); } }); if (seenError.get() != null) { throw seenError.get(); } engine.close(); } @Test public void testAccessTruffleContextFromExclusivePolyglotThread() throws Throwable { // don't allow multi-threading in this test as every context // is used exclusively by one thread. MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return req.singleThreaded; }; final int iterations = 10; final int innerIterations = 10; AtomicReference<Throwable> lastError = new AtomicReference<>(); UncaughtExceptionHandler uncaughtHandler = (run, e) -> lastError.set(e); Context polyglotContext = Context.newBuilder().allowCreateThread(true).build(); ConcurrentHashMap<LanguageContext, String> seenContexts = new ConcurrentHashMap<>(); eval(polyglotContext, new Function<Env, Object>() { @SuppressWarnings("hiding") public Object apply(Env env) { List<Thread> threads = new ArrayList<>(); List<TruffleContext> contexts = new ArrayList<>(); for (int i = 0; i < iterations; i++) { TruffleContext context = env.newInnerContextBuilder().initializeCreatorContext(true).inheritAllAccess(true).build(); Thread thread = env.newTruffleThreadBuilder(() -> { assertUniqueContext(); List<Thread> innerThreads = new ArrayList<>(); List<TruffleContext> innerContexts = new ArrayList<>(); for (int j = 0; j < innerIterations; j++) { TruffleContext innerContext = env.newInnerContextBuilder().initializeCreatorContext(true).inheritAllAccess(true).build(); Thread innerThread = env.newTruffleThreadBuilder(() -> { assertUniqueContext(); }).virtual(vthreads).context(innerContext).build(); innerThread.setUncaughtExceptionHandler(uncaughtHandler); innerThread.start(); innerThreads.add(innerThread); innerContexts.add(innerContext); } for (Thread innerThread : innerThreads) { try { innerThread.join(); } catch (InterruptedException e) { } } for (TruffleContext innerContext : innerContexts) { innerContext.close(); } }).virtual(vthreads).context(context).build(); thread.setUncaughtExceptionHandler(uncaughtHandler); thread.start(); threads.add(thread); contexts.add(context); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { } } for (TruffleContext context : contexts) { context.close(); } return null; } private LanguageContext assertUniqueContext() { LanguageContext languageContext = MultiThreadedLanguage.getContext(); Assert.assertNotNull(languageContext); Assert.assertFalse(seenContexts.containsKey(languageContext)); seenContexts.put(languageContext, ""); return languageContext; } }); Assert.assertEquals(221, initializeCount.get()); Assert.assertEquals(initializeCount.get() - 1, disposeCount.get()); Assert.assertEquals(0, initializeMultiThreadingCount.get()); // Test that the same context is available in threads when created with Env.getContext() MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return true; }; eval(polyglotContext, new Function<Env, Object>() { @SuppressWarnings("hiding") public Object apply(Env env) { List<Thread> threads = new ArrayList<>(); LanguageContext languageContext = MultiThreadedLanguage.getContext(); for (int i = 0; i < iterations; i++) { Thread thread = env.newTruffleThreadBuilder(() -> { LanguageContext threadContext = MultiThreadedLanguage.getContext(); assertSame(languageContext, threadContext); List<Thread> innerThreads = new ArrayList<>(); List<TruffleContext> innerContexts = new ArrayList<>(); for (int j = 0; j < innerIterations; j++) { Thread innerThread = env.newTruffleThreadBuilder(() -> { LanguageContext innerThreadContext = MultiThreadedLanguage.getContext(); assertSame(languageContext, innerThreadContext); }).virtual(vthreads).context(env.getContext()).build(); innerThread.setUncaughtExceptionHandler(uncaughtHandler); innerThread.start(); innerThreads.add(innerThread); } for (Thread innerThread : innerThreads) { try { innerThread.join(); } catch (InterruptedException e) { } } for (TruffleContext innerContext : innerContexts) { innerContext.close(); } }).virtual(vthreads).context(env.getContext()).build(); thread.setUncaughtExceptionHandler(uncaughtHandler); thread.start(); threads.add(thread); } for (Thread thread : threads) { try { thread.join(); } catch (InterruptedException e) { } } return null; } }); if (lastError.get() != null) { throw lastError.get(); } polyglotContext.close(); Assert.assertEquals(331, initializeCount.get()); Assert.assertEquals(initializeCount.get(), disposeCount.get()); Assert.assertEquals(1, initializeMultiThreadingCount.get()); } @Test public void testAsssertionIfThreadStillActive() throws InterruptedException { MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return true; }; Engine engine = Engine.create(); Context context = Context.newBuilder().allowCreateThread(true).engine(engine).build(); Semaphore wait = new Semaphore(0); Thread returnThread = eval(context, new Function<Env, Object>() { public Object apply(Env env) { Semaphore waitForEnter = new Semaphore(0); Thread t = env.newTruffleThreadBuilder(() -> { try { waitForEnter.release(); wait.acquire(); } catch (InterruptedException e) { } }).virtual(vthreads).build(); t.start(); try { waitForEnter.acquire(); } catch (InterruptedException e) { } return t; } }).asHostObject(); try { engine.close(); Assert.fail(); } catch (PolyglotException e) { assertTrue(e.isInternalError()); assertTrue(e.getMessage().contains("The language did not complete all polyglot threads but should have")); } wait.release(1); returnThread.join(); engine.close(); } @Test public void testInterruptPolyglotThread() throws Throwable { AtomicReference<Thread> tref = new AtomicReference<>(); MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return true; }; MultiThreadedLanguage.finalizeContext = (context) -> { try { tref.get().join(); } catch (InterruptedException e) { throw new AssertionError(e); } return null; }; AtomicBoolean seenInterrupt = new AtomicBoolean(false); AtomicReference<Throwable> seenError = new AtomicReference<>(); Engine engine = Engine.create(); Context context = Context.newBuilder().allowCreateThread(true).engine(engine).build(); Semaphore wait = new Semaphore(0); eval(context, new Function<Env, Object>() { public Object apply(Env env) { Semaphore waitForEnter = new Semaphore(0); Thread t = env.newTruffleThreadBuilder(() -> { try { waitForEnter.release(); wait.acquire(); } catch (InterruptedException e) { seenInterrupt.set(true); } }).virtual(vthreads).build(); tref.set(t); t.setUncaughtExceptionHandler((thread, e) -> seenError.set(e)); t.start(); try { waitForEnter.acquire(); } catch (InterruptedException e) { } return t; } }).asHostObject(); engine.close(true); if (seenError.get() != null) { throw seenError.get(); } Assert.assertTrue(seenInterrupt.get()); } @Test public void testMultiThreadedAccessExceptionThrownToCreator() throws Throwable { try (Context context = Context.newBuilder(MultiThreadedLanguage.ID).allowCreateThread(true).build()) { MultiThreadedLanguage.isThreadAccessAllowed = (req) -> { return req.singleThreaded; }; eval(context, (env) -> { AbstractPolyglotTest.assertFails(() -> env.newTruffleThreadBuilder(() -> { }).virtual(vthreads).build(), IllegalStateException.class, (ise) -> { assertTrue(ise.getMessage().contains("Multi threaded access requested by thread")); }); return null; }); } } /* * Test infrastructure code. */ private final List<Thread> threads = new ArrayList<>(); private final List<ExecutorService> executors = new ArrayList<>(); volatile AtomicInteger initializeCount; volatile AtomicInteger disposeCount; volatile AtomicInteger initializeMultiThreadingCount; volatile AtomicReference<ThreadRequest> lastInitializeRequest; volatile AtomicReference<ThreadRequest> lastDisposeRequest; private final Map<Object, Set<Thread>> initializedThreadsPerContext = Collections.synchronizedMap(new HashMap<>()); @Before public void setup() { resetData(); MultiThreadedLanguage.initializeMultiThreading = (req) -> { initializeMultiThreadingCount.incrementAndGet(); Assert.assertSame(req.context, MultiThreadedLanguage.getContext()); return null; }; MultiThreadedLanguage.initializeThread = (req) -> { initializeCount.incrementAndGet(); lastInitializeRequest.set(req); Assert.assertSame(req.context, MultiThreadedLanguage.getContext()); Set<Thread> threadsPerContext = initializedThreadsPerContext.computeIfAbsent(req.context, (e) -> Collections.synchronizedSet(new HashSet<Thread>())); if (threadsPerContext.contains(req.thread)) { throw new AssertionError("Thread initialized twice for context " + req.context + " thread " + req.thread); } threadsPerContext.add(req.thread); return null; }; MultiThreadedLanguage.disposeThread = (req) -> { disposeCount.incrementAndGet(); lastDisposeRequest.set(req); Assert.assertSame(req.context, MultiThreadedLanguage.getContext()); Set<Thread> threadsPerContext = initializedThreadsPerContext.get(req.context); if (!threadsPerContext.contains(req.thread)) { throw new AssertionError("Not initialized but disposed thread " + req.thread); } // should not be able to dispose twice. threadsPerContext.remove(req.thread); return null; }; } private void resetData() { initializeCount = new AtomicInteger(0); disposeCount = new AtomicInteger(0); initializeMultiThreadingCount = new AtomicInteger(0); lastInitializeRequest = new AtomicReference<>(null); lastDisposeRequest = new AtomicReference<>(null); initializedThreadsPerContext.clear(); } @After public void teardown() { threads.clear(); for (ExecutorService executor : executors) { assertTrue(executor.shutdownNow().isEmpty()); } executors.clear(); for (Entry<Object, Set<Thread>> entry : initializedThreadsPerContext.entrySet()) { if (!entry.getValue().isEmpty()) { throw new AssertionError("Threads initialized but not disposed for context " + entry.getKey() + ": " + entry.getValue()); } } } private ExecutorService createExecutor(int noThreads, boolean vthreads) { threads.clear(); ExecutorService service = Executors.newFixedThreadPool(noThreads, (r) -> { Thread t = vthreads ? Thread.ofVirtual().unstarted(r) : new Thread(r); threads.add(t); return t; }); executors.add(service); return service; } /** * Method evals code on another thread and waits until the function is finished evaluation. The * future then waits until Future#get is invoked to complete the operation. */ private static Completable<Value> evalAndWait(ExecutorService executor, Context context, boolean manualComplete, CountDownLatch latch, Function<Env, Object> f) { Semaphore waitInEval = manualComplete ? new Semaphore(0) : null; Future<Value> valueResult = executor.<Value> submit(() -> { try { return eval(context, (env) -> { Object result = f.apply(env); try { if (latch != null) { latch.countDown(); } if (waitInEval != null) { waitInEval.acquire(); } } catch (InterruptedException e) { // cancelled } return result; }); } catch (Throwable e) { if (latch != null) { latch.countDown(); } throw e; } }); return new Completable<>(valueResult, waitInEval); } private static class Completable<V> implements Future<V> { private final Future<V> delegate; private final Semaphore waitInEval; Completable(Future<V> delegate, Semaphore waitInEval) { this.delegate = delegate; this.waitInEval = waitInEval; } public boolean cancel(boolean mayInterruptIfRunning) { return delegate.cancel(mayInterruptIfRunning); } public boolean isCancelled() { return delegate.isCancelled(); } public boolean isDone() { return delegate.isDone(); } public V get() throws InterruptedException, ExecutionException { return delegate.get(); } public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.get(timeout, unit); } void complete() { waitInEval.release(); } } }
googleapis/google-cloud-java
36,511
java-speech/proto-google-cloud-speech-v2/src/main/java/com/google/cloud/speech/v2/ExplicitDecodingConfig.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> * Explicitly specified decoding parameters. * </pre> * * Protobuf type {@code google.cloud.speech.v2.ExplicitDecodingConfig} */ public final class ExplicitDecodingConfig extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.speech.v2.ExplicitDecodingConfig) ExplicitDecodingConfigOrBuilder { private static final long serialVersionUID = 0L; // Use ExplicitDecodingConfig.newBuilder() to construct. private ExplicitDecodingConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ExplicitDecodingConfig() { encoding_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ExplicitDecodingConfig(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ExplicitDecodingConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ExplicitDecodingConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.ExplicitDecodingConfig.class, com.google.cloud.speech.v2.ExplicitDecodingConfig.Builder.class); } /** * * * <pre> * Supported audio data encodings. * </pre> * * Protobuf enum {@code google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding} */ public enum AudioEncoding implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * Default value. This value is unused. * </pre> * * <code>AUDIO_ENCODING_UNSPECIFIED = 0;</code> */ AUDIO_ENCODING_UNSPECIFIED(0), /** * * * <pre> * Headerless 16-bit signed little-endian PCM samples. * </pre> * * <code>LINEAR16 = 1;</code> */ LINEAR16(1), /** * * * <pre> * Headerless 8-bit companded mulaw samples. * </pre> * * <code>MULAW = 2;</code> */ MULAW(2), /** * * * <pre> * Headerless 8-bit companded alaw samples. * </pre> * * <code>ALAW = 3;</code> */ ALAW(3), /** * * * <pre> * AMR frames with an rfc4867.5 header. * </pre> * * <code>AMR = 4;</code> */ AMR(4), /** * * * <pre> * AMR-WB frames with an rfc4867.5 header. * </pre> * * <code>AMR_WB = 5;</code> */ AMR_WB(5), /** * * * <pre> * FLAC frames in the "native FLAC" container format. * </pre> * * <code>FLAC = 6;</code> */ FLAC(6), /** * * * <pre> * MPEG audio frames with optional (ignored) ID3 metadata. * </pre> * * <code>MP3 = 7;</code> */ MP3(7), /** * * * <pre> * Opus audio frames in an Ogg container. * </pre> * * <code>OGG_OPUS = 8;</code> */ OGG_OPUS(8), /** * * * <pre> * Opus audio frames in a WebM container. * </pre> * * <code>WEBM_OPUS = 9;</code> */ WEBM_OPUS(9), /** * * * <pre> * AAC audio frames in an MP4 container. * </pre> * * <code>MP4_AAC = 10;</code> */ MP4_AAC(10), /** * * * <pre> * AAC audio frames in an M4A container. * </pre> * * <code>M4A_AAC = 11;</code> */ M4A_AAC(11), /** * * * <pre> * AAC audio frames in an MOV container. * </pre> * * <code>MOV_AAC = 12;</code> */ MOV_AAC(12), UNRECOGNIZED(-1), ; /** * * * <pre> * Default value. This value is unused. * </pre> * * <code>AUDIO_ENCODING_UNSPECIFIED = 0;</code> */ public static final int AUDIO_ENCODING_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Headerless 16-bit signed little-endian PCM samples. * </pre> * * <code>LINEAR16 = 1;</code> */ public static final int LINEAR16_VALUE = 1; /** * * * <pre> * Headerless 8-bit companded mulaw samples. * </pre> * * <code>MULAW = 2;</code> */ public static final int MULAW_VALUE = 2; /** * * * <pre> * Headerless 8-bit companded alaw samples. * </pre> * * <code>ALAW = 3;</code> */ public static final int ALAW_VALUE = 3; /** * * * <pre> * AMR frames with an rfc4867.5 header. * </pre> * * <code>AMR = 4;</code> */ public static final int AMR_VALUE = 4; /** * * * <pre> * AMR-WB frames with an rfc4867.5 header. * </pre> * * <code>AMR_WB = 5;</code> */ public static final int AMR_WB_VALUE = 5; /** * * * <pre> * FLAC frames in the "native FLAC" container format. * </pre> * * <code>FLAC = 6;</code> */ public static final int FLAC_VALUE = 6; /** * * * <pre> * MPEG audio frames with optional (ignored) ID3 metadata. * </pre> * * <code>MP3 = 7;</code> */ public static final int MP3_VALUE = 7; /** * * * <pre> * Opus audio frames in an Ogg container. * </pre> * * <code>OGG_OPUS = 8;</code> */ public static final int OGG_OPUS_VALUE = 8; /** * * * <pre> * Opus audio frames in a WebM container. * </pre> * * <code>WEBM_OPUS = 9;</code> */ public static final int WEBM_OPUS_VALUE = 9; /** * * * <pre> * AAC audio frames in an MP4 container. * </pre> * * <code>MP4_AAC = 10;</code> */ public static final int MP4_AAC_VALUE = 10; /** * * * <pre> * AAC audio frames in an M4A container. * </pre> * * <code>M4A_AAC = 11;</code> */ public static final int M4A_AAC_VALUE = 11; /** * * * <pre> * AAC audio frames in an MOV container. * </pre> * * <code>MOV_AAC = 12;</code> */ public static final int MOV_AAC_VALUE = 12; 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 AudioEncoding 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 AudioEncoding forNumber(int value) { switch (value) { case 0: return AUDIO_ENCODING_UNSPECIFIED; case 1: return LINEAR16; case 2: return MULAW; case 3: return ALAW; case 4: return AMR; case 5: return AMR_WB; case 6: return FLAC; case 7: return MP3; case 8: return OGG_OPUS; case 9: return WEBM_OPUS; case 10: return MP4_AAC; case 11: return M4A_AAC; case 12: return MOV_AAC; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<AudioEncoding> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<AudioEncoding> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<AudioEncoding>() { public AudioEncoding findValueByNumber(int number) { return AudioEncoding.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.speech.v2.ExplicitDecodingConfig.getDescriptor() .getEnumTypes() .get(0); } private static final AudioEncoding[] VALUES = values(); public static AudioEncoding 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 AudioEncoding(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding) } public static final int ENCODING_FIELD_NUMBER = 1; private int encoding_ = 0; /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for encoding. */ @java.lang.Override public int getEncodingValue() { return encoding_; } /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The encoding. */ @java.lang.Override public com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding getEncoding() { com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding result = com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding.forNumber(encoding_); return result == null ? com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding.UNRECOGNIZED : result; } public static final int SAMPLE_RATE_HERTZ_FIELD_NUMBER = 2; private int sampleRateHertz_ = 0; /** * * * <pre> * Optional. Sample rate in Hertz of the audio data sent for recognition. * Valid values are: 8000-48000, and 16000 is optimal. For best results, set * the sampling rate of the audio source to 16000 Hz. If that's not possible, * use the native sample rate of the audio source (instead of resampling). * Note that this field is marked as OPTIONAL for backward compatibility * reasons. It is (and has always been) effectively REQUIRED. * </pre> * * <code>int32 sample_rate_hertz = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The sampleRateHertz. */ @java.lang.Override public int getSampleRateHertz() { return sampleRateHertz_; } public static final int AUDIO_CHANNEL_COUNT_FIELD_NUMBER = 3; private int audioChannelCount_ = 0; /** * * * <pre> * Optional. Number of channels present in the audio data sent for * recognition. Note that this field is marked as OPTIONAL for backward * compatibility reasons. It is (and has always been) effectively REQUIRED. * * The maximum allowed value is 8. * </pre> * * <code>int32 audio_channel_count = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The audioChannelCount. */ @java.lang.Override public int getAudioChannelCount() { return audioChannelCount_; } 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 (encoding_ != com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding .AUDIO_ENCODING_UNSPECIFIED .getNumber()) { output.writeEnum(1, encoding_); } if (sampleRateHertz_ != 0) { output.writeInt32(2, sampleRateHertz_); } if (audioChannelCount_ != 0) { output.writeInt32(3, audioChannelCount_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (encoding_ != com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding .AUDIO_ENCODING_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, encoding_); } if (sampleRateHertz_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, sampleRateHertz_); } if (audioChannelCount_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, audioChannelCount_); } 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.ExplicitDecodingConfig)) { return super.equals(obj); } com.google.cloud.speech.v2.ExplicitDecodingConfig other = (com.google.cloud.speech.v2.ExplicitDecodingConfig) obj; if (encoding_ != other.encoding_) return false; if (getSampleRateHertz() != other.getSampleRateHertz()) return false; if (getAudioChannelCount() != other.getAudioChannelCount()) 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) + ENCODING_FIELD_NUMBER; hash = (53 * hash) + encoding_; hash = (37 * hash) + SAMPLE_RATE_HERTZ_FIELD_NUMBER; hash = (53 * hash) + getSampleRateHertz(); hash = (37 * hash) + AUDIO_CHANNEL_COUNT_FIELD_NUMBER; hash = (53 * hash) + getAudioChannelCount(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.speech.v2.ExplicitDecodingConfig parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.ExplicitDecodingConfig 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.ExplicitDecodingConfig parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.ExplicitDecodingConfig 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.ExplicitDecodingConfig parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.speech.v2.ExplicitDecodingConfig 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.ExplicitDecodingConfig parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.ExplicitDecodingConfig 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.ExplicitDecodingConfig parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.speech.v2.ExplicitDecodingConfig 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.ExplicitDecodingConfig 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.ExplicitDecodingConfig 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.ExplicitDecodingConfig 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> * Explicitly specified decoding parameters. * </pre> * * Protobuf type {@code google.cloud.speech.v2.ExplicitDecodingConfig} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.speech.v2.ExplicitDecodingConfig) com.google.cloud.speech.v2.ExplicitDecodingConfigOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ExplicitDecodingConfig_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.speech.v2.CloudSpeechProto .internal_static_google_cloud_speech_v2_ExplicitDecodingConfig_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.speech.v2.ExplicitDecodingConfig.class, com.google.cloud.speech.v2.ExplicitDecodingConfig.Builder.class); } // Construct using com.google.cloud.speech.v2.ExplicitDecodingConfig.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; encoding_ = 0; sampleRateHertz_ = 0; audioChannelCount_ = 0; 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_ExplicitDecodingConfig_descriptor; } @java.lang.Override public com.google.cloud.speech.v2.ExplicitDecodingConfig getDefaultInstanceForType() { return com.google.cloud.speech.v2.ExplicitDecodingConfig.getDefaultInstance(); } @java.lang.Override public com.google.cloud.speech.v2.ExplicitDecodingConfig build() { com.google.cloud.speech.v2.ExplicitDecodingConfig result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.speech.v2.ExplicitDecodingConfig buildPartial() { com.google.cloud.speech.v2.ExplicitDecodingConfig result = new com.google.cloud.speech.v2.ExplicitDecodingConfig(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.speech.v2.ExplicitDecodingConfig result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.encoding_ = encoding_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.sampleRateHertz_ = sampleRateHertz_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.audioChannelCount_ = audioChannelCount_; } } @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.ExplicitDecodingConfig) { return mergeFrom((com.google.cloud.speech.v2.ExplicitDecodingConfig) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.speech.v2.ExplicitDecodingConfig other) { if (other == com.google.cloud.speech.v2.ExplicitDecodingConfig.getDefaultInstance()) return this; if (other.encoding_ != 0) { setEncodingValue(other.getEncodingValue()); } if (other.getSampleRateHertz() != 0) { setSampleRateHertz(other.getSampleRateHertz()); } if (other.getAudioChannelCount() != 0) { setAudioChannelCount(other.getAudioChannelCount()); } 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: { encoding_ = input.readEnum(); bitField0_ |= 0x00000001; break; } // case 8 case 16: { sampleRateHertz_ = input.readInt32(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { audioChannelCount_ = 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 int encoding_ = 0; /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The enum numeric value on the wire for encoding. */ @java.lang.Override public int getEncodingValue() { return encoding_; } /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The enum numeric value on the wire for encoding to set. * @return This builder for chaining. */ public Builder setEncodingValue(int value) { encoding_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The encoding. */ @java.lang.Override public com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding getEncoding() { com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding result = com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding.forNumber(encoding_); return result == null ? com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding.UNRECOGNIZED : result; } /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @param value The encoding to set. * @return This builder for chaining. */ public Builder setEncoding( com.google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; encoding_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Required. Encoding of the audio data sent for recognition. * </pre> * * <code> * .google.cloud.speech.v2.ExplicitDecodingConfig.AudioEncoding encoding = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return This builder for chaining. */ public Builder clearEncoding() { bitField0_ = (bitField0_ & ~0x00000001); encoding_ = 0; onChanged(); return this; } private int sampleRateHertz_; /** * * * <pre> * Optional. Sample rate in Hertz of the audio data sent for recognition. * Valid values are: 8000-48000, and 16000 is optimal. For best results, set * the sampling rate of the audio source to 16000 Hz. If that's not possible, * use the native sample rate of the audio source (instead of resampling). * Note that this field is marked as OPTIONAL for backward compatibility * reasons. It is (and has always been) effectively REQUIRED. * </pre> * * <code>int32 sample_rate_hertz = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The sampleRateHertz. */ @java.lang.Override public int getSampleRateHertz() { return sampleRateHertz_; } /** * * * <pre> * Optional. Sample rate in Hertz of the audio data sent for recognition. * Valid values are: 8000-48000, and 16000 is optimal. For best results, set * the sampling rate of the audio source to 16000 Hz. If that's not possible, * use the native sample rate of the audio source (instead of resampling). * Note that this field is marked as OPTIONAL for backward compatibility * reasons. It is (and has always been) effectively REQUIRED. * </pre> * * <code>int32 sample_rate_hertz = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The sampleRateHertz to set. * @return This builder for chaining. */ public Builder setSampleRateHertz(int value) { sampleRateHertz_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. Sample rate in Hertz of the audio data sent for recognition. * Valid values are: 8000-48000, and 16000 is optimal. For best results, set * the sampling rate of the audio source to 16000 Hz. If that's not possible, * use the native sample rate of the audio source (instead of resampling). * Note that this field is marked as OPTIONAL for backward compatibility * reasons. It is (and has always been) effectively REQUIRED. * </pre> * * <code>int32 sample_rate_hertz = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearSampleRateHertz() { bitField0_ = (bitField0_ & ~0x00000002); sampleRateHertz_ = 0; onChanged(); return this; } private int audioChannelCount_; /** * * * <pre> * Optional. Number of channels present in the audio data sent for * recognition. Note that this field is marked as OPTIONAL for backward * compatibility reasons. It is (and has always been) effectively REQUIRED. * * The maximum allowed value is 8. * </pre> * * <code>int32 audio_channel_count = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The audioChannelCount. */ @java.lang.Override public int getAudioChannelCount() { return audioChannelCount_; } /** * * * <pre> * Optional. Number of channels present in the audio data sent for * recognition. Note that this field is marked as OPTIONAL for backward * compatibility reasons. It is (and has always been) effectively REQUIRED. * * The maximum allowed value is 8. * </pre> * * <code>int32 audio_channel_count = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The audioChannelCount to set. * @return This builder for chaining. */ public Builder setAudioChannelCount(int value) { audioChannelCount_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. Number of channels present in the audio data sent for * recognition. Note that this field is marked as OPTIONAL for backward * compatibility reasons. It is (and has always been) effectively REQUIRED. * * The maximum allowed value is 8. * </pre> * * <code>int32 audio_channel_count = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearAudioChannelCount() { bitField0_ = (bitField0_ & ~0x00000004); audioChannelCount_ = 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.speech.v2.ExplicitDecodingConfig) } // @@protoc_insertion_point(class_scope:google.cloud.speech.v2.ExplicitDecodingConfig) private static final com.google.cloud.speech.v2.ExplicitDecodingConfig DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.speech.v2.ExplicitDecodingConfig(); } public static com.google.cloud.speech.v2.ExplicitDecodingConfig getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ExplicitDecodingConfig> PARSER = new com.google.protobuf.AbstractParser<ExplicitDecodingConfig>() { @java.lang.Override public ExplicitDecodingConfig 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<ExplicitDecodingConfig> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ExplicitDecodingConfig> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.speech.v2.ExplicitDecodingConfig getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,552
java-functions/proto-google-cloud-functions-v2/src/main/java/com/google/cloud/functions/v2/CreateFunctionRequest.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/functions/v2/functions.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.functions.v2; /** * * * <pre> * Request for the `CreateFunction` method. * </pre> * * Protobuf type {@code google.cloud.functions.v2.CreateFunctionRequest} */ public final class CreateFunctionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.functions.v2.CreateFunctionRequest) CreateFunctionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateFunctionRequest.newBuilder() to construct. private CreateFunctionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateFunctionRequest() { parent_ = ""; functionId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateFunctionRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.functions.v2.FunctionsProto .internal_static_google_cloud_functions_v2_CreateFunctionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.functions.v2.FunctionsProto .internal_static_google_cloud_functions_v2_CreateFunctionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.functions.v2.CreateFunctionRequest.class, com.google.cloud.functions.v2.CreateFunctionRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </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 FUNCTION_FIELD_NUMBER = 2; private com.google.cloud.functions.v2.Function function_; /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the function field is set. */ @java.lang.Override public boolean hasFunction() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The function. */ @java.lang.Override public com.google.cloud.functions.v2.Function getFunction() { return function_ == null ? com.google.cloud.functions.v2.Function.getDefaultInstance() : function_; } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.functions.v2.FunctionOrBuilder getFunctionOrBuilder() { return function_ == null ? com.google.cloud.functions.v2.Function.getDefaultInstance() : function_; } public static final int FUNCTION_ID_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object functionId_ = ""; /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @return The functionId. */ @java.lang.Override public java.lang.String getFunctionId() { java.lang.Object ref = functionId_; 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(); functionId_ = s; return s; } } /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @return The bytes for functionId. */ @java.lang.Override public com.google.protobuf.ByteString getFunctionIdBytes() { java.lang.Object ref = functionId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); functionId_ = 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, getFunction()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(functionId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, functionId_); } 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, getFunction()); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(functionId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, functionId_); } 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.functions.v2.CreateFunctionRequest)) { return super.equals(obj); } com.google.cloud.functions.v2.CreateFunctionRequest other = (com.google.cloud.functions.v2.CreateFunctionRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasFunction() != other.hasFunction()) return false; if (hasFunction()) { if (!getFunction().equals(other.getFunction())) return false; } if (!getFunctionId().equals(other.getFunctionId())) 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 (hasFunction()) { hash = (37 * hash) + FUNCTION_FIELD_NUMBER; hash = (53 * hash) + getFunction().hashCode(); } hash = (37 * hash) + FUNCTION_ID_FIELD_NUMBER; hash = (53 * hash) + getFunctionId().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.functions.v2.CreateFunctionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.functions.v2.CreateFunctionRequest 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.functions.v2.CreateFunctionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.functions.v2.CreateFunctionRequest 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.functions.v2.CreateFunctionRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.functions.v2.CreateFunctionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.functions.v2.CreateFunctionRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.functions.v2.CreateFunctionRequest 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.functions.v2.CreateFunctionRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.functions.v2.CreateFunctionRequest 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.functions.v2.CreateFunctionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.functions.v2.CreateFunctionRequest 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.functions.v2.CreateFunctionRequest 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 the `CreateFunction` method. * </pre> * * Protobuf type {@code google.cloud.functions.v2.CreateFunctionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.functions.v2.CreateFunctionRequest) com.google.cloud.functions.v2.CreateFunctionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.functions.v2.FunctionsProto .internal_static_google_cloud_functions_v2_CreateFunctionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.functions.v2.FunctionsProto .internal_static_google_cloud_functions_v2_CreateFunctionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.functions.v2.CreateFunctionRequest.class, com.google.cloud.functions.v2.CreateFunctionRequest.Builder.class); } // Construct using com.google.cloud.functions.v2.CreateFunctionRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getFunctionFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; function_ = null; if (functionBuilder_ != null) { functionBuilder_.dispose(); functionBuilder_ = null; } functionId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.functions.v2.FunctionsProto .internal_static_google_cloud_functions_v2_CreateFunctionRequest_descriptor; } @java.lang.Override public com.google.cloud.functions.v2.CreateFunctionRequest getDefaultInstanceForType() { return com.google.cloud.functions.v2.CreateFunctionRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.functions.v2.CreateFunctionRequest build() { com.google.cloud.functions.v2.CreateFunctionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.functions.v2.CreateFunctionRequest buildPartial() { com.google.cloud.functions.v2.CreateFunctionRequest result = new com.google.cloud.functions.v2.CreateFunctionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.functions.v2.CreateFunctionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.function_ = functionBuilder_ == null ? function_ : functionBuilder_.build(); to_bitField0_ |= 0x00000001; } if (((from_bitField0_ & 0x00000004) != 0)) { result.functionId_ = functionId_; } 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.functions.v2.CreateFunctionRequest) { return mergeFrom((com.google.cloud.functions.v2.CreateFunctionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.functions.v2.CreateFunctionRequest other) { if (other == com.google.cloud.functions.v2.CreateFunctionRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (other.hasFunction()) { mergeFunction(other.getFunction()); } if (!other.getFunctionId().isEmpty()) { functionId_ = other.functionId_; 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(getFunctionFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000002; break; } // case 18 case 26: { functionId_ = 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 project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The project and location in which the function should be created, * specified in the format `projects/&#42;&#47;locations/&#42;` * </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.functions.v2.Function function_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.functions.v2.Function, com.google.cloud.functions.v2.Function.Builder, com.google.cloud.functions.v2.FunctionOrBuilder> functionBuilder_; /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the function field is set. */ public boolean hasFunction() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The function. */ public com.google.cloud.functions.v2.Function getFunction() { if (functionBuilder_ == null) { return function_ == null ? com.google.cloud.functions.v2.Function.getDefaultInstance() : function_; } else { return functionBuilder_.getMessage(); } } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setFunction(com.google.cloud.functions.v2.Function value) { if (functionBuilder_ == null) { if (value == null) { throw new NullPointerException(); } function_ = value; } else { functionBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setFunction(com.google.cloud.functions.v2.Function.Builder builderForValue) { if (functionBuilder_ == null) { function_ = builderForValue.build(); } else { functionBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeFunction(com.google.cloud.functions.v2.Function value) { if (functionBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && function_ != null && function_ != com.google.cloud.functions.v2.Function.getDefaultInstance()) { getFunctionBuilder().mergeFrom(value); } else { function_ = value; } } else { functionBuilder_.mergeFrom(value); } if (function_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearFunction() { bitField0_ = (bitField0_ & ~0x00000002); function_ = null; if (functionBuilder_ != null) { functionBuilder_.dispose(); functionBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.functions.v2.Function.Builder getFunctionBuilder() { bitField0_ |= 0x00000002; onChanged(); return getFunctionFieldBuilder().getBuilder(); } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.functions.v2.FunctionOrBuilder getFunctionOrBuilder() { if (functionBuilder_ != null) { return functionBuilder_.getMessageOrBuilder(); } else { return function_ == null ? com.google.cloud.functions.v2.Function.getDefaultInstance() : function_; } } /** * * * <pre> * Required. Function to be created. * </pre> * * <code> * .google.cloud.functions.v2.Function function = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.functions.v2.Function, com.google.cloud.functions.v2.Function.Builder, com.google.cloud.functions.v2.FunctionOrBuilder> getFunctionFieldBuilder() { if (functionBuilder_ == null) { functionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.functions.v2.Function, com.google.cloud.functions.v2.Function.Builder, com.google.cloud.functions.v2.FunctionOrBuilder>( getFunction(), getParentForChildren(), isClean()); function_ = null; } return functionBuilder_; } private java.lang.Object functionId_ = ""; /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @return The functionId. */ public java.lang.String getFunctionId() { java.lang.Object ref = functionId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); functionId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @return The bytes for functionId. */ public com.google.protobuf.ByteString getFunctionIdBytes() { java.lang.Object ref = functionId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); functionId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @param value The functionId to set. * @return This builder for chaining. */ public Builder setFunctionId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } functionId_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @return This builder for chaining. */ public Builder clearFunctionId() { functionId_ = getDefaultInstance().getFunctionId(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * The ID to use for the function, which will become the final component of * the function's resource name. * * This value should be 4-63 characters, and valid characters * are /[a-z][0-9]-/. * </pre> * * <code>string function_id = 3;</code> * * @param value The bytes for functionId to set. * @return This builder for chaining. */ public Builder setFunctionIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); functionId_ = 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.functions.v2.CreateFunctionRequest) } // @@protoc_insertion_point(class_scope:google.cloud.functions.v2.CreateFunctionRequest) private static final com.google.cloud.functions.v2.CreateFunctionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.functions.v2.CreateFunctionRequest(); } public static com.google.cloud.functions.v2.CreateFunctionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateFunctionRequest> PARSER = new com.google.protobuf.AbstractParser<CreateFunctionRequest>() { @java.lang.Override public CreateFunctionRequest 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<CreateFunctionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateFunctionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.functions.v2.CreateFunctionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,579
java-language/proto-google-cloud-language-v1/src/main/java/com/google/cloud/language/v1/AnalyzeEntitiesResponse.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 analysis response message. * </pre> * * Protobuf type {@code google.cloud.language.v1.AnalyzeEntitiesResponse} */ public final class AnalyzeEntitiesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.language.v1.AnalyzeEntitiesResponse) AnalyzeEntitiesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use AnalyzeEntitiesResponse.newBuilder() to construct. private AnalyzeEntitiesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AnalyzeEntitiesResponse() { entities_ = java.util.Collections.emptyList(); language_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new AnalyzeEntitiesResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitiesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitiesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.language.v1.AnalyzeEntitiesResponse.class, com.google.cloud.language.v1.AnalyzeEntitiesResponse.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. * </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. * </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. * </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. * </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. * </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.AnalyzeEntitiesResponse)) { return super.equals(obj); } com.google.cloud.language.v1.AnalyzeEntitiesResponse other = (com.google.cloud.language.v1.AnalyzeEntitiesResponse) 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.AnalyzeEntitiesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.language.v1.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.language.v1.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.language.v1.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.language.v1.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.language.v1.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse 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 analysis response message. * </pre> * * Protobuf type {@code google.cloud.language.v1.AnalyzeEntitiesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.language.v1.AnalyzeEntitiesResponse) com.google.cloud.language.v1.AnalyzeEntitiesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitiesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.language.v1.LanguageServiceProto .internal_static_google_cloud_language_v1_AnalyzeEntitiesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.language.v1.AnalyzeEntitiesResponse.class, com.google.cloud.language.v1.AnalyzeEntitiesResponse.Builder.class); } // Construct using com.google.cloud.language.v1.AnalyzeEntitiesResponse.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_AnalyzeEntitiesResponse_descriptor; } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitiesResponse getDefaultInstanceForType() { return com.google.cloud.language.v1.AnalyzeEntitiesResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitiesResponse build() { com.google.cloud.language.v1.AnalyzeEntitiesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitiesResponse buildPartial() { com.google.cloud.language.v1.AnalyzeEntitiesResponse result = new com.google.cloud.language.v1.AnalyzeEntitiesResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.language.v1.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse 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.AnalyzeEntitiesResponse) { return mergeFrom((com.google.cloud.language.v1.AnalyzeEntitiesResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.language.v1.AnalyzeEntitiesResponse other) { if (other == com.google.cloud.language.v1.AnalyzeEntitiesResponse.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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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. * </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.AnalyzeEntitiesResponse) } // @@protoc_insertion_point(class_scope:google.cloud.language.v1.AnalyzeEntitiesResponse) private static final com.google.cloud.language.v1.AnalyzeEntitiesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.language.v1.AnalyzeEntitiesResponse(); } public static com.google.cloud.language.v1.AnalyzeEntitiesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AnalyzeEntitiesResponse> PARSER = new com.google.protobuf.AbstractParser<AnalyzeEntitiesResponse>() { @java.lang.Override public AnalyzeEntitiesResponse 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<AnalyzeEntitiesResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AnalyzeEntitiesResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.language.v1.AnalyzeEntitiesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
36,769
jdk/src/share/classes/java/util/stream/IntStream.java
/* * Copyright (c) 2012, 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.util.stream; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.Objects; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.ObjIntConsumer; import java.util.function.Supplier; /** * A sequence of primitive int-valued elements supporting sequential and parallel * aggregate operations. This is the {@code int} primitive specialization of * {@link Stream}. * * <p>The following example illustrates an aggregate operation using * {@link Stream} and {@link IntStream}, computing the sum of the weights of the * red widgets: * * <pre>{@code * int sum = widgets.stream() * .filter(w -> w.getColor() == RED) * .mapToInt(w -> w.getWeight()) * .sum(); * }</pre> * * See the class documentation for {@link Stream} and the package documentation * for <a href="package-summary.html">java.util.stream</a> for additional * specification of streams, stream operations, stream pipelines, and * parallelism. * * @since 1.8 * @see Stream * @see <a href="package-summary.html">java.util.stream</a> */ public interface IntStream extends BaseStream<Integer, IntStream> { /** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to each element to determine if it * should be included * @return the new stream */ IntStream filter(IntPredicate predicate); /** * Returns a stream consisting of the results of applying the given * function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ IntStream map(IntUnaryOperator mapper); /** * Returns an object-valued {@code Stream} consisting of the results of * applying the given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps"> * intermediate operation</a>. * * @param <U> the element type of the new stream * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ <U> Stream<U> mapToObj(IntFunction<? extends U> mapper); /** * Returns a {@code LongStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ LongStream mapToLong(IntToLongFunction mapper); /** * Returns a {@code DoubleStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ DoubleStream mapToDouble(IntToDoubleFunction mapper); /** * Returns a stream consisting of the results of replacing each element of * this stream with the contents of a mapped stream produced by applying * the provided mapping function to each element. Each mapped stream is * {@link java.util.stream.BaseStream#close() closed} after its contents * have been placed into this stream. (If a mapped stream is {@code null} * an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces an * {@code IntStream} of new values * @return the new stream * @see Stream#flatMap(Function) */ IntStream flatMap(IntFunction<? extends IntStream> mapper); /** * Returns a stream consisting of the distinct elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the new stream */ IntStream distinct(); /** * Returns a stream consisting of the elements of this stream in sorted * order. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the new stream */ IntStream sorted(); /** * Returns a stream consisting of the elements of this stream, additionally * performing the provided action on each element as elements are consumed * from the resulting stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * <p>For parallel stream pipelines, the action may be called at * whatever time and in whatever thread the element is made available by the * upstream operation. If the action modifies shared state, * it is responsible for providing the required synchronization. * * @apiNote This method exists mainly to support debugging, where you want * to see the elements as they flow past a certain point in a pipeline: * <pre>{@code * IntStream.of(1, 2, 3, 4) * .filter(e -> e > 2) * .peek(e -> System.out.println("Filtered value: " + e)) * .map(e -> e * e) * .peek(e -> System.out.println("Mapped value: " + e)) * .sum(); * }</pre> * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements as * they are consumed from the stream * @return the new stream */ IntStream peek(IntConsumer action); /** * Returns a stream consisting of the elements of this stream, truncated * to be no longer than {@code maxSize} in length. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * stateful intermediate operation</a>. * * @apiNote * While {@code limit()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code maxSize}, since {@code limit(n)} * is constrained to return not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(IntSupplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code limit()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code limit()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. * * @param maxSize the number of elements the stream should be limited to * @return the new stream * @throws IllegalArgumentException if {@code maxSize} is negative */ IntStream limit(long maxSize); /** * Returns a stream consisting of the remaining elements of this stream * after discarding the first {@code n} elements of the stream. * If this stream contains fewer than {@code n} elements then an * empty stream will be returned. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @apiNote * While {@code skip()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code n}, since {@code skip(n)} * is constrained to skip not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(IntSupplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code skip()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code skip()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. * * @param n the number of leading elements to skip * @return the new stream * @throws IllegalArgumentException if {@code n} is negative */ IntStream skip(long n); /** * Performs an action for each element of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * <p>For parallel stream pipelines, this operation does <em>not</em> * guarantee to respect the encounter order of the stream, as doing so * would sacrifice the benefit of parallelism. For any given element, the * action may be performed at whatever time and in whatever thread the * library chooses. If the action accesses shared state, it is * responsible for providing the required synchronization. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements */ void forEach(IntConsumer action); /** * Performs an action for each element of this stream, guaranteeing that * each element is processed in encounter order for streams that have a * defined encounter order. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements * @see #forEach(IntConsumer) */ void forEachOrdered(IntConsumer action); /** * Returns an array containing the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an array containing the elements of this stream */ int[] toArray(); /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using the provided identity value and an * <a href="package-summary.html#Associativity">associative</a> * accumulation function, and returns the reduced value. This is equivalent * to: * <pre>{@code * int result = identity; * for (int element : this stream) * result = accumulator.applyAsInt(result, element) * return result; * }</pre> * * but is not constrained to execute sequentially. * * <p>The {@code identity} value must be an identity for the accumulator * function. This means that for all {@code x}, * {@code accumulator.apply(identity, x)} is equal to {@code x}. * The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @apiNote Sum, min, max, and average are all special cases of reduction. * Summing a stream of numbers can be expressed as: * * <pre>{@code * int sum = integers.reduce(0, (a, b) -> a+b); * }</pre> * * or more compactly: * * <pre>{@code * int sum = integers.reduce(0, Integer::sum); * }</pre> * * <p>While this may seem a more roundabout way to perform an aggregation * compared to simply mutating a running total in a loop, reduction * operations parallelize more gracefully, without needing additional * synchronization and with greatly reduced risk of data races. * * @param identity the identity value for the accumulating function * @param op an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * @return the result of the reduction * @see #sum() * @see #min() * @see #max() * @see #average() */ int reduce(int identity, IntBinaryOperator op); /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using an * <a href="package-summary.html#Associativity">associative</a> accumulation * function, and returns an {@code OptionalInt} describing the reduced value, * if any. This is equivalent to: * <pre>{@code * boolean foundAny = false; * int result = null; * for (int element : this stream) { * if (!foundAny) { * foundAny = true; * result = element; * } * else * result = accumulator.applyAsInt(result, element); * } * return foundAny ? OptionalInt.of(result) : OptionalInt.empty(); * }</pre> * * but is not constrained to execute sequentially. * * <p>The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param op an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * @return the result of the reduction * @see #reduce(int, IntBinaryOperator) */ OptionalInt reduce(IntBinaryOperator op); /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream. A mutable * reduction is one in which the reduced value is a mutable result container, * such as an {@code ArrayList}, and elements are incorporated by updating * the state of the result rather than by replacing the result. This * produces a result equivalent to: * <pre>{@code * R result = supplier.get(); * for (int element : this stream) * accumulator.accept(result, element); * return result; * }</pre> * * <p>Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations * can be parallelized without requiring additional synchronization. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param <R> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for incorporating an additional element into a result * @param combiner an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values, which must be * compatible with the accumulator function * @return the result of the reduction * @see Stream#collect(Supplier, BiConsumer, BiConsumer) */ <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner); /** * Returns the sum of elements in this stream. This is a special case * of a <a href="package-summary.html#Reduction">reduction</a> * and is equivalent to: * <pre>{@code * return reduce(0, Integer::sum); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return the sum of elements in this stream */ int sum(); /** * Returns an {@code OptionalInt} describing the minimum element of this * stream, or an empty optional if this stream is empty. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a> * and is equivalent to: * <pre>{@code * return reduce(Integer::min); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @return an {@code OptionalInt} containing the minimum element of this * stream, or an empty {@code OptionalInt} if the stream is empty */ OptionalInt min(); /** * Returns an {@code OptionalInt} describing the maximum element of this * stream, or an empty optional if this stream is empty. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a> * and is equivalent to: * <pre>{@code * return reduce(Integer::max); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code OptionalInt} containing the maximum element of this * stream, or an empty {@code OptionalInt} if the stream is empty */ OptionalInt max(); /** * Returns the count of elements in this stream. This is a special case of * a <a href="package-summary.html#Reduction">reduction</a> and is * equivalent to: * <pre>{@code * return mapToLong(e -> 1L).sum(); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @return the count of elements in this stream */ long count(); /** * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of * this stream, or an empty optional if this stream is empty. This is a * special case of a * <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code OptionalDouble} containing the average element of this * stream, or an empty optional if the stream is empty */ OptionalDouble average(); /** * Returns an {@code IntSummaryStatistics} describing various * summary data about the elements of this stream. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code IntSummaryStatistics} describing various summary data * about the elements of this stream */ IntSummaryStatistics summaryStatistics(); /** * Returns whether any elements of this stream match the provided * predicate. May not evaluate the predicate on all elements if not * necessary for determining the result. If the stream is empty then * {@code false} is returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>existential quantification</em> of the * predicate over the elements of the stream (for some x P(x)). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ boolean anyMatch(IntPredicate predicate); /** * Returns whether all elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>universal quantification</em> of the * predicate over the elements of the stream (for all x P(x)). If the * stream is empty, the quantification is said to be <em>vacuously * satisfied</em> and is always {@code true} (regardless of P(x)). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ boolean allMatch(IntPredicate predicate); /** * Returns whether no elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>universal quantification</em> of the * negated predicate over the elements of the stream (for all x ~P(x)). If * the stream is empty, the quantification is said to be vacuously satisfied * and is always {@code true}, regardless of P(x). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ boolean noneMatch(IntPredicate predicate); /** * Returns an {@link OptionalInt} describing the first element of this * stream, or an empty {@code OptionalInt} if the stream is empty. If the * stream has no encounter order, then any element may be returned. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @return an {@code OptionalInt} describing the first element of this stream, * or an empty {@code OptionalInt} if the stream is empty */ OptionalInt findFirst(); /** * Returns an {@link OptionalInt} describing some element of the stream, or * an empty {@code OptionalInt} if the stream is empty. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * <p>The behavior of this operation is explicitly nondeterministic; it is * free to select any element in the stream. This is to allow for maximal * performance in parallel operations; the cost is that multiple invocations * on the same source may not return the same result. (If a stable result * is desired, use {@link #findFirst()} instead.) * * @return an {@code OptionalInt} describing some element of this stream, or * an empty {@code OptionalInt} if the stream is empty * @see #findFirst() */ OptionalInt findAny(); /** * Returns a {@code LongStream} consisting of the elements of this stream, * converted to {@code long}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code LongStream} consisting of the elements of this stream, * converted to {@code long} */ LongStream asLongStream(); /** * Returns a {@code DoubleStream} consisting of the elements of this stream, * converted to {@code double}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code DoubleStream} consisting of the elements of this stream, * converted to {@code double} */ DoubleStream asDoubleStream(); /** * Returns a {@code Stream} consisting of the elements of this stream, * each boxed to an {@code Integer}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code Stream} consistent of the elements of this stream, * each boxed to an {@code Integer} */ Stream<Integer> boxed(); @Override IntStream sequential(); @Override IntStream parallel(); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); // Static factories /** * Returns a builder for an {@code IntStream}. * * @return a stream builder */ public static Builder builder() { return new Streams.IntStreamBuilderImpl(); } /** * Returns an empty sequential {@code IntStream}. * * @return an empty sequential stream */ public static IntStream empty() { return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false); } /** * Returns a sequential {@code IntStream} containing a single element. * * @param t the single element * @return a singleton sequential stream */ public static IntStream of(int t) { return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false); } /** * Returns a sequential ordered stream whose elements are the specified values. * * @param values the elements of the new stream * @return the new stream */ public static IntStream of(int... values) { return Arrays.stream(values); } /** * Returns an infinite sequential ordered {@code IntStream} produced by iterative * application of a function {@code f} to an initial element {@code seed}, * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, * {@code f(f(seed))}, etc. * * <p>The first element (position {@code 0}) in the {@code IntStream} will be * the provided {@code seed}. For {@code n > 0}, the element at position * {@code n}, will be the result of applying the function {@code f} to the * element at position {@code n - 1}. * * @param seed the initial element * @param f a function to be applied to to the previous element to produce * a new element * @return A new sequential {@code IntStream} */ public static IntStream iterate(final int seed, final IntUnaryOperator f) { Objects.requireNonNull(f); final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() { int t = seed; @Override public boolean hasNext() { return true; } @Override public int nextInt() { int v = t; t = f.applyAsInt(t); return v; } }; return StreamSupport.intStream(Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } /** * Returns an infinite sequential unordered stream where each element is * generated by the provided {@code IntSupplier}. This is suitable for * generating constant streams, streams of random elements, etc. * * @param s the {@code IntSupplier} for generated elements * @return a new infinite sequential unordered {@code IntStream} */ public static IntStream generate(IntSupplier s) { Objects.requireNonNull(s); return StreamSupport.intStream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false); } /** * Returns a sequential ordered {@code IntStream} from {@code startInclusive} * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of * {@code 1}. * * @apiNote * <p>An equivalent sequence of increasing values can be produced * sequentially using a {@code for} loop as follows: * <pre>{@code * for (int i = startInclusive; i < endExclusive ; i++) { ... } * }</pre> * * @param startInclusive the (inclusive) initial value * @param endExclusive the exclusive upper bound * @return a sequential {@code IntStream} for the range of {@code int} * elements */ public static IntStream range(int startInclusive, int endExclusive) { if (startInclusive >= endExclusive) { return empty(); } else { return StreamSupport.intStream( new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false); } } /** * Returns a sequential ordered {@code IntStream} from {@code startInclusive} * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of * {@code 1}. * * @apiNote * <p>An equivalent sequence of increasing values can be produced * sequentially using a {@code for} loop as follows: * <pre>{@code * for (int i = startInclusive; i <= endInclusive ; i++) { ... } * }</pre> * * @param startInclusive the (inclusive) initial value * @param endInclusive the inclusive upper bound * @return a sequential {@code IntStream} for the range of {@code int} * elements */ public static IntStream rangeClosed(int startInclusive, int endInclusive) { if (startInclusive > endInclusive) { return empty(); } else { return StreamSupport.intStream( new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false); } } /** * Creates a lazily concatenated stream whose elements are all the * elements of the first stream followed by all the elements of the * second stream. The resulting stream is ordered if both * of the input streams are ordered, and parallel if either of the input * streams is parallel. When the resulting stream is closed, the close * handlers for both input streams are invoked. * * @implNote * Use caution when constructing streams from repeated concatenation. * Accessing an element of a deeply concatenated stream can result in deep * call chains, or even {@code StackOverflowException}. * * @param a the first stream * @param b the second stream * @return the concatenation of the two input streams */ public static IntStream concat(IntStream a, IntStream b) { Objects.requireNonNull(a); Objects.requireNonNull(b); Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt( a.spliterator(), b.spliterator()); IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel()); return stream.onClose(Streams.composedClose(a, b)); } /** * A mutable builder for an {@code IntStream}. * * <p>A stream builder has a lifecycle, which starts in a building * phase, during which elements can be added, and then transitions to a built * phase, after which elements may not be added. The built phase * begins when the {@link #build()} method is called, which creates an * ordered stream whose elements are the elements that were added to the * stream builder, in the order they were added. * * @see IntStream#builder() * @since 1.8 */ public interface Builder extends IntConsumer { /** * Adds an element to the stream being built. * * @throws IllegalStateException if the builder has already transitioned * to the built state */ @Override void accept(int t); /** * Adds an element to the stream being built. * * @implSpec * The default implementation behaves as if: * <pre>{@code * accept(t) * return this; * }</pre> * * @param t the element to add * @return {@code this} builder * @throws IllegalStateException if the builder has already transitioned * to the built state */ default Builder add(int t) { accept(t); return this; } /** * Builds the stream, transitioning this builder to the built state. * An {@code IllegalStateException} is thrown if there are further * attempts to operate on the builder after it has entered the built * state. * * @return the built stream * @throws IllegalStateException if the builder has already transitioned to * the built state */ IntStream build(); } }
apache/hop
36,537
ui/src/main/java/org/apache/hop/ui/core/PropsUi.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.hop.ui.core; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.hop.core.Const; import org.apache.hop.core.Props; import org.apache.hop.core.gui.IGuiPosition; import org.apache.hop.core.gui.Point; import org.apache.hop.core.logging.LogChannel; import org.apache.hop.core.util.Utils; import org.apache.hop.history.AuditManager; import org.apache.hop.history.AuditState; import org.apache.hop.ui.core.gui.GuiResource; import org.apache.hop.ui.core.gui.WindowProperty; import org.apache.hop.ui.core.widget.OsHelper; import org.apache.hop.ui.hopgui.HopGui; import org.apache.hop.ui.hopgui.TextSizeUtilFacade; import org.apache.hop.ui.util.EnvironmentUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; /** * We use Props to store all kinds of user interactive information such as the selected colors, * fonts, positions of windows, etc. */ public class PropsUi extends Props { private static final String OS = System.getProperty("os.name").toLowerCase(); private static double nativeZoomFactor; private static final String STRING_SHOW_COPY_OR_DISTRIBUTE_WARNING = "ShowCopyOrDistributeWarning"; private static final String SHOW_TOOL_TIPS = "ShowToolTips"; private static final String RESOLVE_VARIABLES_IN_TOOLTIPS = "ResolveVariablesInToolTips"; private static final String SHOW_HELP_TOOL_TIPS = "ShowHelpToolTips"; private static final String HIDE_MENU_BAR = "HideMenuBar"; private static final String SORT_FIELD_BY_NAME = "SortFieldByName"; private static final String CANVAS_GRID_SIZE = "CanvasGridSize"; private static final String LEGACY_PERSPECTIVE_MODE = "LegacyPerspectiveMode"; private static final String DISABLE_BROWSER_ENVIRONMENT_CHECK = "DisableBrowserEnvironmentCheck"; private static final String USE_DOUBLE_CLICK_ON_CANVAS = "UseDoubleClickOnCanvas"; private static final String DRAW_BORDER_AROUND_CANVAS_NAMES = "DrawBorderAroundCanvasNames"; private static final String USE_GLOBAL_FILE_BOOKMARKS = "UseGlobalFileBookmarks"; private static final String DARK_MODE = "DarkMode"; private static final String GLOBAL_ZOOMFACTOR = "GlobalZoomFactor"; private static final String MAX_EXECUTION_LOGGING_TEXT_SIZE = "MaxExecutionLoggingTextSize"; private static final String GRAPH_EXTRA_VIEW_VERTICAL_ORIENTATION = "GraphExtraViewVerticalOrientation"; public static final int DEFAULT_MAX_EXECUTION_LOGGING_TEXT_SIZE = 2000000; private Map<RGB, RGB> contrastingColors; private static PropsUi instance; public static PropsUi getInstance() { if (instance == null) { instance = new PropsUi(); } return instance; } private PropsUi() { super(); // If the zoom factor is set with variable HOP_GUI_ZOOM_FACTOR we set this first. // String hopGuiZoomFactor = System.getProperty(ConstUi.HOP_GUI_ZOOM_FACTOR); if (StringUtils.isNotEmpty(hopGuiZoomFactor)) { setProperty(GLOBAL_ZOOMFACTOR, hopGuiZoomFactor); } reCalculateNativeZoomFactor(); setDefault(); } /** * Re-calculate the static native zoom factor. Do not make this method static because Sonar * recommends it. */ public void reCalculateNativeZoomFactor() { double globalZoom = getGlobalZoomFactor(); if (EnvironmentUtils.getInstance().isWeb()) { nativeZoomFactor = globalZoom / 0.75; } else { // Calculate the native default zoom factor... // We take the default font and render it, calculate the height. // Compare that to the standard small icon size of 16 // org.eclipse.swt.graphics.Point extent = TextSizeUtilFacade.textExtent("The quick brown fox jumped over the lazy dog!"); nativeZoomFactor = (extent.y / (double) ConstUi.SMALL_ICON_SIZE) * globalZoom; } } @Override public void setDefault() { super.setDefault(); Display display = Display.getCurrent(); populateContrastingColors(); // Only set OS look shown once in case we switch to dark mode // and vice versa. We don't want to override user choices all the time. // If we do it like before it becomes impossible to choose your own font and colors. // if (!EnvironmentUtils.getInstance().isWeb() && !OsHelper.isWindows()) { if (Display.isSystemDarkTheme()) { if (!isDarkMode()) { setDarkMode(true); } } else { if (isDarkMode()) { setDarkMode(false); } } } // Various tweaks to improve dark theme experience on Windows if (OsHelper.isWindows() && isDarkMode()) { display.setData("org.eclipse.swt.internal.win32.useDarkModeExplorerTheme", true); display.setData("org.eclipse.swt.internal.win32.useShellTitleColoring", true); display.setData( "org.eclipse.swt.internal.win32.menuBarForegroundColor", new Color(display, 0xD0, 0xD0, 0xD0)); display.setData( "org.eclipse.swt.internal.win32.menuBarBackgroundColor", new Color(display, 0x30, 0x30, 0x30)); display.setData( "org.eclipse.swt.internal.win32.menuBarBorderColor", new Color(display, 0x50, 0x50, 0x50)); display.setData("org.eclipse.swt.internal.win32.all.use_WS_BORDER", true); display.setData( "org.eclipse.swt.internal.win32.Table.headerLineColor", new Color(display, 0x50, 0x50, 0x50)); display.setData( "org.eclipse.swt.internal.win32.Label.disabledForegroundColor", new Color(display, 0x80, 0x80, 0x80)); display.setData("org.eclipse.swt.internal.win32.Combo.useDarkTheme", true); display.setData( "org.eclipse.swt.internal.win32.ToolBar.backgroundColor", new Color(display, 0xD0, 0xD0, 0xD0)); display.setData( "org.eclipse.swt.internal.win32.Combo.backgroundColor", new Color(display, 0xD0, 0xD0, 0xD0)); display.setData("org.eclipse.swt.internal.win32.ProgressBar.useColors", true); } if (display != null) { FontData fontData = getDefaultFont(); setProperty(STRING_FONT_DEFAULT_NAME, fontData.getName()); setProperty(STRING_FONT_DEFAULT_SIZE, "" + fontData.getHeight()); setProperty(STRING_FONT_DEFAULT_STYLE, "" + fontData.getStyle()); fontData = getFixedFont(); setProperty(STRING_FONT_FIXED_NAME, fontData.getName()); setProperty(STRING_FONT_FIXED_SIZE, "" + fontData.getHeight()); setProperty(STRING_FONT_FIXED_STYLE, "" + fontData.getStyle()); fontData = getGraphFont(); setProperty(STRING_FONT_GRAPH_NAME, fontData.getName()); setProperty(STRING_FONT_GRAPH_SIZE, "" + fontData.getHeight()); setProperty(STRING_FONT_GRAPH_STYLE, "" + fontData.getStyle()); fontData = getNoteFont(); setProperty(STRING_FONT_NOTE_NAME, fontData.getName()); setProperty(STRING_FONT_NOTE_SIZE, "" + fontData.getHeight()); setProperty(STRING_FONT_NOTE_STYLE, "" + fontData.getStyle()); setProperty(STRING_ICON_SIZE, "" + getIconSize()); setProperty(STRING_LINE_WIDTH, "" + getLineWidth()); setProperty(STRING_MAX_UNDO, "" + getMaxUndo()); } } public void setFixedFont(FontData fd) { setProperty(STRING_FONT_FIXED_NAME, fd.getName()); setProperty(STRING_FONT_FIXED_SIZE, "" + fd.getHeight()); setProperty(STRING_FONT_FIXED_STYLE, "" + fd.getStyle()); } public FontData getFixedFont() { FontData def = getDefaultFontData(); String name = getProperty(STRING_FONT_FIXED_NAME); if (StringUtils.isEmpty(name)) { if (Const.isWindows()) { name = "Consolas"; } else if (Const.isLinux()) { name = "Monospace"; } else if (Const.isOSX()) { name = "Monaco"; } else if (EnvironmentUtils.getInstance().isWeb()) { name = "monospace"; } else { name = java.awt.Font.MONOSPACED; } } int size = Const.toInt(getProperty(STRING_FONT_FIXED_SIZE), def.getHeight()); int style = Const.toInt(getProperty(STRING_FONT_FIXED_STYLE), def.getStyle()); return new FontData(name, size, style); } public FontData getDefaultFont() { FontData def = getDefaultFontData(); String name = getProperty(STRING_FONT_DEFAULT_NAME, def.getName()); int size = Const.toInt(getProperty(STRING_FONT_DEFAULT_SIZE), def.getHeight()); int style = Const.toInt(getProperty(STRING_FONT_DEFAULT_STYLE), def.getStyle()); return new FontData(name, size, style); } public void setDefaultFont(FontData fd) { setProperty(STRING_FONT_DEFAULT_NAME, fd.getName()); setProperty(STRING_FONT_DEFAULT_SIZE, "" + fd.getHeight()); setProperty(STRING_FONT_DEFAULT_STYLE, "" + fd.getStyle()); } public void setGraphFont(FontData fd) { setProperty(STRING_FONT_GRAPH_NAME, fd.getName()); setProperty(STRING_FONT_GRAPH_SIZE, "" + fd.getHeight()); setProperty(STRING_FONT_GRAPH_STYLE, "" + fd.getStyle()); } public FontData getGraphFont() { FontData def = getDefaultFontData(); String name = getProperty(STRING_FONT_GRAPH_NAME, def.getName()); int size = Const.toInt(getProperty(STRING_FONT_GRAPH_SIZE), def.getHeight()); int style = Const.toInt(getProperty(STRING_FONT_GRAPH_STYLE), def.getStyle()); return new FontData(name, size, style); } public void setNoteFont(FontData fd) { setProperty(STRING_FONT_NOTE_NAME, fd.getName()); setProperty(STRING_FONT_NOTE_SIZE, "" + fd.getHeight()); setProperty(STRING_FONT_NOTE_STYLE, "" + fd.getStyle()); } public FontData getNoteFont() { FontData def = getDefaultFontData(); String name = getProperty(STRING_FONT_NOTE_NAME, def.getName()); int size = Const.toInt(getProperty(STRING_FONT_NOTE_SIZE), def.getHeight()); int style = Const.toInt(getProperty(STRING_FONT_NOTE_STYLE), def.getStyle()); return new FontData(name, size, style); } public void setIconSize(int size) { setProperty(STRING_ICON_SIZE, "" + size); } public int getIconSize() { return Const.toInt(getProperty(STRING_ICON_SIZE), ConstUi.ICON_SIZE); } public void setZoomFactor(double factor) { setProperty(STRING_ZOOM_FACTOR, Double.toString(factor)); } public double getZoomFactor() { return getNativeZoomFactor(); } /** * Get the margin compensated for the zoom factor * * @return */ /** The margin between the different dialog components &amp; widgets */ public static int getMargin() { return (int) Math.round(4 * getNativeZoomFactor()); } public void setLineWidth(int width) { setProperty(STRING_LINE_WIDTH, "" + width); } public int getLineWidth() { return Const.toInt(getProperty(STRING_LINE_WIDTH), ConstUi.LINE_WIDTH); } public void setLastPreview(String[] lastpreview, int[] transformsize) { setProperty(STRING_LAST_PREVIEW_TRANSFORM, "" + lastpreview.length); for (int i = 0; i < lastpreview.length; i++) { setProperty(STRING_LAST_PREVIEW_TRANSFORM + (i + 1), lastpreview[i]); setProperty(STRING_LAST_PREVIEW_SIZE + (i + 1), "" + transformsize[i]); } } public String[] getLastPreview() { String snr = getProperty(STRING_LAST_PREVIEW_TRANSFORM); int nr = Const.toInt(snr, 0); String[] lp = new String[nr]; for (int i = 0; i < nr; i++) { lp[i] = getProperty(STRING_LAST_PREVIEW_TRANSFORM + (i + 1), ""); } return lp; } public int[] getLastPreviewSize() { String snr = getProperty(STRING_LAST_PREVIEW_TRANSFORM); int nr = Const.toInt(snr, 0); int[] si = new int[nr]; for (int i = 0; i < nr; i++) { si[i] = Const.toInt(getProperty(STRING_LAST_PREVIEW_SIZE + (i + 1), ""), 0); } return si; } public FontData getDefaultFontData() { return Display.getCurrent().getSystemFont().getFontData()[0]; } public void setMaxUndo(int max) { setProperty(STRING_MAX_UNDO, "" + max); } public int getMaxUndo() { return Const.toInt(getProperty(STRING_MAX_UNDO), Const.MAX_UNDO); } public void setMiddlePct(int pct) { setProperty(STRING_MIDDLE_PCT, "" + pct); } /** The percentage of the width of screen where we consider the middle of a dialog. */ public int getMiddlePct() { return Const.toInt(getProperty(STRING_MIDDLE_PCT), 35); } /** The horizontal and vertical margin of a dialog box. */ public static int getFormMargin() { return (int) Math.round(5 * getNativeZoomFactor()); } public void setScreen(WindowProperty windowProperty) { AuditManager.storeState( LogChannel.UI, HopGui.DEFAULT_HOP_GUI_NAMESPACE, "shells", windowProperty.getName(), windowProperty.getStateProperties()); } public WindowProperty getScreen(String windowName) { if (windowName == null) { return null; } AuditState auditState = AuditManager.retrieveState( LogChannel.UI, HopGui.DEFAULT_HOP_GUI_NAMESPACE, "shells", windowName); if (auditState == null) { return null; } return new WindowProperty(windowName, auditState.getStateMap()); } public void setOpenLastFile(boolean open) { setProperty(STRING_OPEN_LAST_FILE, open ? YES : NO); } public boolean openLastFile() { String open = getProperty(STRING_OPEN_LAST_FILE); return !NO.equalsIgnoreCase(open); } public void setAutoSave(boolean autosave) { setProperty(STRING_AUTO_SAVE, autosave ? YES : NO); } public boolean getAutoSave() { String autosave = getProperty(STRING_AUTO_SAVE); return YES.equalsIgnoreCase(autosave); // Default = OFF } public void setSaveConfirmation(boolean saveconf) { setProperty(STRING_SAVE_CONF, saveconf ? YES : NO); } public boolean getSaveConfirmation() { String saveconf = getProperty(STRING_SAVE_CONF); return YES.equalsIgnoreCase(saveconf); // Default = OFF } public boolean isGraphExtraViewVerticalOrientation() { String vertical = this.getProperty(GRAPH_EXTRA_VIEW_VERTICAL_ORIENTATION); return YES.equalsIgnoreCase(vertical); } /** Set true for vertical orientation */ public void setGraphExtraViewVerticalOrientation(boolean vertical) { setProperty(GRAPH_EXTRA_VIEW_VERTICAL_ORIENTATION, vertical ? YES : NO); } public void setAutoSplit(boolean autosplit) { setProperty(STRING_AUTO_SPLIT, autosplit ? YES : NO); } public boolean getAutoSplit() { String autosplit = getProperty(STRING_AUTO_SPLIT); return YES.equalsIgnoreCase(autosplit); // Default = OFF } public void setExitWarningShown(boolean show) { setProperty(STRING_SHOW_EXIT_WARNING, show ? YES : NO); } public boolean isShowCanvasGridEnabled() { String showCanvas = getProperty(STRING_SHOW_CANVAS_GRID, NO); return YES.equalsIgnoreCase(showCanvas); // Default: don't show canvas grid } public void setShowCanvasGridEnabled(boolean anti) { setProperty(STRING_SHOW_CANVAS_GRID, anti ? YES : NO); } public boolean isHideViewportEnabled() { String showViewport = getProperty(STRING_HIDE_VIEWPORT, NO); return YES.equalsIgnoreCase(showViewport); // Default: don't hide the viewport } public void setHideViewportEnabled(boolean anti) { setProperty(STRING_HIDE_VIEWPORT, anti ? YES : NO); } public boolean showExitWarning() { String show = getProperty(STRING_SHOW_EXIT_WARNING, YES); return YES.equalsIgnoreCase(show); // Default: show repositories dialog at startup } public boolean isShowTableViewToolbar() { String show = getProperty(STRING_SHOW_TABLE_VIEW_TOOLBAR, YES); return YES.equalsIgnoreCase(show); // Default: show the toolbar } public void setShowTableViewToolbar(boolean show) { setProperty(STRING_SHOW_TABLE_VIEW_TOOLBAR, show ? YES : NO); } public static void setLook(Widget widget) { int style = WIDGET_STYLE_DEFAULT; if (widget instanceof Table) { style = WIDGET_STYLE_TABLE; } else if (widget instanceof Tree) { style = WIDGET_STYLE_TREE; } else if (widget instanceof ToolBar) { style = WIDGET_STYLE_TOOLBAR; } else if (widget instanceof CTabFolder) { style = WIDGET_STYLE_TAB; } else if (OS.contains("mac") && (widget instanceof Group)) { style = WIDGET_STYLE_OSX_GROUP; } else if (widget instanceof Button) { if (Const.isWindows() && ((widget.getStyle() & (SWT.CHECK | SWT.RADIO)) != 0)) { style = WIDGET_STYLE_DEFAULT; } else { style = WIDGET_STYLE_PUSH_BUTTON; } } setLook(widget, style); if (widget instanceof Composite compositeWidget) { Composite composite = compositeWidget; for (Control child : composite.getChildren()) { setLook(child); } } } public static void setLook(final Widget widget, int style) { if (OsHelper.isWindows()) { setLookOnWindows(widget, style); } else if (OsHelper.isMac()) { setLookOnMac(widget, style); } else { setLookOnLinux(widget, style); } } protected static void setLookOnWindows(final Widget widget, int style) { final GuiResource gui = GuiResource.getInstance(); Font font = gui.getFontDefault(); Color background = null; Color foreground = null; if (widget instanceof Shell shellWidget) { background = gui.getColorWhite(); foreground = gui.getColorBlack(); Shell shell = shellWidget; shell.setBackgroundMode(SWT.INHERIT_FORCE); shell.setForeground(gui.getColorBlack()); shell.setBackground(gui.getColorWhite()); return; } switch (style) { case WIDGET_STYLE_DEFAULT: background = gui.getColorWhite(); foreground = gui.getColorBlack(); break; case WIDGET_STYLE_FIXED: font = gui.getFontFixed(); background = gui.getColorWhite(); foreground = gui.getColorBlack(); break; case WIDGET_STYLE_TABLE: if (PropsUi.getInstance().isDarkMode()) { background = gui.getColorWhite(); foreground = gui.getColorBlack(); Table table = (Table) widget; table.setHeaderBackground(gui.getColorLightGray()); table.setHeaderForeground(gui.getColorDarkGray()); } break; case WIDGET_STYLE_TREE: if (PropsUi.getInstance().isDarkMode()) { background = gui.getColorWhite(); foreground = gui.getColorBlack(); Tree tree = (Tree) widget; tree.setHeaderBackground(gui.getColorLightGray()); tree.setHeaderForeground(gui.getColorDarkGray()); } break; case WIDGET_STYLE_TOOLBAR: if (PropsUi.getInstance().isDarkMode()) { background = gui.getColorLightGray(); foreground = gui.getColorBlack(); } break; case WIDGET_STYLE_TAB: CTabFolder tabFolder = (CTabFolder) widget; tabFolder.setBorderVisible(true); tabFolder.setTabHeight(28); if (PropsUi.getInstance().isDarkMode()) { tabFolder.setBackground(gui.getColorWhite()); tabFolder.setForeground(gui.getColorBlack()); tabFolder.setSelectionBackground(gui.getColorWhite()); tabFolder.setSelectionForeground(gui.getColorBlack()); } break; case WIDGET_STYLE_PUSH_BUTTON: break; default: background = gui.getColorGray(); font = null; break; } if (font != null && !font.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setFont(font); } if (background != null && !background.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setBackground(background); } if (foreground != null && !foreground.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setForeground(foreground); } } protected static void setLookOnMac(final Widget widget, int style) { final GuiResource gui = GuiResource.getInstance(); Font font = gui.getFontDefault(); Color background = gui.getColorWhite(); Color foreground = gui.getColorBlack(); switch (style) { case WIDGET_STYLE_DEFAULT: break; case WIDGET_STYLE_OSX_GROUP: background = gui.getColorWhite(); foreground = gui.getColorBlack(); font = gui.getFontDefault(); Group group = ((Group) widget); group.addPaintListener( paintEvent -> { paintEvent.gc.setForeground(gui.getColorBlack()); paintEvent.gc.setBackground(gui.getColorWhite()); paintEvent.gc.fillRectangle( 2, 0, group.getBounds().width - 8, group.getBounds().height - 20); }); break; case WIDGET_STYLE_FIXED: font = gui.getFontFixed(); break; case WIDGET_STYLE_TABLE: background = gui.getColorLightGray(); foreground = gui.getColorDarkGray(); Table table = (Table) widget; table.setHeaderBackground(gui.getColorLightGray()); table.setHeaderForeground(gui.getColorDarkGray()); break; case WIDGET_STYLE_TREE: // TODO: Adjust for Linux break; case WIDGET_STYLE_TOOLBAR: if (PropsUi.getInstance().isDarkMode()) { background = gui.getColorLightGray(); } else { background = gui.getColorDemoGray(); } break; case WIDGET_STYLE_TAB: CTabFolder tabFolder = (CTabFolder) widget; tabFolder.setBorderVisible(true); tabFolder.setBackground(gui.getColorGray()); tabFolder.setForeground(gui.getColorBlack()); tabFolder.setSelectionBackground(gui.getColorWhite()); tabFolder.setSelectionForeground(gui.getColorBlack()); break; case WIDGET_STYLE_PUSH_BUTTON: background = null; foreground = null; break; default: background = gui.getColorBackground(); font = null; break; } if (font != null && !font.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setFont(font); } if (background != null && !background.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setBackground(background); } if (foreground != null && !foreground.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setForeground(foreground); } if (widget instanceof Combo combo) { combo.setBackground(gui.getColorWhite()); } } protected static void setLookOnLinux(final Widget widget, int style) { final GuiResource gui = GuiResource.getInstance(); Font font = gui.getFontDefault(); Color background = gui.getColorWhite(); Color foreground = gui.getColorBlack(); switch (style) { case WIDGET_STYLE_DEFAULT: break; case WIDGET_STYLE_OSX_GROUP: // TODO: Adjust for Linux break; case WIDGET_STYLE_FIXED: font = gui.getFontFixed(); break; case WIDGET_STYLE_TABLE: background = gui.getColorLightGray(); foreground = gui.getColorDarkGray(); Table table = (Table) widget; table.setHeaderBackground(gui.getColorLightGray()); table.setHeaderForeground(gui.getColorDarkGray()); break; case WIDGET_STYLE_TREE: // TODO: Adjust for Linux break; case WIDGET_STYLE_TOOLBAR: if (PropsUi.getInstance().isDarkMode()) { background = gui.getColorLightGray(); } else { background = gui.getColorDemoGray(); } break; case WIDGET_STYLE_TAB: CTabFolder tabFolder = (CTabFolder) widget; tabFolder.setBorderVisible(true); tabFolder.setBackground(gui.getColorGray()); tabFolder.setForeground(gui.getColorBlack()); tabFolder.setSelectionBackground(gui.getColorWhite()); tabFolder.setSelectionForeground(gui.getColorBlack()); break; case WIDGET_STYLE_PUSH_BUTTON: background = null; foreground = null; break; default: background = gui.getColorBackground(); font = null; break; } if (font != null && !font.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setFont(font); } if (background != null && !background.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setBackground(background); } if (foreground != null && !foreground.isDisposed() && (widget instanceof Control controlWidget)) { controlWidget.setForeground(foreground); } } /** * @return Returns the display. */ public static Display getDisplay() { return Display.getCurrent(); } public void setDefaultPreviewSize(int size) { setProperty(STRING_DEFAULT_PREVIEW_SIZE, "" + size); } public int getDefaultPreviewSize() { return Const.toInt(getProperty(STRING_DEFAULT_PREVIEW_SIZE), 1000); } public boolean showCopyOrDistributeWarning() { String show = getProperty(STRING_SHOW_COPY_OR_DISTRIBUTE_WARNING, YES); return YES.equalsIgnoreCase(show); } public void setShowCopyOrDistributeWarning(boolean show) { setProperty(STRING_SHOW_COPY_OR_DISTRIBUTE_WARNING, show ? YES : NO); } public void setDialogSize(Shell shell, String styleProperty) { String prop = getProperty(styleProperty); if (Utils.isEmpty(prop)) { return; } String[] xy = prop.split(","); if (xy.length != 2) { return; } shell.setSize(Integer.parseInt(xy[0]), Integer.parseInt(xy[1])); } public boolean useDoubleClick() { return YES.equalsIgnoreCase(getProperty(USE_DOUBLE_CLICK_ON_CANVAS, NO)); } public void setUseDoubleClickOnCanvas(boolean use) { setProperty(USE_DOUBLE_CLICK_ON_CANVAS, use ? YES : NO); } public boolean isBorderDrawnAroundCanvasNames() { return YES.equalsIgnoreCase(getProperty(DRAW_BORDER_AROUND_CANVAS_NAMES, NO)); } public void setDrawBorderAroundCanvasNames(boolean draw) { setProperty(DRAW_BORDER_AROUND_CANVAS_NAMES, draw ? YES : NO); } public boolean useGlobalFileBookmarks() { return YES.equalsIgnoreCase(getProperty(USE_GLOBAL_FILE_BOOKMARKS, YES)); } public void setUseGlobalFileBookmarks(boolean use) { setProperty(USE_GLOBAL_FILE_BOOKMARKS, use ? YES : NO); } public boolean isDarkMode() { return YES.equalsIgnoreCase(getProperty(DARK_MODE, NO)); } public void setDarkMode(boolean darkMode) { setProperty(DARK_MODE, darkMode ? YES : NO); } public boolean showToolTips() { return YES.equalsIgnoreCase(getProperty(SHOW_TOOL_TIPS, YES)); } public void setShowToolTips(boolean show) { setProperty(SHOW_TOOL_TIPS, show ? YES : NO); } public boolean resolveVariablesInToolTips() { return YES.equalsIgnoreCase(getProperty(RESOLVE_VARIABLES_IN_TOOLTIPS, YES)); } public void setResolveVariablesInToolTips(boolean resolve) { setProperty(RESOLVE_VARIABLES_IN_TOOLTIPS, resolve ? YES : NO); } public boolean isShowingHelpToolTips() { return YES.equalsIgnoreCase(getProperty(SHOW_HELP_TOOL_TIPS, YES)); } public void setHidingMenuBar(boolean show) { setProperty(HIDE_MENU_BAR, show ? YES : NO); } public boolean isHidingMenuBar() { return YES.equalsIgnoreCase( System.getProperty(ConstUi.HOP_GUI_HIDE_MENU, getProperty(HIDE_MENU_BAR, YES))); } public void setSortFieldByName(boolean sort) { setProperty(SORT_FIELD_BY_NAME, sort ? YES : NO); } public boolean isSortFieldByName() { return YES.equalsIgnoreCase( System.getProperty(SORT_FIELD_BY_NAME, getProperty(SORT_FIELD_BY_NAME, YES))); } public void setShowingHelpToolTips(boolean show) { setProperty(SHOW_HELP_TOOL_TIPS, show ? YES : NO); } public int getCanvasGridSize() { return Const.toInt(getProperty(CANVAS_GRID_SIZE, "16"), 16); } public void setCanvasGridSize(int gridSize) { setProperty(CANVAS_GRID_SIZE, Integer.toString(gridSize)); } /** * Gets the supported version of the requested software. * * @param property the key for the software version * @return an integer that represents the supported version for the software. */ public int getSupportedVersion(String property) { return Integer.parseInt(getProperty(property)); } /** * Ask if the browsing environment checks are disabled. * * @return 'true' if disabled 'false' otherwise. */ public boolean isBrowserEnvironmentCheckDisabled() { return "Y".equalsIgnoreCase(getProperty(DISABLE_BROWSER_ENVIRONMENT_CHECK, "N")); } public boolean isLegacyPerspectiveMode() { return "Y".equalsIgnoreCase(getProperty(LEGACY_PERSPECTIVE_MODE, "N")); } public static void setLocation(IGuiPosition guiElement, int x, int y) { if (x < 0) { x = 0; } if (y < 0) { y = 0; } guiElement.setLocation(calculateGridPosition(new Point(x, y))); } public static Point calculateGridPosition(Point p) { int gridSize = PropsUi.getInstance().getCanvasGridSize(); if (gridSize > 1) { // Snap to grid... // return new Point( gridSize * Math.round((float) p.x / gridSize), gridSize * Math.round((float) p.y / gridSize)); } else { // Normal draw // return p; } } public boolean isIndicateSlowPipelineTransformsEnabled() { String indicate = getProperty(STRING_INDICATE_SLOW_PIPELINE_TRANSFORMS, "Y"); return YES.equalsIgnoreCase(indicate); } public void setIndicateSlowPipelineTransformsEnabled(boolean indicate) { setProperty(STRING_INDICATE_SLOW_PIPELINE_TRANSFORMS, indicate ? YES : NO); } /** * Gets nativeZoomFactor * * @return value of nativeZoomFactor */ public static double getNativeZoomFactor() { return nativeZoomFactor; } /** * @param nativeZoomFactor The nativeZoomFactor to set */ public static void setNativeZoomFactor(double nativeZoomFactor) { PropsUi.nativeZoomFactor = nativeZoomFactor; } private void populateContrastingColors() { contrastingColors = new HashMap<>(); contrastingColors.put(toRGB("#000000"), toRGB("#ffffff")); contrastingColors.put(toRGB("#0e3a5a"), toRGB("#c8e7fa")); contrastingColors.put(toRGB("#0f3b5a"), toRGB("#c7e6fa")); contrastingColors.put(toRGB("#f0f0f0"), toRGB("#0f0f0f")); contrastingColors.put(toRGB("#e1e1e1"), toRGB("#303030")); contrastingColors.put(toRGB("#646464"), toRGB("#707070")); contrastingColors.put(toRGB("#ffd700"), toRGB("#0028ff")); // brighten workflow logo color by 50% contrastingColors.put(toRGB("#033d5d"), toRGB("#36b3f8")); // Darken yellow in JS transform by 75% contrastingColors.put(toRGB("#eeffaa"), toRGB("#556a00")); // Darken light blue by 50% // contrastingColors.put(toRGB("#c9e8fb"), toRGB("#0f88d2")); contrastingColors.put(new RGB(254, 254, 254), new RGB(35, 35, 35)); contrastingColors.put(new RGB(245, 245, 245), new RGB(40, 40, 40)); contrastingColors.put(new RGB(240, 240, 240), new RGB(45, 45, 45)); contrastingColors.put(new RGB(235, 235, 235), new RGB(50, 50, 50)); contrastingColors.put(new RGB(225, 225, 225), new RGB(70, 70, 70)); contrastingColors.put(new RGB(215, 215, 215), new RGB(100, 100, 100)); contrastingColors.put(new RGB(100, 100, 100), new RGB(215, 215, 215)); contrastingColors.put(new RGB(50, 50, 50), new RGB(235, 235, 235)); // Add all the inverse color mappings as well // Map<RGB, RGB> inverse = new HashMap<>(); contrastingColors.keySet().stream() .forEach(key -> inverse.put(contrastingColors.get(key), key)); contrastingColors.putAll(inverse); } private RGB toRGB(String colorString) { int red = Integer.valueOf(colorString.substring(1, 3), 16); int green = Integer.valueOf(colorString.substring(3, 5), 16); int blue = Integer.valueOf(colorString.substring(5, 7), 16); return new RGB(red, green, blue); } /** * @param rgb the color to contrast if the system is in "Dark Mode" * @return The contrasted color */ public RGB contrastColor(RGB rgb) { if (PropsUi.getInstance().isDarkMode()) { RGB contrastingRGB = contrastingColors.get(rgb); if (contrastingRGB != null) { return contrastingRGB; } } return rgb; } public RGB contrastColor(int r, int g, int b) { return contrastColor(new RGB(r, g, b)); } public Map<String, String> getContrastingColorStrings() { Map<String, String> map = new HashMap<>(); for (Map.Entry<RGB, RGB> entry : contrastingColors.entrySet()) { RGB rgb = entry.getKey(); RGB contrastingRGB = entry.getValue(); String fromColor = toColorString(rgb); String toColor = toColorString(contrastingRGB); // Lowercase & uppercase // map.put(fromColor.toLowerCase(), toColor); map.put(fromColor.toUpperCase(), toColor); } return map; } private String toColorString(RGB rgb) { String r = Integer.toString(rgb.red, 16); r = r.length() == 1 ? "0" + r : r; String g = Integer.toString(rgb.green, 16); g = g.length() == 1 ? "0" + g : g; String b = Integer.toString(rgb.blue, 16); b = b.length() == 1 ? "0" + b : b; return ("#" + r + g + b).toLowerCase(); } /** * Gets contrastingColors * * @return value of contrastingColors */ public Map<RGB, RGB> getContrastingColors() { return contrastingColors; } /** * @param contrastingColors The contrastingColors to set */ public void setContrastingColors(Map<RGB, RGB> contrastingColors) { this.contrastingColors = contrastingColors; } public double getGlobalZoomFactor() { return Const.toDouble(getProperty(GLOBAL_ZOOMFACTOR, "1.0"), 1.0); } public void setGlobalZoomFactor(double globalZoomFactor) { setProperty(GLOBAL_ZOOMFACTOR, Double.toString(globalZoomFactor)); } public int getMaxExecutionLoggingTextSize() { return Const.toInt( getProperty( MAX_EXECUTION_LOGGING_TEXT_SIZE, Integer.toString(DEFAULT_MAX_EXECUTION_LOGGING_TEXT_SIZE)), DEFAULT_MAX_EXECUTION_LOGGING_TEXT_SIZE); } public void setMaxExecutionLoggingTextSize(int maxExecutionLoggingTextSize) { setProperty(MAX_EXECUTION_LOGGING_TEXT_SIZE, Integer.toString(maxExecutionLoggingTextSize)); } protected static final String[] globalZoomFactorLevels = new String[] { "200%", "175%", "150%", "140%", "130%", "120%", "110%", "100%", "90%", "80%", "70%" }; public static final String[] getGlobalZoomFactorLevels() { return globalZoomFactorLevels; } public Layout createFormLayout() { FormLayout formLayout = new FormLayout(); formLayout.marginLeft = getFormMargin(); formLayout.marginTop = getFormMargin(); formLayout.marginBottom = getFormMargin(); formLayout.marginRight = getFormMargin(); return formLayout; } }
apache/tomcat
36,143
test/org/apache/jasper/compiler/TestGenerator.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.jasper.compiler; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.beans.PropertyEditorSupport; import java.io.File; import java.io.IOException; import java.nio.charset.CodingErrorAction; import java.util.Date; import java.util.Scanner; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.jsp.JspException; import jakarta.servlet.jsp.PageContext; import jakarta.servlet.jsp.tagext.BodyTagSupport; import jakarta.servlet.jsp.tagext.DynamicAttributes; import jakarta.servlet.jsp.tagext.JspIdConsumer; import jakarta.servlet.jsp.tagext.Tag; import jakarta.servlet.jsp.tagext.TagData; import jakarta.servlet.jsp.tagext.TagExtraInfo; import jakarta.servlet.jsp.tagext.TagSupport; import jakarta.servlet.jsp.tagext.TryCatchFinally; import jakarta.servlet.jsp.tagext.VariableInfo; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.LifecycleException; import org.apache.catalina.Wrapper; 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; public class TestGenerator extends TomcatBaseTest { private static final String NEW_LINE = System.lineSeparator(); @Test public void testBug45015a() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk res = getUrl("http://localhost:" + getPort() + "/test/bug45nnn/bug45015a.jsp"); String result = res.toString(); // Beware of the differences between escaping in JSP attributes and // in Java Strings assertEcho(result, "00-hello 'world'"); assertEcho(result, "01-hello 'world"); assertEcho(result, "02-hello world'"); assertEcho(result, "03-hello world'"); assertEcho(result, "04-hello world\""); assertEcho(result, "05-hello \"world\""); assertEcho(result, "06-hello \"world"); assertEcho(result, "07-hello world\""); assertEcho(result, "08-hello world'"); assertEcho(result, "09-hello world\""); } @Test public void testBug45015b() throws Exception { getTomcatInstanceTestWebapp(false, true); int rc = getUrl("http://localhost:" + getPort() + "/test/bug45nnn/bug45015b.jsp", new ByteChunk(), null); Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); } @Test public void testBug45015c() throws Exception { getTomcatInstanceTestWebapp(false, true); int rc = getUrl("http://localhost:" + getPort() + "/test/bug45nnn/bug45015c.jsp", new ByteChunk(), null); Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); } @Test public void testBug48701Fail() throws Exception { getTomcatInstanceTestWebapp(true, true); int rc = getUrl("http://localhost:" + getPort() + "/test/bug48nnn/bug48701-fail.jsp", new ByteChunk(), null); Assert.assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); } @Test public void testBug48701UseBean() throws Exception { testBug48701("bug48nnn/bug48701-UseBean.jsp"); } @Test public void testBug48701VariableInfo() throws Exception { testBug48701("bug48nnn/bug48701-VI.jsp"); } @Test public void testBug48701TagVariableInfoNameGiven() throws Exception { testBug48701("bug48nnn/bug48701-TVI-NG.jsp"); } @Test public void testBug48701TagVariableInfoNameFromAttribute() throws Exception { testBug48701("bug48nnn/bug48701-TVI-NFA.jsp"); } private void testBug48701(String jsp) throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk res = getUrl("http://localhost:" + getPort() + "/test/" + jsp); String result = res.toString(); assertEcho(result, "00-PASS"); } public static class Bug48701 extends TagSupport { private static final long serialVersionUID = 1L; private String beanName = null; public void setBeanName(String beanName) { this.beanName = beanName; } public String getBeanName() { return beanName; } @Override public int doStartTag() throws JspException { Bean bean = new Bean(); bean.setTime((new Date()).toString()); pageContext.setAttribute("now", bean); return super.doStartTag(); } } public static class Bug48701TEI extends TagExtraInfo { @Override public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo("now", Bean.class.getCanonicalName(), true, VariableInfo.AT_END) }; } } public static class Bean { private String time; public void setTime(String time) { this.time = time; } public String getTime() { return time; } } @Test public void testBug49799() throws Exception { String[] expected = { "<p style=\"color:red\">00-Red</p>", "<p>01-Not Red</p>", "<p style=\"color:red\">02-Red</p>", "<p>03-Not Red</p>", "<p style=\"color:red\">04-Red</p>", "<p>05-Not Red</p>" }; getTomcatInstanceTestWebapp(false, true); ByteChunk res = new ByteChunk(); getUrl("http://localhost:" + getPort() + "/test/bug49nnn/bug49799.jsp", res, null); // Check request completed String result = res.toString(); String[] lines = result.split("\n|\r|\r\n"); int i = 0; for (String line : lines) { if (line.length() > 0) { Assert.assertEquals(expected[i], line); i++; } } } /** Assertion for text printed by tags:echo */ private static void assertEcho(String result, String expected) { Assert.assertTrue(result.indexOf("<p>" + expected + "</p>") > 0); } @Test public void testBug56529() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug56529.jsp", bc, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); String response = bc.toStringInternal(CodingErrorAction.REPORT, CodingErrorAction.REPORT); Assert.assertTrue(response, response.contains("[1:attribute1: '', attribute2: '']")); Assert.assertTrue(response, response.contains("[2:attribute1: '', attribute2: '']")); } public static class Bug56529 extends TagSupport { private static final long serialVersionUID = 1L; private String attribute1 = null; private String attribute2 = null; public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } public String getAttribute1() { return attribute1; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } public String getAttribute2() { return attribute2; } @Override public int doEndTag() throws JspException { try { pageContext.getOut().print("attribute1: '" + attribute1 + "', " + "attribute2: '" + attribute2 + "'"); } catch (IOException ioe) { throw new JspException(ioe); } return EVAL_PAGE; } } @Test public void testBug56581() throws LifecycleException { getTomcatInstanceTestWebapp(false, true); ByteChunk res = new ByteChunk(); try { getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug56581.jsp", res, null); Assert.fail("An IOException was expected."); } catch (IOException ignore) { /* * ErrorReportValve flushes and aborts the connection when an unexpected error is encountered and response * has already been committed. It results in an exception here: java.io.IOException: Premature EOF */ } String result = res.toString(); Assert.assertTrue(result.startsWith("0 Hello world!\n")); Assert.assertTrue(result.endsWith("999 Hello world!\n")); } // https://bz.apache.org/bugzilla/show_bug.cgi?id=43400 @Test public void testTagsWithEnums() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk res = getUrl("http://localhost:" + getPort() + "/test/bug43nnn/bug43400.jsp"); String result = res.toString(); System.out.println(result); assertEcho(result, "ASYNC"); } @Test public void testTrimSpacesExtended01() throws Exception { doTestTrimSpacesExtended(false); } @Test public void testTrimSpacesExtended02() throws Exception { doTestTrimSpacesExtended(true); } private void doTestTrimSpacesExtended(boolean removeBlankLines) throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); ctxt.addServletContainerInitializer(new JasperInitializer(), null); Tomcat.initWebappDefaults(ctxt); Wrapper w = (Wrapper) ctxt.findChild("jsp"); if (removeBlankLines) { w.addInitParameter("trimSpaces", "extended"); } tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + "/jsp/trim-spaces-extended.jsp"); String result = res.toString(); Scanner scanner = new Scanner(result); int blankLineCount = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.length() == 0) { blankLineCount++; } } if (!removeBlankLines && blankLineCount == 0) { Assert.fail("TrimSpaceOptions.EXTENDED not configured but blank lines have been removed"); } else if (removeBlankLines && blankLineCount > 0) { Assert.fail("TrimSpaceOptions.EXTENDED does not allow the line to be just a new line character"); } scanner.close(); } @Test public void testEscape01() { String result = Generator.escape("\"\\\n\r"); Assert.assertEquals("\\\"\\\\\\n\\r", result); } @Test public void testEscape02() { String result = Generator.escape("\\"); Assert.assertEquals("\\\\", result); } @Test public void testEscape03() { String result = Generator.escape("xxx\\"); Assert.assertEquals("xxx\\\\", result); } @Test public void testEscape04() { String result = Generator.escape("\\xxx"); Assert.assertEquals("\\\\xxx", result); } @Test public void testQuote01() { String result = Generator.quote('\''); Assert.assertEquals("\'\\\'\'", result); } @Test public void testQuote02() { String result = Generator.quote('\\'); Assert.assertEquals("\'\\\\\'", result); } @Test public void testQuote03() { String result = Generator.quote('\n'); Assert.assertEquals("\'\\n\'", result); } @Test public void testQuote04() { String result = Generator.quote('\r'); Assert.assertEquals("\'\\r\'", result); } @Test public void testQuote05() { String result = Generator.quote('x'); Assert.assertEquals("\'x\'", result); } @Test public void testJspId() throws Exception { doTestJspId(false); } @Test public void testJspIdDocument() throws Exception { doTestJspId(true); } @Test public void testNonstandardSets() throws Exception { getTomcatInstanceTestWebapp(true, true); // This should break all subsequent requests ByteChunk body = new ByteChunk(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/set-01.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=testValue" + NEW_LINE + "request value=null" + NEW_LINE + "session value=null" + NEW_LINE + "application value=null", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/set-02.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=testValue" + NEW_LINE + "request value=null" + NEW_LINE + "session value=null" + NEW_LINE + "application value=null", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/set-03.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=null" + NEW_LINE + "request value=testValue" + NEW_LINE + "session value=null" + NEW_LINE + "application value=null", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/set-04.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=null" + NEW_LINE + "request value=null" + NEW_LINE + "session value=testValue" + NEW_LINE + "application value=null", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/set-05.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=null" + NEW_LINE + "request value=null" + NEW_LINE + "session value=null" + NEW_LINE + "application value=testValue", body.toString()); body.recycle(); } private void doTestJspId(boolean document) throws Exception { getTomcatInstanceTestWebapp(false, true); String uri = "http://localhost:" + getPort() + "/test/jsp/generator/jsp-id.jsp"; if (document) { uri += "x"; } ByteChunk res = getUrl(uri); String result = res.toString(); // Two tags should have different IDs String[] ids = new String[2]; int start = 0; int end = 0; for (int i = 0; i < ids.length; i++) { start = result.indexOf("Jsp ID is [", start) + 11; end = result.indexOf("]", start); ids[i] = result.substring(start, end); } // Confirm the IDs are not the same Assert.assertNotEquals(ids[0], ids[1]); } @Test public void testTryCatchFinally02() throws Exception { doTestJsp("try-catch-finally-02.jsp"); } public static class JspIdTag extends TagSupport implements JspIdConsumer { private static final long serialVersionUID = 1L; private volatile String jspId; @Override public int doStartTag() throws JspException { try { pageContext.getOut().print("<p>Jsp ID is [" + jspId + "]</p>"); } catch (IOException ioe) { throw new JspException(ioe); } return super.doStartTag(); } @Override public void setJspId(String jspId) { this.jspId = jspId; } } public static class TryCatchFinallyBodyTag extends BodyTagSupport implements TryCatchFinally { private static final long serialVersionUID = 1L; @Override public int doStartTag() throws JspException { try { pageContext.getOut().print("<p>OK</p>"); } catch (IOException ioe) { throw new JspException(ioe); } return super.doStartTag(); } @Override public void doCatch(Throwable t) throws Throwable { // NO-OP } @Override public void doFinally() { // NO-OP } } public static class TryCatchFinallyTag extends TagSupport implements TryCatchFinally { private static final long serialVersionUID = 1L; @Override public void doCatch(Throwable t) throws Throwable { // NO-OP } @Override public void doFinally() { // NO-OP } } public static class TesterBodyTag extends BodyTagSupport { private static final long serialVersionUID = 1L; @Override public int doStartTag() throws JspException { try { pageContext.getOut().print("<p>OK</p>"); } catch (IOException ioe) { throw new JspException(ioe); } return super.doStartTag(); } } public static class TesterTag implements Tag { private Tag parent; @Override public void setPageContext(PageContext pc) { } @Override public void setParent(Tag t) { parent = t; } @Override public Tag getParent() { return parent; } @Override public int doStartTag() throws JspException { return 0; } @Override public int doEndTag() throws JspException { return 0; } @Override public void release() { } } public static class TesterTagA extends TesterTag { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } } private static boolean tagTesterTagReleaseReleased = false; public static class TesterTagRelease extends TesterTag { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public void release() { tagTesterTagReleaseReleased = true; } } public static class DataPropertyEditor extends PropertyEditorSupport { } public static class TesterScriptingTag extends TagSupport { private static final long serialVersionUID = 1L; private String attribute02; private String attribute03; public String getAttribute02() { return attribute02; } public void setAttribute02(String attribute02) { this.attribute02 = attribute02; } public String getAttribute03() { return attribute03; } public void setAttribute03(String attribute03) { this.attribute03 = attribute03; } } public static class TesterScriptingTagB extends TagSupport { private static final long serialVersionUID = 1L; private String attribute02; public String getAttribute02() { return attribute02; } public void setAttribute02(String attribute02) { this.attribute02 = attribute02; } } public static class TesterScriptingTagBTEI extends TagExtraInfo { @Override public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo("variable01", "java.lang.String", true, VariableInfo.NESTED), new VariableInfo(data.getAttribute("attribute02").toString(), "java.lang.String", true, VariableInfo.NESTED), new VariableInfo("variable03", "java.lang.String", false, VariableInfo.NESTED) }; } } public static class TesterDynamicTag extends TagSupport implements DynamicAttributes { private static final long serialVersionUID = 1L; @Override public void setDynamicAttribute(String uri, String localName, Object value) throws JspException { // NO-OP } } public static class TesterAttributeTag extends TagSupport { private static final long serialVersionUID = 1L; private Object attribute01; private Object attribute02; private Object attribute03; private Object attribute04; private Object attribute05; private Object attribute06; public Object getAttribute01() { return attribute01; } public void setAttribute01(Object attribute01) { this.attribute01 = attribute01; } public Object getAttribute02() { return attribute02; } public void setAttribute02(Object attribute02) { this.attribute02 = attribute02; } public Object getAttribute03() { return attribute03; } public void setAttribute03(Object attribute03) { this.attribute03 = attribute03; } public Object getAttribute04() { return attribute04; } public void setAttribute04(Object attribute04) { this.attribute04 = attribute04; } public Object getAttribute05() { return attribute05; } public void setAttribute05(Object attribute05) { this.attribute05 = attribute05; } public Object getAttribute06() { return attribute06; } public void setAttribute06(Object attribute06) { this.attribute06 = attribute06; } } @Test public void testLambdaScriptlets() throws Exception { doTestJsp("lambda.jsp"); } @Test public void testInfoConflictNone() throws Exception { doTestJsp("info-conflict-none.jsp"); } @Test public void testInfoConflict() throws Exception { doTestJsp("info-conflict.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testTagWithVariable() throws Exception { doTestJsp("variable-tei-nested.jsp"); } @Test public void testTagWithVariableFromAttr() throws Exception { doTestJsp("variable-from-attr-nested.jsp"); } @Test public void testTagFileWithVariable() throws Exception { doTestJsp("variable-tagfile-nested.jsp"); } @Test public void testTagFileWithVariableFromAttr() throws Exception { doTestJsp("variable-tagfile-from-attr-nested.jsp"); } @Test public void testXpoweredBy() throws Exception { doTestJsp("x-powered-by.jsp"); } @Test public void testXmlProlog01() throws Exception { doTestJsp("xml-prolog-01.jspx"); } @Test public void testXmlProlog02() throws Exception { doTestJsp("xml-prolog-02.jspx"); } @Test public void testXmlPrologTag() throws Exception { doTestJsp("xml-prolog-tag.jspx"); } @Test public void testXmlDoctype01() throws Exception { doTestJsp("xml-doctype-01.jspx"); } @Test public void testXmlDoctype02() throws Exception { doTestJsp("xml-doctype-02.jspx"); } @Test public void testForward01() throws Exception { doTestJsp("forward-01.jsp"); } @Test public void testForward02() throws Exception { doTestJsp("forward-02.jsp"); } @Test public void testForward03() throws Exception { doTestJsp("forward-03.jsp"); } @Test public void testForward04() throws Exception { doTestJsp("forward-04.jsp"); } @Test public void testElement01() throws Exception { doTestJsp("element-01.jsp"); } @Test public void testInclude01() throws Exception { doTestJsp("include-01.jsp"); } @Test public void testSetProperty01() throws Exception { doTestJsp("setproperty-01.jsp"); } @Test public void testUseBean01() throws Exception { doTestJsp("usebean-01.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testUseBean02() throws Exception { doTestJsp("usebean-02.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testUseBean03() throws Exception { doTestJsp("usebean-03.jsp"); } @Test public void testUseBean04() throws Exception { doTestJsp("usebean-04.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testUseBean05() throws Exception { // Whether this test passes or fails depends on the Java version used // and the JRE settings. // For the test to pass use --illegal-access=deny // This is the default setting for Java 16 onwards doTestJsp("usebean-05.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testUseBean06() throws Exception { doTestJsp("usebean-06.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testUseBean07() throws Exception { doTestJsp("usebean-07.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testUseBean08() throws Exception { doTestJsp("usebean-08.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testCustomTag01() throws Exception { doTestJsp("try-catch-finally-01.jsp"); } @Test public void testCustomTag02() throws Exception { doTestJsp("customtag-02.jsp"); } @Test public void testCustomTag03() throws Exception { doTestJsp("customtag-03.jsp"); } @Test public void testCustomTag04() throws Exception { doTestJsp("customtag-04.jsp", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void testTemplateText01() throws Exception { doTestJsp("templatetext-01.jsp"); } @Test public void testTemplateText02() throws Exception { doTestJsp("templatetext-02.jsp"); } @Test public void testInvoke01() throws Exception { doTestJsp("invoke-01.jsp"); } @Test public void testDoBody01() throws Exception { doTestJsp("dobody-01.jsp"); } @Test public void testScriptingVariables01() throws Exception { doTestJsp("scriptingvariables-01.jsp"); } @Test public void testScriptingVariables02() throws Exception { doTestJsp("scriptingvariables-02.jsp"); } @Test public void testAttribute01() throws Exception { doTestJsp("attribute-01.jsp"); } @Test public void testAttribute02() throws Exception { doTestJsp("attribute-02.jsp"); } @Test public void testAttribute03() throws Exception { doTestJsp("attribute-03.jsp"); } @Test public void testAttribute04() throws Exception { doTestJsp("attribute-04.jsp"); } @Test public void testSetters01() throws Exception { doTestJsp("setters-01.jsp"); } @Test public void testCircular01() throws Exception { doTestJsp("circular-01.jsp"); } @Test public void testDeferredMethod01() throws Exception { doTestJsp("deferred-method-01.jsp"); } @Test public void testDeferredMethod02() throws Exception { doTestJsp("deferred-method-02.jsp"); } @Test public void testBeanInfo01() throws Exception { BeanInfo bi = Introspector.getBeanInfo(TesterTagA.class); for (PropertyDescriptor pd : bi.getPropertyDescriptors()) { if (pd.getName().equals("data")) { pd.setPropertyEditorClass(DataPropertyEditor.class); } } doTestJsp("beaninfo-01.jsp"); } @Test public void testBreakELInterpreter() throws Exception { getTomcatInstanceTestWebapp(false, true); // This should break all subsequent requests ByteChunk body = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/generator/break-el-interpreter.jsp", body, null); Assert.assertEquals(body.toString(), HttpServletResponse.SC_OK, rc); body.recycle(); rc = getUrl("http://localhost:" + getPort() + "/test/jsp/generator/info.jsp", body, null); Assert.assertEquals(body.toString(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); } @Test public void testBreakStringInterpreter() throws Exception { getTomcatInstanceTestWebapp(false, true); // This should break all subsequent requests ByteChunk body = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/generator/break-string-interpreter.jsp", body, null); Assert.assertEquals(body.toString(), HttpServletResponse.SC_OK, rc); body.recycle(); rc = getUrl("http://localhost:" + getPort() + "/test/jsp/generator/info.jsp", body, null); Assert.assertEquals(body.toString(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); } @Test public void testBug65390() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk body = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug6nnnn/bug65390.jsp", body, null); Assert.assertEquals(body.toString(), HttpServletResponse.SC_OK, rc); } @Test public void testBug69508() throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk body = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug6nnnn/bug69508.jsp?init=InitCommand", body, null); String text = body.toString(); Assert.assertEquals(text, HttpServletResponse.SC_OK, rc); // include page URL with param cmd Assert.assertTrue(text, text.contains("<p>cmd - someCommand</p>")); Assert.assertTrue(text, text.contains("<p>param1 - value1</p>")); Assert.assertTrue(text, text.contains("<p>cmd - someCommandAbs</p>")); Assert.assertTrue(text, text.contains("<p>param1 - value1Abs</p>")); // include page URL without param Assert.assertTrue(text, text.contains("<p>param2 - value2</p>")); Assert.assertTrue(text, text.contains("<p>param2 - value2Abs</p>")); Assert.assertTrue(text, text.contains("<p>param3 - InitCommand</p>")); Assert.assertTrue(text, text.contains("<p>param3 - InitCommandAbs</p>")); Assert.assertTrue(text, text.contains("<p>param4 - value4</p>")); Assert.assertTrue(text, text.contains("<p>param4 - value4Abs</p>")); Assert.assertTrue(text, text.contains("<p>param5 - InitCommand</p>")); Assert.assertTrue(text, text.contains("<p>param5 - InitCommandAbs</p>")); Assert.assertTrue(text, text.contains("<p>param6 - value6</p>")); Assert.assertTrue(text, text.contains("<p>param6 - value6Abs</p>")); } @Test public void testTagReleaseWithPooling() throws Exception { doTestTagRelease(true); } @Test public void testTagReleaseWithoutPooling() throws Exception { doTestTagRelease(false); } public void doTestTagRelease(boolean enablePooling) throws Exception { tagTesterTagReleaseReleased = false; Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); Context ctxt = tomcat.addContext("", appDir.getAbsolutePath()); ctxt.addServletContainerInitializer(new JasperInitializer(), null); Tomcat.initWebappDefaults(ctxt); Wrapper w = (Wrapper) ctxt.findChild("jsp"); w.addInitParameter("enablePooling", String.valueOf(enablePooling)); tomcat.start(); getUrl("http://localhost:" + getPort() + "/jsp/generator/release.jsp"); if (enablePooling) { Assert.assertFalse(tagTesterTagReleaseReleased); } else { Assert.assertTrue(tagTesterTagReleaseReleased); } } private void doTestJsp(String jspName) throws Exception { doTestJsp(jspName, HttpServletResponse.SC_OK); } private void doTestJsp(String jspName, int expectedResponseCode) throws Exception { getTomcatInstanceTestWebapp(false, true); ByteChunk body = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/jsp/generator/" + jspName, body, null); Assert.assertEquals(body.toString(), expectedResponseCode, rc); } @Test public void testNonstandardRemoves() throws Exception { getTomcatInstanceTestWebapp(true, true); // This should break all subsequent requests ByteChunk body = new ByteChunk(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/remove-01.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=null" + NEW_LINE + "request value=testValue" + NEW_LINE + "session value=testValue" + NEW_LINE + "application value=testValue", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/remove-02.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=testValue" + NEW_LINE + "request value=null" + NEW_LINE + "session value=testValue" + NEW_LINE + "application value=testValue", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/remove-03.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=testValue" + NEW_LINE + "request value=testValue" + NEW_LINE + "session value=null" + NEW_LINE + "application value=testValue", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/remove-04.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=testValue" + NEW_LINE + "request value=testValue" + NEW_LINE + "session value=testValue" + NEW_LINE + "application value=null", body.toString()); body.recycle(); getUrl("http://localhost:" + getPort() + "/test/jsp/generator/nonstandard/remove-05.jsp", body, null); Assert.assertEquals(NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + NEW_LINE + "pageContext value=null" + NEW_LINE + "request value=null" + NEW_LINE + "session value=null" + NEW_LINE + "application value=null", body.toString()); body.recycle(); } }
googleads/google-ads-java
36,750
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/YouTubeCreatorInsights.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/services/content_creator_insights_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.services; /** * <pre> * A YouTube creator and the insights for this creator. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.YouTubeCreatorInsights} */ public final class YouTubeCreatorInsights extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.YouTubeCreatorInsights) YouTubeCreatorInsightsOrBuilder { private static final long serialVersionUID = 0L; // Use YouTubeCreatorInsights.newBuilder() to construct. private YouTubeCreatorInsights(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private YouTubeCreatorInsights() { creatorName_ = ""; creatorChannels_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new YouTubeCreatorInsights(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v19_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v19_services_YouTubeCreatorInsights_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.YouTubeCreatorInsights.class, com.google.ads.googleads.v19.services.YouTubeCreatorInsights.Builder.class); } public static final int CREATOR_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object creatorName_ = ""; /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The creatorName. */ @java.lang.Override public java.lang.String getCreatorName() { java.lang.Object ref = creatorName_; 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(); creatorName_ = s; return s; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The bytes for creatorName. */ @java.lang.Override public com.google.protobuf.ByteString getCreatorNameBytes() { java.lang.Object ref = creatorName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); creatorName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATOR_CHANNELS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v19.services.YouTubeChannelInsights> creatorChannels_; /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v19.services.YouTubeChannelInsights> getCreatorChannelsList() { return creatorChannels_; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsOrBuilderList() { return creatorChannels_; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public int getCreatorChannelsCount() { return creatorChannels_.size(); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.YouTubeChannelInsights getCreatorChannels(int index) { return creatorChannels_.get(index); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder getCreatorChannelsOrBuilder( int index) { return creatorChannels_.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(creatorName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, creatorName_); } for (int i = 0; i < creatorChannels_.size(); i++) { output.writeMessage(2, creatorChannels_.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(creatorName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, creatorName_); } for (int i = 0; i < creatorChannels_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, creatorChannels_.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.ads.googleads.v19.services.YouTubeCreatorInsights)) { return super.equals(obj); } com.google.ads.googleads.v19.services.YouTubeCreatorInsights other = (com.google.ads.googleads.v19.services.YouTubeCreatorInsights) obj; if (!getCreatorName() .equals(other.getCreatorName())) return false; if (!getCreatorChannelsList() .equals(other.getCreatorChannelsList())) 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) + CREATOR_NAME_FIELD_NUMBER; hash = (53 * hash) + getCreatorName().hashCode(); if (getCreatorChannelsCount() > 0) { hash = (37 * hash) + CREATOR_CHANNELS_FIELD_NUMBER; hash = (53 * hash) + getCreatorChannelsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.services.YouTubeCreatorInsights parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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 YouTube creator and the insights for this creator. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.YouTubeCreatorInsights} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.YouTubeCreatorInsights) com.google.ads.googleads.v19.services.YouTubeCreatorInsightsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v19_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v19_services_YouTubeCreatorInsights_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.YouTubeCreatorInsights.class, com.google.ads.googleads.v19.services.YouTubeCreatorInsights.Builder.class); } // Construct using com.google.ads.googleads.v19.services.YouTubeCreatorInsights.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; creatorName_ = ""; if (creatorChannelsBuilder_ == null) { creatorChannels_ = java.util.Collections.emptyList(); } else { creatorChannels_ = null; creatorChannelsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v19_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.services.YouTubeCreatorInsights getDefaultInstanceForType() { return com.google.ads.googleads.v19.services.YouTubeCreatorInsights.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.services.YouTubeCreatorInsights build() { com.google.ads.googleads.v19.services.YouTubeCreatorInsights result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.services.YouTubeCreatorInsights buildPartial() { com.google.ads.googleads.v19.services.YouTubeCreatorInsights result = new com.google.ads.googleads.v19.services.YouTubeCreatorInsights(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v19.services.YouTubeCreatorInsights result) { if (creatorChannelsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { creatorChannels_ = java.util.Collections.unmodifiableList(creatorChannels_); bitField0_ = (bitField0_ & ~0x00000002); } result.creatorChannels_ = creatorChannels_; } else { result.creatorChannels_ = creatorChannelsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v19.services.YouTubeCreatorInsights result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.creatorName_ = creatorName_; } } @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.YouTubeCreatorInsights) { return mergeFrom((com.google.ads.googleads.v19.services.YouTubeCreatorInsights)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.services.YouTubeCreatorInsights other) { if (other == com.google.ads.googleads.v19.services.YouTubeCreatorInsights.getDefaultInstance()) return this; if (!other.getCreatorName().isEmpty()) { creatorName_ = other.creatorName_; bitField0_ |= 0x00000001; onChanged(); } if (creatorChannelsBuilder_ == null) { if (!other.creatorChannels_.isEmpty()) { if (creatorChannels_.isEmpty()) { creatorChannels_ = other.creatorChannels_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureCreatorChannelsIsMutable(); creatorChannels_.addAll(other.creatorChannels_); } onChanged(); } } else { if (!other.creatorChannels_.isEmpty()) { if (creatorChannelsBuilder_.isEmpty()) { creatorChannelsBuilder_.dispose(); creatorChannelsBuilder_ = null; creatorChannels_ = other.creatorChannels_; bitField0_ = (bitField0_ & ~0x00000002); creatorChannelsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCreatorChannelsFieldBuilder() : null; } else { creatorChannelsBuilder_.addAllMessages(other.creatorChannels_); } } } 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: { creatorName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.ads.googleads.v19.services.YouTubeChannelInsights m = input.readMessage( com.google.ads.googleads.v19.services.YouTubeChannelInsights.parser(), extensionRegistry); if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(m); } else { creatorChannelsBuilder_.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 creatorName_ = ""; /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The creatorName. */ public java.lang.String getCreatorName() { java.lang.Object ref = creatorName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); creatorName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The bytes for creatorName. */ public com.google.protobuf.ByteString getCreatorNameBytes() { java.lang.Object ref = creatorName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); creatorName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @param value The creatorName to set. * @return This builder for chaining. */ public Builder setCreatorName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } creatorName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return This builder for chaining. */ public Builder clearCreatorName() { creatorName_ = getDefaultInstance().getCreatorName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @param value The bytes for creatorName to set. * @return This builder for chaining. */ public Builder setCreatorNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); creatorName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v19.services.YouTubeChannelInsights> creatorChannels_ = java.util.Collections.emptyList(); private void ensureCreatorChannelsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { creatorChannels_ = new java.util.ArrayList<com.google.ads.googleads.v19.services.YouTubeChannelInsights>(creatorChannels_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.YouTubeChannelInsights, com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder> creatorChannelsBuilder_; /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<com.google.ads.googleads.v19.services.YouTubeChannelInsights> getCreatorChannelsList() { if (creatorChannelsBuilder_ == null) { return java.util.Collections.unmodifiableList(creatorChannels_); } else { return creatorChannelsBuilder_.getMessageList(); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public int getCreatorChannelsCount() { if (creatorChannelsBuilder_ == null) { return creatorChannels_.size(); } else { return creatorChannelsBuilder_.getCount(); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v19.services.YouTubeChannelInsights getCreatorChannels(int index) { if (creatorChannelsBuilder_ == null) { return creatorChannels_.get(index); } else { return creatorChannelsBuilder_.getMessage(index); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder setCreatorChannels( int index, com.google.ads.googleads.v19.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.set(index, value); onChanged(); } else { creatorChannelsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder setCreatorChannels( int index, com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.set(index, builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels(com.google.ads.googleads.v19.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.add(value); onChanged(); } else { creatorChannelsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( int index, com.google.ads.googleads.v19.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.add(index, value); onChanged(); } else { creatorChannelsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( int index, com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(index, builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addAllCreatorChannels( java.lang.Iterable<? extends com.google.ads.googleads.v19.services.YouTubeChannelInsights> values) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, creatorChannels_); onChanged(); } else { creatorChannelsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder clearCreatorChannels() { if (creatorChannelsBuilder_ == null) { creatorChannels_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { creatorChannelsBuilder_.clear(); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder removeCreatorChannels(int index) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.remove(index); onChanged(); } else { creatorChannelsBuilder_.remove(index); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder getCreatorChannelsBuilder( int index) { return getCreatorChannelsFieldBuilder().getBuilder(index); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder getCreatorChannelsOrBuilder( int index) { if (creatorChannelsBuilder_ == null) { return creatorChannels_.get(index); } else { return creatorChannelsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<? extends com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsOrBuilderList() { if (creatorChannelsBuilder_ != null) { return creatorChannelsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(creatorChannels_); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder addCreatorChannelsBuilder() { return getCreatorChannelsFieldBuilder().addBuilder( com.google.ads.googleads.v19.services.YouTubeChannelInsights.getDefaultInstance()); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder addCreatorChannelsBuilder( int index) { return getCreatorChannelsFieldBuilder().addBuilder( index, com.google.ads.googleads.v19.services.YouTubeChannelInsights.getDefaultInstance()); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v19.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder> getCreatorChannelsBuilderList() { return getCreatorChannelsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.YouTubeChannelInsights, com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsFieldBuilder() { if (creatorChannelsBuilder_ == null) { creatorChannelsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.YouTubeChannelInsights, com.google.ads.googleads.v19.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v19.services.YouTubeChannelInsightsOrBuilder>( creatorChannels_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); creatorChannels_ = null; } return creatorChannelsBuilder_; } @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.YouTubeCreatorInsights) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.YouTubeCreatorInsights) private static final com.google.ads.googleads.v19.services.YouTubeCreatorInsights DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.YouTubeCreatorInsights(); } public static com.google.ads.googleads.v19.services.YouTubeCreatorInsights getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<YouTubeCreatorInsights> PARSER = new com.google.protobuf.AbstractParser<YouTubeCreatorInsights>() { @java.lang.Override public YouTubeCreatorInsights 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<YouTubeCreatorInsights> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<YouTubeCreatorInsights> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.services.YouTubeCreatorInsights getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,750
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/YouTubeCreatorInsights.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/services/content_creator_insights_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.services; /** * <pre> * A YouTube creator and the insights for this creator. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.YouTubeCreatorInsights} */ public final class YouTubeCreatorInsights extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.YouTubeCreatorInsights) YouTubeCreatorInsightsOrBuilder { private static final long serialVersionUID = 0L; // Use YouTubeCreatorInsights.newBuilder() to construct. private YouTubeCreatorInsights(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private YouTubeCreatorInsights() { creatorName_ = ""; creatorChannels_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new YouTubeCreatorInsights(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v20_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v20_services_YouTubeCreatorInsights_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.YouTubeCreatorInsights.class, com.google.ads.googleads.v20.services.YouTubeCreatorInsights.Builder.class); } public static final int CREATOR_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object creatorName_ = ""; /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The creatorName. */ @java.lang.Override public java.lang.String getCreatorName() { java.lang.Object ref = creatorName_; 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(); creatorName_ = s; return s; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The bytes for creatorName. */ @java.lang.Override public com.google.protobuf.ByteString getCreatorNameBytes() { java.lang.Object ref = creatorName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); creatorName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATOR_CHANNELS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v20.services.YouTubeChannelInsights> creatorChannels_; /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v20.services.YouTubeChannelInsights> getCreatorChannelsList() { return creatorChannels_; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsOrBuilderList() { return creatorChannels_; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public int getCreatorChannelsCount() { return creatorChannels_.size(); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.YouTubeChannelInsights getCreatorChannels(int index) { return creatorChannels_.get(index); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder getCreatorChannelsOrBuilder( int index) { return creatorChannels_.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(creatorName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, creatorName_); } for (int i = 0; i < creatorChannels_.size(); i++) { output.writeMessage(2, creatorChannels_.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(creatorName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, creatorName_); } for (int i = 0; i < creatorChannels_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, creatorChannels_.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.ads.googleads.v20.services.YouTubeCreatorInsights)) { return super.equals(obj); } com.google.ads.googleads.v20.services.YouTubeCreatorInsights other = (com.google.ads.googleads.v20.services.YouTubeCreatorInsights) obj; if (!getCreatorName() .equals(other.getCreatorName())) return false; if (!getCreatorChannelsList() .equals(other.getCreatorChannelsList())) 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) + CREATOR_NAME_FIELD_NUMBER; hash = (53 * hash) + getCreatorName().hashCode(); if (getCreatorChannelsCount() > 0) { hash = (37 * hash) + CREATOR_CHANNELS_FIELD_NUMBER; hash = (53 * hash) + getCreatorChannelsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.services.YouTubeCreatorInsights parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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 YouTube creator and the insights for this creator. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.YouTubeCreatorInsights} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.YouTubeCreatorInsights) com.google.ads.googleads.v20.services.YouTubeCreatorInsightsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v20_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v20_services_YouTubeCreatorInsights_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.YouTubeCreatorInsights.class, com.google.ads.googleads.v20.services.YouTubeCreatorInsights.Builder.class); } // Construct using com.google.ads.googleads.v20.services.YouTubeCreatorInsights.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; creatorName_ = ""; if (creatorChannelsBuilder_ == null) { creatorChannels_ = java.util.Collections.emptyList(); } else { creatorChannels_ = null; creatorChannelsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v20_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.services.YouTubeCreatorInsights getDefaultInstanceForType() { return com.google.ads.googleads.v20.services.YouTubeCreatorInsights.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.services.YouTubeCreatorInsights build() { com.google.ads.googleads.v20.services.YouTubeCreatorInsights result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.services.YouTubeCreatorInsights buildPartial() { com.google.ads.googleads.v20.services.YouTubeCreatorInsights result = new com.google.ads.googleads.v20.services.YouTubeCreatorInsights(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v20.services.YouTubeCreatorInsights result) { if (creatorChannelsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { creatorChannels_ = java.util.Collections.unmodifiableList(creatorChannels_); bitField0_ = (bitField0_ & ~0x00000002); } result.creatorChannels_ = creatorChannels_; } else { result.creatorChannels_ = creatorChannelsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v20.services.YouTubeCreatorInsights result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.creatorName_ = creatorName_; } } @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.YouTubeCreatorInsights) { return mergeFrom((com.google.ads.googleads.v20.services.YouTubeCreatorInsights)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.services.YouTubeCreatorInsights other) { if (other == com.google.ads.googleads.v20.services.YouTubeCreatorInsights.getDefaultInstance()) return this; if (!other.getCreatorName().isEmpty()) { creatorName_ = other.creatorName_; bitField0_ |= 0x00000001; onChanged(); } if (creatorChannelsBuilder_ == null) { if (!other.creatorChannels_.isEmpty()) { if (creatorChannels_.isEmpty()) { creatorChannels_ = other.creatorChannels_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureCreatorChannelsIsMutable(); creatorChannels_.addAll(other.creatorChannels_); } onChanged(); } } else { if (!other.creatorChannels_.isEmpty()) { if (creatorChannelsBuilder_.isEmpty()) { creatorChannelsBuilder_.dispose(); creatorChannelsBuilder_ = null; creatorChannels_ = other.creatorChannels_; bitField0_ = (bitField0_ & ~0x00000002); creatorChannelsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCreatorChannelsFieldBuilder() : null; } else { creatorChannelsBuilder_.addAllMessages(other.creatorChannels_); } } } 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: { creatorName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.ads.googleads.v20.services.YouTubeChannelInsights m = input.readMessage( com.google.ads.googleads.v20.services.YouTubeChannelInsights.parser(), extensionRegistry); if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(m); } else { creatorChannelsBuilder_.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 creatorName_ = ""; /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The creatorName. */ public java.lang.String getCreatorName() { java.lang.Object ref = creatorName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); creatorName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The bytes for creatorName. */ public com.google.protobuf.ByteString getCreatorNameBytes() { java.lang.Object ref = creatorName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); creatorName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @param value The creatorName to set. * @return This builder for chaining. */ public Builder setCreatorName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } creatorName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return This builder for chaining. */ public Builder clearCreatorName() { creatorName_ = getDefaultInstance().getCreatorName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @param value The bytes for creatorName to set. * @return This builder for chaining. */ public Builder setCreatorNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); creatorName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v20.services.YouTubeChannelInsights> creatorChannels_ = java.util.Collections.emptyList(); private void ensureCreatorChannelsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { creatorChannels_ = new java.util.ArrayList<com.google.ads.googleads.v20.services.YouTubeChannelInsights>(creatorChannels_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.YouTubeChannelInsights, com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder> creatorChannelsBuilder_; /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<com.google.ads.googleads.v20.services.YouTubeChannelInsights> getCreatorChannelsList() { if (creatorChannelsBuilder_ == null) { return java.util.Collections.unmodifiableList(creatorChannels_); } else { return creatorChannelsBuilder_.getMessageList(); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public int getCreatorChannelsCount() { if (creatorChannelsBuilder_ == null) { return creatorChannels_.size(); } else { return creatorChannelsBuilder_.getCount(); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v20.services.YouTubeChannelInsights getCreatorChannels(int index) { if (creatorChannelsBuilder_ == null) { return creatorChannels_.get(index); } else { return creatorChannelsBuilder_.getMessage(index); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder setCreatorChannels( int index, com.google.ads.googleads.v20.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.set(index, value); onChanged(); } else { creatorChannelsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder setCreatorChannels( int index, com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.set(index, builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels(com.google.ads.googleads.v20.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.add(value); onChanged(); } else { creatorChannelsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( int index, com.google.ads.googleads.v20.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.add(index, value); onChanged(); } else { creatorChannelsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( int index, com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(index, builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addAllCreatorChannels( java.lang.Iterable<? extends com.google.ads.googleads.v20.services.YouTubeChannelInsights> values) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, creatorChannels_); onChanged(); } else { creatorChannelsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder clearCreatorChannels() { if (creatorChannelsBuilder_ == null) { creatorChannels_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { creatorChannelsBuilder_.clear(); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder removeCreatorChannels(int index) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.remove(index); onChanged(); } else { creatorChannelsBuilder_.remove(index); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder getCreatorChannelsBuilder( int index) { return getCreatorChannelsFieldBuilder().getBuilder(index); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder getCreatorChannelsOrBuilder( int index) { if (creatorChannelsBuilder_ == null) { return creatorChannels_.get(index); } else { return creatorChannelsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<? extends com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsOrBuilderList() { if (creatorChannelsBuilder_ != null) { return creatorChannelsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(creatorChannels_); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder addCreatorChannelsBuilder() { return getCreatorChannelsFieldBuilder().addBuilder( com.google.ads.googleads.v20.services.YouTubeChannelInsights.getDefaultInstance()); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder addCreatorChannelsBuilder( int index) { return getCreatorChannelsFieldBuilder().addBuilder( index, com.google.ads.googleads.v20.services.YouTubeChannelInsights.getDefaultInstance()); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v20.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder> getCreatorChannelsBuilderList() { return getCreatorChannelsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.YouTubeChannelInsights, com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsFieldBuilder() { if (creatorChannelsBuilder_ == null) { creatorChannelsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.YouTubeChannelInsights, com.google.ads.googleads.v20.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v20.services.YouTubeChannelInsightsOrBuilder>( creatorChannels_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); creatorChannels_ = null; } return creatorChannelsBuilder_; } @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.YouTubeCreatorInsights) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.YouTubeCreatorInsights) private static final com.google.ads.googleads.v20.services.YouTubeCreatorInsights DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.YouTubeCreatorInsights(); } public static com.google.ads.googleads.v20.services.YouTubeCreatorInsights getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<YouTubeCreatorInsights> PARSER = new com.google.protobuf.AbstractParser<YouTubeCreatorInsights>() { @java.lang.Override public YouTubeCreatorInsights 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<YouTubeCreatorInsights> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<YouTubeCreatorInsights> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.services.YouTubeCreatorInsights getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,750
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/YouTubeCreatorInsights.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/content_creator_insights_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; /** * <pre> * A YouTube creator and the insights for this creator. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.YouTubeCreatorInsights} */ public final class YouTubeCreatorInsights extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.YouTubeCreatorInsights) YouTubeCreatorInsightsOrBuilder { private static final long serialVersionUID = 0L; // Use YouTubeCreatorInsights.newBuilder() to construct. private YouTubeCreatorInsights(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private YouTubeCreatorInsights() { creatorName_ = ""; creatorChannels_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new YouTubeCreatorInsights(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v21_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v21_services_YouTubeCreatorInsights_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.YouTubeCreatorInsights.class, com.google.ads.googleads.v21.services.YouTubeCreatorInsights.Builder.class); } public static final int CREATOR_NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object creatorName_ = ""; /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The creatorName. */ @java.lang.Override public java.lang.String getCreatorName() { java.lang.Object ref = creatorName_; 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(); creatorName_ = s; return s; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The bytes for creatorName. */ @java.lang.Override public com.google.protobuf.ByteString getCreatorNameBytes() { java.lang.Object ref = creatorName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); creatorName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATOR_CHANNELS_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v21.services.YouTubeChannelInsights> creatorChannels_; /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v21.services.YouTubeChannelInsights> getCreatorChannelsList() { return creatorChannels_; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsOrBuilderList() { return creatorChannels_; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public int getCreatorChannelsCount() { return creatorChannels_.size(); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.YouTubeChannelInsights getCreatorChannels(int index) { return creatorChannels_.get(index); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder getCreatorChannelsOrBuilder( int index) { return creatorChannels_.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(creatorName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, creatorName_); } for (int i = 0; i < creatorChannels_.size(); i++) { output.writeMessage(2, creatorChannels_.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(creatorName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, creatorName_); } for (int i = 0; i < creatorChannels_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, creatorChannels_.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.ads.googleads.v21.services.YouTubeCreatorInsights)) { return super.equals(obj); } com.google.ads.googleads.v21.services.YouTubeCreatorInsights other = (com.google.ads.googleads.v21.services.YouTubeCreatorInsights) obj; if (!getCreatorName() .equals(other.getCreatorName())) return false; if (!getCreatorChannelsList() .equals(other.getCreatorChannelsList())) 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) + CREATOR_NAME_FIELD_NUMBER; hash = (53 * hash) + getCreatorName().hashCode(); if (getCreatorChannelsCount() > 0) { hash = (37 * hash) + CREATOR_CHANNELS_FIELD_NUMBER; hash = (53 * hash) + getCreatorChannelsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.services.YouTubeCreatorInsights parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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.YouTubeCreatorInsights 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 YouTube creator and the insights for this creator. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.YouTubeCreatorInsights} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.YouTubeCreatorInsights) com.google.ads.googleads.v21.services.YouTubeCreatorInsightsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v21_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v21_services_YouTubeCreatorInsights_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.YouTubeCreatorInsights.class, com.google.ads.googleads.v21.services.YouTubeCreatorInsights.Builder.class); } // Construct using com.google.ads.googleads.v21.services.YouTubeCreatorInsights.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; creatorName_ = ""; if (creatorChannelsBuilder_ == null) { creatorChannels_ = java.util.Collections.emptyList(); } else { creatorChannels_ = null; creatorChannelsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.services.ContentCreatorInsightsServiceProto.internal_static_google_ads_googleads_v21_services_YouTubeCreatorInsights_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.services.YouTubeCreatorInsights getDefaultInstanceForType() { return com.google.ads.googleads.v21.services.YouTubeCreatorInsights.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.services.YouTubeCreatorInsights build() { com.google.ads.googleads.v21.services.YouTubeCreatorInsights result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.services.YouTubeCreatorInsights buildPartial() { com.google.ads.googleads.v21.services.YouTubeCreatorInsights result = new com.google.ads.googleads.v21.services.YouTubeCreatorInsights(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v21.services.YouTubeCreatorInsights result) { if (creatorChannelsBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { creatorChannels_ = java.util.Collections.unmodifiableList(creatorChannels_); bitField0_ = (bitField0_ & ~0x00000002); } result.creatorChannels_ = creatorChannels_; } else { result.creatorChannels_ = creatorChannelsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v21.services.YouTubeCreatorInsights result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.creatorName_ = creatorName_; } } @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.YouTubeCreatorInsights) { return mergeFrom((com.google.ads.googleads.v21.services.YouTubeCreatorInsights)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.services.YouTubeCreatorInsights other) { if (other == com.google.ads.googleads.v21.services.YouTubeCreatorInsights.getDefaultInstance()) return this; if (!other.getCreatorName().isEmpty()) { creatorName_ = other.creatorName_; bitField0_ |= 0x00000001; onChanged(); } if (creatorChannelsBuilder_ == null) { if (!other.creatorChannels_.isEmpty()) { if (creatorChannels_.isEmpty()) { creatorChannels_ = other.creatorChannels_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureCreatorChannelsIsMutable(); creatorChannels_.addAll(other.creatorChannels_); } onChanged(); } } else { if (!other.creatorChannels_.isEmpty()) { if (creatorChannelsBuilder_.isEmpty()) { creatorChannelsBuilder_.dispose(); creatorChannelsBuilder_ = null; creatorChannels_ = other.creatorChannels_; bitField0_ = (bitField0_ & ~0x00000002); creatorChannelsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCreatorChannelsFieldBuilder() : null; } else { creatorChannelsBuilder_.addAllMessages(other.creatorChannels_); } } } 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: { creatorName_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { com.google.ads.googleads.v21.services.YouTubeChannelInsights m = input.readMessage( com.google.ads.googleads.v21.services.YouTubeChannelInsights.parser(), extensionRegistry); if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(m); } else { creatorChannelsBuilder_.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 creatorName_ = ""; /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The creatorName. */ public java.lang.String getCreatorName() { java.lang.Object ref = creatorName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); creatorName_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return The bytes for creatorName. */ public com.google.protobuf.ByteString getCreatorNameBytes() { java.lang.Object ref = creatorName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); creatorName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @param value The creatorName to set. * @return This builder for chaining. */ public Builder setCreatorName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } creatorName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @return This builder for chaining. */ public Builder clearCreatorName() { creatorName_ = getDefaultInstance().getCreatorName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * The name of the creator. * </pre> * * <code>string creator_name = 1;</code> * @param value The bytes for creatorName to set. * @return This builder for chaining. */ public Builder setCreatorNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); creatorName_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.util.List<com.google.ads.googleads.v21.services.YouTubeChannelInsights> creatorChannels_ = java.util.Collections.emptyList(); private void ensureCreatorChannelsIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { creatorChannels_ = new java.util.ArrayList<com.google.ads.googleads.v21.services.YouTubeChannelInsights>(creatorChannels_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.YouTubeChannelInsights, com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder> creatorChannelsBuilder_; /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<com.google.ads.googleads.v21.services.YouTubeChannelInsights> getCreatorChannelsList() { if (creatorChannelsBuilder_ == null) { return java.util.Collections.unmodifiableList(creatorChannels_); } else { return creatorChannelsBuilder_.getMessageList(); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public int getCreatorChannelsCount() { if (creatorChannelsBuilder_ == null) { return creatorChannels_.size(); } else { return creatorChannelsBuilder_.getCount(); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v21.services.YouTubeChannelInsights getCreatorChannels(int index) { if (creatorChannelsBuilder_ == null) { return creatorChannels_.get(index); } else { return creatorChannelsBuilder_.getMessage(index); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder setCreatorChannels( int index, com.google.ads.googleads.v21.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.set(index, value); onChanged(); } else { creatorChannelsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder setCreatorChannels( int index, com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.set(index, builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels(com.google.ads.googleads.v21.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.add(value); onChanged(); } else { creatorChannelsBuilder_.addMessage(value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( int index, com.google.ads.googleads.v21.services.YouTubeChannelInsights value) { if (creatorChannelsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCreatorChannelsIsMutable(); creatorChannels_.add(index, value); onChanged(); } else { creatorChannelsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addCreatorChannels( int index, com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder builderForValue) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.add(index, builderForValue.build()); onChanged(); } else { creatorChannelsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder addAllCreatorChannels( java.lang.Iterable<? extends com.google.ads.googleads.v21.services.YouTubeChannelInsights> values) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, creatorChannels_); onChanged(); } else { creatorChannelsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder clearCreatorChannels() { if (creatorChannelsBuilder_ == null) { creatorChannels_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { creatorChannelsBuilder_.clear(); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public Builder removeCreatorChannels(int index) { if (creatorChannelsBuilder_ == null) { ensureCreatorChannelsIsMutable(); creatorChannels_.remove(index); onChanged(); } else { creatorChannelsBuilder_.remove(index); } return this; } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder getCreatorChannelsBuilder( int index) { return getCreatorChannelsFieldBuilder().getBuilder(index); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder getCreatorChannelsOrBuilder( int index) { if (creatorChannelsBuilder_ == null) { return creatorChannels_.get(index); } else { return creatorChannelsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<? extends com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsOrBuilderList() { if (creatorChannelsBuilder_ != null) { return creatorChannelsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(creatorChannels_); } } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder addCreatorChannelsBuilder() { return getCreatorChannelsFieldBuilder().addBuilder( com.google.ads.googleads.v21.services.YouTubeChannelInsights.getDefaultInstance()); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder addCreatorChannelsBuilder( int index) { return getCreatorChannelsFieldBuilder().addBuilder( index, com.google.ads.googleads.v21.services.YouTubeChannelInsights.getDefaultInstance()); } /** * <pre> * The list of YouTube Channels * </pre> * * <code>repeated .google.ads.googleads.v21.services.YouTubeChannelInsights creator_channels = 2;</code> */ public java.util.List<com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder> getCreatorChannelsBuilderList() { return getCreatorChannelsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.YouTubeChannelInsights, com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder> getCreatorChannelsFieldBuilder() { if (creatorChannelsBuilder_ == null) { creatorChannelsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.YouTubeChannelInsights, com.google.ads.googleads.v21.services.YouTubeChannelInsights.Builder, com.google.ads.googleads.v21.services.YouTubeChannelInsightsOrBuilder>( creatorChannels_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); creatorChannels_ = null; } return creatorChannelsBuilder_; } @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.YouTubeCreatorInsights) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.YouTubeCreatorInsights) private static final com.google.ads.googleads.v21.services.YouTubeCreatorInsights DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.YouTubeCreatorInsights(); } public static com.google.ads.googleads.v21.services.YouTubeCreatorInsights getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<YouTubeCreatorInsights> PARSER = new com.google.protobuf.AbstractParser<YouTubeCreatorInsights>() { @java.lang.Override public YouTubeCreatorInsights 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<YouTubeCreatorInsights> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<YouTubeCreatorInsights> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.services.YouTubeCreatorInsights getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,573
java-appengine-admin/proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/BatchUpdateIngressRulesRequest.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/appengine/v1/appengine.proto // Protobuf Java Version: 3.25.8 package com.google.appengine.v1; /** * * * <pre> * Request message for `Firewall.BatchUpdateIngressRules`. * </pre> * * Protobuf type {@code google.appengine.v1.BatchUpdateIngressRulesRequest} */ public final class BatchUpdateIngressRulesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.appengine.v1.BatchUpdateIngressRulesRequest) BatchUpdateIngressRulesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use BatchUpdateIngressRulesRequest.newBuilder() to construct. private BatchUpdateIngressRulesRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private BatchUpdateIngressRulesRequest() { name_ = ""; ingressRules_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new BatchUpdateIngressRulesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_BatchUpdateIngressRulesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_BatchUpdateIngressRulesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.appengine.v1.BatchUpdateIngressRulesRequest.class, com.google.appengine.v1.BatchUpdateIngressRulesRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</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> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</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 INGRESS_RULES_FIELD_NUMBER = 2; @SuppressWarnings("serial") private java.util.List<com.google.appengine.v1.firewall.FirewallRule> ingressRules_; /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ @java.lang.Override public java.util.List<com.google.appengine.v1.firewall.FirewallRule> getIngressRulesList() { return ingressRules_; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ @java.lang.Override public java.util.List<? extends com.google.appengine.v1.firewall.FirewallRuleOrBuilder> getIngressRulesOrBuilderList() { return ingressRules_; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ @java.lang.Override public int getIngressRulesCount() { return ingressRules_.size(); } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ @java.lang.Override public com.google.appengine.v1.firewall.FirewallRule getIngressRules(int index) { return ingressRules_.get(index); } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ @java.lang.Override public com.google.appengine.v1.firewall.FirewallRuleOrBuilder getIngressRulesOrBuilder( int index) { return ingressRules_.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(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } for (int i = 0; i < ingressRules_.size(); i++) { output.writeMessage(2, ingressRules_.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(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } for (int i = 0; i < ingressRules_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, ingressRules_.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.appengine.v1.BatchUpdateIngressRulesRequest)) { return super.equals(obj); } com.google.appengine.v1.BatchUpdateIngressRulesRequest other = (com.google.appengine.v1.BatchUpdateIngressRulesRequest) obj; if (!getName().equals(other.getName())) return false; if (!getIngressRulesList().equals(other.getIngressRulesList())) 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 (getIngressRulesCount() > 0) { hash = (37 * hash) + INGRESS_RULES_FIELD_NUMBER; hash = (53 * hash) + getIngressRulesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest 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.appengine.v1.BatchUpdateIngressRulesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest 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.appengine.v1.BatchUpdateIngressRulesRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest 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.appengine.v1.BatchUpdateIngressRulesRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest 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.appengine.v1.BatchUpdateIngressRulesRequest 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 `Firewall.BatchUpdateIngressRules`. * </pre> * * Protobuf type {@code google.appengine.v1.BatchUpdateIngressRulesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.appengine.v1.BatchUpdateIngressRulesRequest) com.google.appengine.v1.BatchUpdateIngressRulesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_BatchUpdateIngressRulesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_BatchUpdateIngressRulesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.appengine.v1.BatchUpdateIngressRulesRequest.class, com.google.appengine.v1.BatchUpdateIngressRulesRequest.Builder.class); } // Construct using com.google.appengine.v1.BatchUpdateIngressRulesRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; if (ingressRulesBuilder_ == null) { ingressRules_ = java.util.Collections.emptyList(); } else { ingressRules_ = null; ingressRulesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.appengine.v1.AppengineProto .internal_static_google_appengine_v1_BatchUpdateIngressRulesRequest_descriptor; } @java.lang.Override public com.google.appengine.v1.BatchUpdateIngressRulesRequest getDefaultInstanceForType() { return com.google.appengine.v1.BatchUpdateIngressRulesRequest.getDefaultInstance(); } @java.lang.Override public com.google.appengine.v1.BatchUpdateIngressRulesRequest build() { com.google.appengine.v1.BatchUpdateIngressRulesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.appengine.v1.BatchUpdateIngressRulesRequest buildPartial() { com.google.appengine.v1.BatchUpdateIngressRulesRequest result = new com.google.appengine.v1.BatchUpdateIngressRulesRequest(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.appengine.v1.BatchUpdateIngressRulesRequest result) { if (ingressRulesBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { ingressRules_ = java.util.Collections.unmodifiableList(ingressRules_); bitField0_ = (bitField0_ & ~0x00000002); } result.ingressRules_ = ingressRules_; } else { result.ingressRules_ = ingressRulesBuilder_.build(); } } private void buildPartial0(com.google.appengine.v1.BatchUpdateIngressRulesRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } } @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.appengine.v1.BatchUpdateIngressRulesRequest) { return mergeFrom((com.google.appengine.v1.BatchUpdateIngressRulesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.appengine.v1.BatchUpdateIngressRulesRequest other) { if (other == com.google.appengine.v1.BatchUpdateIngressRulesRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (ingressRulesBuilder_ == null) { if (!other.ingressRules_.isEmpty()) { if (ingressRules_.isEmpty()) { ingressRules_ = other.ingressRules_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureIngressRulesIsMutable(); ingressRules_.addAll(other.ingressRules_); } onChanged(); } } else { if (!other.ingressRules_.isEmpty()) { if (ingressRulesBuilder_.isEmpty()) { ingressRulesBuilder_.dispose(); ingressRulesBuilder_ = null; ingressRules_ = other.ingressRules_; bitField0_ = (bitField0_ & ~0x00000002); ingressRulesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getIngressRulesFieldBuilder() : null; } else { ingressRulesBuilder_.addAllMessages(other.ingressRules_); } } } 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: { com.google.appengine.v1.firewall.FirewallRule m = input.readMessage( com.google.appengine.v1.firewall.FirewallRule.parser(), extensionRegistry); if (ingressRulesBuilder_ == null) { ensureIngressRulesIsMutable(); ingressRules_.add(m); } else { ingressRulesBuilder_.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 name_ = ""; /** * * * <pre> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</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> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</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> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</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> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of the Firewall collection to set. * Example: `apps/myapp/firewall/ingressRules`. * </pre> * * <code>string name = 1;</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.util.List<com.google.appengine.v1.firewall.FirewallRule> ingressRules_ = java.util.Collections.emptyList(); private void ensureIngressRulesIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { ingressRules_ = new java.util.ArrayList<com.google.appengine.v1.firewall.FirewallRule>(ingressRules_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.appengine.v1.firewall.FirewallRule, com.google.appengine.v1.firewall.FirewallRule.Builder, com.google.appengine.v1.firewall.FirewallRuleOrBuilder> ingressRulesBuilder_; /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public java.util.List<com.google.appengine.v1.firewall.FirewallRule> getIngressRulesList() { if (ingressRulesBuilder_ == null) { return java.util.Collections.unmodifiableList(ingressRules_); } else { return ingressRulesBuilder_.getMessageList(); } } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public int getIngressRulesCount() { if (ingressRulesBuilder_ == null) { return ingressRules_.size(); } else { return ingressRulesBuilder_.getCount(); } } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public com.google.appengine.v1.firewall.FirewallRule getIngressRules(int index) { if (ingressRulesBuilder_ == null) { return ingressRules_.get(index); } else { return ingressRulesBuilder_.getMessage(index); } } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder setIngressRules(int index, com.google.appengine.v1.firewall.FirewallRule value) { if (ingressRulesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureIngressRulesIsMutable(); ingressRules_.set(index, value); onChanged(); } else { ingressRulesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder setIngressRules( int index, com.google.appengine.v1.firewall.FirewallRule.Builder builderForValue) { if (ingressRulesBuilder_ == null) { ensureIngressRulesIsMutable(); ingressRules_.set(index, builderForValue.build()); onChanged(); } else { ingressRulesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder addIngressRules(com.google.appengine.v1.firewall.FirewallRule value) { if (ingressRulesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureIngressRulesIsMutable(); ingressRules_.add(value); onChanged(); } else { ingressRulesBuilder_.addMessage(value); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder addIngressRules(int index, com.google.appengine.v1.firewall.FirewallRule value) { if (ingressRulesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureIngressRulesIsMutable(); ingressRules_.add(index, value); onChanged(); } else { ingressRulesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder addIngressRules( com.google.appengine.v1.firewall.FirewallRule.Builder builderForValue) { if (ingressRulesBuilder_ == null) { ensureIngressRulesIsMutable(); ingressRules_.add(builderForValue.build()); onChanged(); } else { ingressRulesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder addIngressRules( int index, com.google.appengine.v1.firewall.FirewallRule.Builder builderForValue) { if (ingressRulesBuilder_ == null) { ensureIngressRulesIsMutable(); ingressRules_.add(index, builderForValue.build()); onChanged(); } else { ingressRulesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder addAllIngressRules( java.lang.Iterable<? extends com.google.appengine.v1.firewall.FirewallRule> values) { if (ingressRulesBuilder_ == null) { ensureIngressRulesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, ingressRules_); onChanged(); } else { ingressRulesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder clearIngressRules() { if (ingressRulesBuilder_ == null) { ingressRules_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { ingressRulesBuilder_.clear(); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public Builder removeIngressRules(int index) { if (ingressRulesBuilder_ == null) { ensureIngressRulesIsMutable(); ingressRules_.remove(index); onChanged(); } else { ingressRulesBuilder_.remove(index); } return this; } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public com.google.appengine.v1.firewall.FirewallRule.Builder getIngressRulesBuilder(int index) { return getIngressRulesFieldBuilder().getBuilder(index); } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public com.google.appengine.v1.firewall.FirewallRuleOrBuilder getIngressRulesOrBuilder( int index) { if (ingressRulesBuilder_ == null) { return ingressRules_.get(index); } else { return ingressRulesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public java.util.List<? extends com.google.appengine.v1.firewall.FirewallRuleOrBuilder> getIngressRulesOrBuilderList() { if (ingressRulesBuilder_ != null) { return ingressRulesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(ingressRules_); } } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public com.google.appengine.v1.firewall.FirewallRule.Builder addIngressRulesBuilder() { return getIngressRulesFieldBuilder() .addBuilder(com.google.appengine.v1.firewall.FirewallRule.getDefaultInstance()); } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public com.google.appengine.v1.firewall.FirewallRule.Builder addIngressRulesBuilder(int index) { return getIngressRulesFieldBuilder() .addBuilder(index, com.google.appengine.v1.firewall.FirewallRule.getDefaultInstance()); } /** * * * <pre> * A list of FirewallRules to replace the existing set. * </pre> * * <code>repeated .google.appengine.v1.FirewallRule ingress_rules = 2;</code> */ public java.util.List<com.google.appengine.v1.firewall.FirewallRule.Builder> getIngressRulesBuilderList() { return getIngressRulesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.appengine.v1.firewall.FirewallRule, com.google.appengine.v1.firewall.FirewallRule.Builder, com.google.appengine.v1.firewall.FirewallRuleOrBuilder> getIngressRulesFieldBuilder() { if (ingressRulesBuilder_ == null) { ingressRulesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.appengine.v1.firewall.FirewallRule, com.google.appengine.v1.firewall.FirewallRule.Builder, com.google.appengine.v1.firewall.FirewallRuleOrBuilder>( ingressRules_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); ingressRules_ = null; } return ingressRulesBuilder_; } @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.appengine.v1.BatchUpdateIngressRulesRequest) } // @@protoc_insertion_point(class_scope:google.appengine.v1.BatchUpdateIngressRulesRequest) private static final com.google.appengine.v1.BatchUpdateIngressRulesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.appengine.v1.BatchUpdateIngressRulesRequest(); } public static com.google.appengine.v1.BatchUpdateIngressRulesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<BatchUpdateIngressRulesRequest> PARSER = new com.google.protobuf.AbstractParser<BatchUpdateIngressRulesRequest>() { @java.lang.Override public BatchUpdateIngressRulesRequest 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<BatchUpdateIngressRulesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<BatchUpdateIngressRulesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.appengine.v1.BatchUpdateIngressRulesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,599
java-apihub/proto-google-cloud-apihub-v1/src/main/java/com/google/cloud/apihub/v1/ListDeploymentsResponse.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/apihub/v1/apihub_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.apihub.v1; /** * * * <pre> * The [ListDeployments][google.cloud.apihub.v1.ApiHub.ListDeployments] method's * response. * </pre> * * Protobuf type {@code google.cloud.apihub.v1.ListDeploymentsResponse} */ public final class ListDeploymentsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.apihub.v1.ListDeploymentsResponse) ListDeploymentsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDeploymentsResponse.newBuilder() to construct. private ListDeploymentsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDeploymentsResponse() { deployments_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDeploymentsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDeploymentsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDeploymentsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apihub.v1.ListDeploymentsResponse.class, com.google.cloud.apihub.v1.ListDeploymentsResponse.Builder.class); } public static final int DEPLOYMENTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.apihub.v1.Deployment> deployments_; /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.apihub.v1.Deployment> getDeploymentsList() { return deployments_; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.apihub.v1.DeploymentOrBuilder> getDeploymentsOrBuilderList() { return deployments_; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ @java.lang.Override public int getDeploymentsCount() { return deployments_.size(); } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ @java.lang.Override public com.google.cloud.apihub.v1.Deployment getDeployments(int index) { return deployments_.get(index); } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ @java.lang.Override public com.google.cloud.apihub.v1.DeploymentOrBuilder getDeploymentsOrBuilder(int index) { return deployments_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, 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 < deployments_.size(); i++) { output.writeMessage(1, deployments_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; for (int i = 0; i < deployments_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, deployments_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.apihub.v1.ListDeploymentsResponse)) { return super.equals(obj); } com.google.cloud.apihub.v1.ListDeploymentsResponse other = (com.google.cloud.apihub.v1.ListDeploymentsResponse) obj; if (!getDeploymentsList().equals(other.getDeploymentsList())) return false; if (!getNextPageToken().equals(other.getNextPageToken())) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (getDeploymentsCount() > 0) { hash = (37 * hash) + DEPLOYMENTS_FIELD_NUMBER; hash = (53 * hash) + getDeploymentsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.apihub.v1.ListDeploymentsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse 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.apihub.v1.ListDeploymentsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse 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.apihub.v1.ListDeploymentsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse 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.apihub.v1.ListDeploymentsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse 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.apihub.v1.ListDeploymentsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse 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.apihub.v1.ListDeploymentsResponse 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 [ListDeployments][google.cloud.apihub.v1.ApiHub.ListDeployments] method's * response. * </pre> * * Protobuf type {@code google.cloud.apihub.v1.ListDeploymentsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.apihub.v1.ListDeploymentsResponse) com.google.cloud.apihub.v1.ListDeploymentsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDeploymentsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDeploymentsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.apihub.v1.ListDeploymentsResponse.class, com.google.cloud.apihub.v1.ListDeploymentsResponse.Builder.class); } // Construct using com.google.cloud.apihub.v1.ListDeploymentsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (deploymentsBuilder_ == null) { deployments_ = java.util.Collections.emptyList(); } else { deployments_ = null; deploymentsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.apihub.v1.ApiHubServiceProto .internal_static_google_cloud_apihub_v1_ListDeploymentsResponse_descriptor; } @java.lang.Override public com.google.cloud.apihub.v1.ListDeploymentsResponse getDefaultInstanceForType() { return com.google.cloud.apihub.v1.ListDeploymentsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.apihub.v1.ListDeploymentsResponse build() { com.google.cloud.apihub.v1.ListDeploymentsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.apihub.v1.ListDeploymentsResponse buildPartial() { com.google.cloud.apihub.v1.ListDeploymentsResponse result = new com.google.cloud.apihub.v1.ListDeploymentsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.apihub.v1.ListDeploymentsResponse result) { if (deploymentsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { deployments_ = java.util.Collections.unmodifiableList(deployments_); bitField0_ = (bitField0_ & ~0x00000001); } result.deployments_ = deployments_; } else { result.deployments_ = deploymentsBuilder_.build(); } } private void buildPartial0(com.google.cloud.apihub.v1.ListDeploymentsResponse 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.apihub.v1.ListDeploymentsResponse) { return mergeFrom((com.google.cloud.apihub.v1.ListDeploymentsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.apihub.v1.ListDeploymentsResponse other) { if (other == com.google.cloud.apihub.v1.ListDeploymentsResponse.getDefaultInstance()) return this; if (deploymentsBuilder_ == null) { if (!other.deployments_.isEmpty()) { if (deployments_.isEmpty()) { deployments_ = other.deployments_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDeploymentsIsMutable(); deployments_.addAll(other.deployments_); } onChanged(); } } else { if (!other.deployments_.isEmpty()) { if (deploymentsBuilder_.isEmpty()) { deploymentsBuilder_.dispose(); deploymentsBuilder_ = null; deployments_ = other.deployments_; bitField0_ = (bitField0_ & ~0x00000001); deploymentsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDeploymentsFieldBuilder() : null; } else { deploymentsBuilder_.addAllMessages(other.deployments_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.apihub.v1.Deployment m = input.readMessage( com.google.cloud.apihub.v1.Deployment.parser(), extensionRegistry); if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.add(m); } else { deploymentsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.apihub.v1.Deployment> deployments_ = java.util.Collections.emptyList(); private void ensureDeploymentsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { deployments_ = new java.util.ArrayList<com.google.cloud.apihub.v1.Deployment>(deployments_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apihub.v1.Deployment, com.google.cloud.apihub.v1.Deployment.Builder, com.google.cloud.apihub.v1.DeploymentOrBuilder> deploymentsBuilder_; /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public java.util.List<com.google.cloud.apihub.v1.Deployment> getDeploymentsList() { if (deploymentsBuilder_ == null) { return java.util.Collections.unmodifiableList(deployments_); } else { return deploymentsBuilder_.getMessageList(); } } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public int getDeploymentsCount() { if (deploymentsBuilder_ == null) { return deployments_.size(); } else { return deploymentsBuilder_.getCount(); } } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public com.google.cloud.apihub.v1.Deployment getDeployments(int index) { if (deploymentsBuilder_ == null) { return deployments_.get(index); } else { return deploymentsBuilder_.getMessage(index); } } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder setDeployments(int index, com.google.cloud.apihub.v1.Deployment value) { if (deploymentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDeploymentsIsMutable(); deployments_.set(index, value); onChanged(); } else { deploymentsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder setDeployments( int index, com.google.cloud.apihub.v1.Deployment.Builder builderForValue) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.set(index, builderForValue.build()); onChanged(); } else { deploymentsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder addDeployments(com.google.cloud.apihub.v1.Deployment value) { if (deploymentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDeploymentsIsMutable(); deployments_.add(value); onChanged(); } else { deploymentsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder addDeployments(int index, com.google.cloud.apihub.v1.Deployment value) { if (deploymentsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDeploymentsIsMutable(); deployments_.add(index, value); onChanged(); } else { deploymentsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder addDeployments(com.google.cloud.apihub.v1.Deployment.Builder builderForValue) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.add(builderForValue.build()); onChanged(); } else { deploymentsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder addDeployments( int index, com.google.cloud.apihub.v1.Deployment.Builder builderForValue) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.add(index, builderForValue.build()); onChanged(); } else { deploymentsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder addAllDeployments( java.lang.Iterable<? extends com.google.cloud.apihub.v1.Deployment> values) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, deployments_); onChanged(); } else { deploymentsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder clearDeployments() { if (deploymentsBuilder_ == null) { deployments_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { deploymentsBuilder_.clear(); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public Builder removeDeployments(int index) { if (deploymentsBuilder_ == null) { ensureDeploymentsIsMutable(); deployments_.remove(index); onChanged(); } else { deploymentsBuilder_.remove(index); } return this; } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public com.google.cloud.apihub.v1.Deployment.Builder getDeploymentsBuilder(int index) { return getDeploymentsFieldBuilder().getBuilder(index); } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public com.google.cloud.apihub.v1.DeploymentOrBuilder getDeploymentsOrBuilder(int index) { if (deploymentsBuilder_ == null) { return deployments_.get(index); } else { return deploymentsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public java.util.List<? extends com.google.cloud.apihub.v1.DeploymentOrBuilder> getDeploymentsOrBuilderList() { if (deploymentsBuilder_ != null) { return deploymentsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(deployments_); } } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public com.google.cloud.apihub.v1.Deployment.Builder addDeploymentsBuilder() { return getDeploymentsFieldBuilder() .addBuilder(com.google.cloud.apihub.v1.Deployment.getDefaultInstance()); } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public com.google.cloud.apihub.v1.Deployment.Builder addDeploymentsBuilder(int index) { return getDeploymentsFieldBuilder() .addBuilder(index, com.google.cloud.apihub.v1.Deployment.getDefaultInstance()); } /** * * * <pre> * The deployment resources present in the API hub. * </pre> * * <code>repeated .google.cloud.apihub.v1.Deployment deployments = 1;</code> */ public java.util.List<com.google.cloud.apihub.v1.Deployment.Builder> getDeploymentsBuilderList() { return getDeploymentsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apihub.v1.Deployment, com.google.cloud.apihub.v1.Deployment.Builder, com.google.cloud.apihub.v1.DeploymentOrBuilder> getDeploymentsFieldBuilder() { if (deploymentsBuilder_ == null) { deploymentsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.apihub.v1.Deployment, com.google.cloud.apihub.v1.Deployment.Builder, com.google.cloud.apihub.v1.DeploymentOrBuilder>( deployments_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); deployments_ = null; } return deploymentsBuilder_; } 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.apihub.v1.ListDeploymentsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.apihub.v1.ListDeploymentsResponse) private static final com.google.cloud.apihub.v1.ListDeploymentsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.apihub.v1.ListDeploymentsResponse(); } public static com.google.cloud.apihub.v1.ListDeploymentsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDeploymentsResponse> PARSER = new com.google.protobuf.AbstractParser<ListDeploymentsResponse>() { @java.lang.Override public ListDeploymentsResponse 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<ListDeploymentsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDeploymentsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.apihub.v1.ListDeploymentsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/commons-math
36,986
commons-math-legacy/src/main/java/org/apache/commons/math4/legacy/linear/FieldMatrix.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.math4.legacy.linear; import org.apache.commons.math4.legacy.core.Field; import org.apache.commons.math4.legacy.core.FieldElement; import org.apache.commons.math4.legacy.exception.DimensionMismatchException; import org.apache.commons.math4.legacy.exception.NoDataException; import org.apache.commons.math4.legacy.exception.NotPositiveException; import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException; import org.apache.commons.math4.legacy.exception.NullArgumentException; import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException; import org.apache.commons.math4.legacy.exception.OutOfRangeException; /** * Interface defining field-valued matrix with basic algebraic operations. * <p> * Matrix element indexing is 0-based -- e.g., <code>getEntry(0, 0)</code> * returns the element in the first row, first column of the matrix.</p> * * @param <T> the type of the field elements */ public interface FieldMatrix<T extends FieldElement<T>> extends AnyMatrix { /** * Get the type of field elements of the matrix. * * @return the type of field elements of the matrix. */ Field<T> getField(); /** * Create a new {@code FieldMatrix<T>} of the same type as the instance with * the supplied row and column dimensions. * * @param rowDimension the number of rows in the new matrix * @param columnDimension the number of columns in the new matrix * @return a new matrix of the same type as the instance * @throws NotStrictlyPositiveException if row or column dimension is not * positive. * @since 2.0 */ FieldMatrix<T> createMatrix(int rowDimension, int columnDimension) throws NotStrictlyPositiveException; /** * Make a (deep) copy of this. * * @return a copy of this matrix. */ FieldMatrix<T> copy(); /** * Compute the sum of this and m. * * @param m Matrix to be added. * @return {@code this} + {@code m}. * @throws MatrixDimensionMismatchException if {@code m} is not the same * size as {@code this} matrix. */ FieldMatrix<T> add(FieldMatrix<T> m) throws MatrixDimensionMismatchException; /** * Subtract {@code m} from this matrix. * * @param m Matrix to be subtracted. * @return {@code this} - {@code m}. * @throws MatrixDimensionMismatchException if {@code m} is not the same * size as {@code this} matrix. */ FieldMatrix<T> subtract(FieldMatrix<T> m) throws MatrixDimensionMismatchException; /** * Increment each entry of this matrix. * * @param d Value to be added to each entry. * @return {@code d} + {@code this}. */ FieldMatrix<T> scalarAdd(T d); /** * Multiply each entry by {@code d}. * * @param d Value to multiply all entries by. * @return {@code d} * {@code this}. */ FieldMatrix<T> scalarMultiply(T d); /** * Postmultiply this matrix by {@code m}. * * @param m Matrix to postmultiply by. * @return {@code this} * {@code m}. * @throws DimensionMismatchException if the number of columns of * {@code this} matrix is not equal to the number of rows of matrix * {@code m}. */ FieldMatrix<T> multiply(FieldMatrix<T> m) throws DimensionMismatchException; /** * Premultiply this matrix by {@code m}. * * @param m Matrix to premultiply by. * @return {@code m} * {@code this}. * @throws DimensionMismatchException if the number of columns of {@code m} * differs from the number of rows of {@code this} matrix. */ FieldMatrix<T> preMultiply(FieldMatrix<T> m) throws DimensionMismatchException; /** * Returns the result multiplying this with itself <code>p</code> times. * Depending on the type of the field elements, T, instability for high * powers might occur. * * @param p raise this to power p * @return this^p * @throws NotPositiveException if {@code p < 0} * @throws NonSquareMatrixException if {@code this matrix} is not square */ FieldMatrix<T> power(int p) throws NonSquareMatrixException, NotPositiveException; /** * Returns matrix entries as a two-dimensional array. * * @return a 2-dimensional array of entries. */ T[][] getData(); /** * Get a submatrix. Rows and columns are indicated * counting from 0 to n - 1. * * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index (inclusive) * @return the matrix containing the data of the specified rows and columns. * @throws NumberIsTooSmallException is {@code endRow < startRow} of * {@code endColumn < startColumn}. * @throws OutOfRangeException if the indices are not valid. */ FieldMatrix<T> getSubMatrix(int startRow, int endRow, int startColumn, int endColumn) throws NumberIsTooSmallException, OutOfRangeException; /** * Get a submatrix. Rows and columns are indicated * counting from 0 to n - 1. * * @param selectedRows Array of row indices. * @param selectedColumns Array of column indices. * @return the matrix containing the data in the * specified rows and columns. * @throws NoDataException if {@code selectedRows} or * {@code selectedColumns} is empty * @throws NullArgumentException if {@code selectedRows} or * {@code selectedColumns} is {@code null}. * @throws OutOfRangeException if row or column selections are not valid. */ FieldMatrix<T> getSubMatrix(int[] selectedRows, int[] selectedColumns) throws NoDataException, NullArgumentException, OutOfRangeException; /** * Copy a submatrix. Rows and columns are 0-based. The designated submatrix * is copied into the top left portion of the destination array. * * @param startRow Initial row index. * @param endRow Final row index (inclusive). * @param startColumn Initial column index. * @param endColumn Final column index (inclusive). * @param destination The array where the submatrix data should be copied * (if larger than rows/columns counts, only the upper-left part will be modified). * @throws MatrixDimensionMismatchException if the dimensions of * {@code destination} are not large enough to hold the submatrix. * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @throws OutOfRangeException if the indices are not valid. */ void copySubMatrix(int startRow, int endRow, int startColumn, int endColumn, T[][] destination) throws MatrixDimensionMismatchException, NumberIsTooSmallException, OutOfRangeException; /** * Copy a submatrix. Rows and columns are indicated * counting from 0 to n - 1. * * @param selectedRows Array of row indices. * @param selectedColumns Array of column indices. * @param destination Arrays where the submatrix data should be copied * (if larger than rows/columns counts, only the upper-left part will be used) * @throws MatrixDimensionMismatchException if the dimensions of * {@code destination} do not match those of {@code this}. * @throws NoDataException if {@code selectedRows} or * {@code selectedColumns} is empty * @throws NullArgumentException if {@code selectedRows} or * {@code selectedColumns} is {@code null}. * @throws OutOfRangeException if the indices are not valid. */ void copySubMatrix(int[] selectedRows, int[] selectedColumns, T[][] destination) throws MatrixDimensionMismatchException, NoDataException, NullArgumentException, OutOfRangeException; /** * Replace the submatrix starting at {@code (row, column)} using data in the * input {@code subMatrix} array. Indexes are 0-based. * <p> * Example:<br> * Starting with * * <pre> * 1 2 3 4 * 5 6 7 8 * 9 0 1 2 * </pre> * * and <code>subMatrix = {{3, 4} {5,6}}</code>, invoking * <code>setSubMatrix(subMatrix,1,1))</code> will result in * * <pre> * 1 2 3 4 * 5 3 4 8 * 9 5 6 2 * </pre> * * * @param subMatrix Array containing the submatrix replacement data. * @param row Row coordinate of the top-left element to be replaced. * @param column Column coordinate of the top-left element to be replaced. * @throws OutOfRangeException if {@code subMatrix} does not fit into this * matrix from element in {@code (row, column)}. * @throws NoDataException if a row or column of {@code subMatrix} is empty. * @throws DimensionMismatchException if {@code subMatrix} is not * rectangular (not all rows have the same length). * @throws NullArgumentException if {@code subMatrix} is {@code null}. * @since 2.0 */ void setSubMatrix(T[][] subMatrix, int row, int column) throws DimensionMismatchException, OutOfRangeException, NoDataException, NullArgumentException; /** * Get the entries in row number {@code row} * as a row matrix. * * @param row Row to be fetched. * @return a row matrix. * @throws OutOfRangeException if the specified row index is invalid. */ FieldMatrix<T> getRowMatrix(int row) throws OutOfRangeException; /** * Set the entries in row number {@code row} * as a row matrix. * * @param row Row to be set. * @param matrix Row matrix (must have one row and the same number * of columns as the instance). * @throws OutOfRangeException if the specified row index is invalid. * @throws MatrixDimensionMismatchException * if the matrix dimensions do not match one instance row. */ void setRowMatrix(int row, FieldMatrix<T> matrix) throws MatrixDimensionMismatchException, OutOfRangeException; /** * Get the entries in column number {@code column} * as a column matrix. * * @param column Column to be fetched. * @return a column matrix. * @throws OutOfRangeException if the specified column index is invalid. */ FieldMatrix<T> getColumnMatrix(int column) throws OutOfRangeException; /** * Set the entries in column number {@code column} * as a column matrix. * * @param column Column to be set. * @param matrix column matrix (must have one column and the same * number of rows as the instance). * @throws OutOfRangeException if the specified column index is invalid. * @throws MatrixDimensionMismatchException if the matrix dimensions do * not match one instance column. */ void setColumnMatrix(int column, FieldMatrix<T> matrix) throws MatrixDimensionMismatchException, OutOfRangeException; /** * Get the entries in row number {@code row} * as a vector. * * @param row Row to be fetched * @return a row vector. * @throws OutOfRangeException if the specified row index is invalid. */ FieldVector<T> getRowVector(int row) throws OutOfRangeException; /** * Set the entries in row number {@code row} * as a vector. * * @param row Row to be set. * @param vector row vector (must have the same number of columns * as the instance). * @throws OutOfRangeException if the specified row index is invalid. * @throws MatrixDimensionMismatchException if the vector dimension does not * match one instance row. */ void setRowVector(int row, FieldVector<T> vector) throws MatrixDimensionMismatchException, OutOfRangeException; /** * Returns the entries in column number {@code column} * as a vector. * * @param column Column to be fetched. * @return a column vector. * @throws OutOfRangeException if the specified column index is invalid. */ FieldVector<T> getColumnVector(int column) throws OutOfRangeException; /** * Set the entries in column number {@code column} * as a vector. * * @param column Column to be set. * @param vector Column vector (must have the same number of rows * as the instance). * @throws OutOfRangeException if the specified column index is invalid. * @throws MatrixDimensionMismatchException if the vector dimension does not * match one instance column. */ void setColumnVector(int column, FieldVector<T> vector) throws MatrixDimensionMismatchException, OutOfRangeException; /** * Get the entries in row number {@code row} as an array. * * @param row Row to be fetched. * @return array of entries in the row. * @throws OutOfRangeException if the specified row index is not valid. */ T[] getRow(int row) throws OutOfRangeException; /** * Set the entries in row number {@code row} * as a row matrix. * * @param row Row to be set. * @param array Row matrix (must have the same number of columns as * the instance). * @throws OutOfRangeException if the specified row index is invalid. * @throws MatrixDimensionMismatchException if the array size does not match * one instance row. */ void setRow(int row, T[] array) throws MatrixDimensionMismatchException, OutOfRangeException; /** * Get the entries in column number {@code col} as an array. * * @param column the column to be fetched * @return array of entries in the column * @throws OutOfRangeException if the specified column index is not valid. */ T[] getColumn(int column) throws OutOfRangeException; /** * Set the entries in column number {@code column} * as a column matrix. * * @param column the column to be set * @param array column array (must have the same number of rows as the instance) * @throws OutOfRangeException if the specified column index is invalid. * @throws MatrixDimensionMismatchException if the array size does not match * one instance column. */ void setColumn(int column, T[] array) throws MatrixDimensionMismatchException, OutOfRangeException; /** * Returns the entry in the specified row and column. * * @param row row location of entry to be fetched * @param column column location of entry to be fetched * @return matrix entry in row,column * @throws OutOfRangeException if the row or column index is not valid. */ T getEntry(int row, int column) throws OutOfRangeException; /** * Set the entry in the specified row and column. * * @param row row location of entry to be set * @param column column location of entry to be set * @param value matrix entry to be set in row,column * @throws OutOfRangeException if the row or column index is not valid. * @since 2.0 */ void setEntry(int row, int column, T value) throws OutOfRangeException; /** * Change an entry in the specified row and column. * * @param row Row location of entry to be set. * @param column Column location of entry to be set. * @param increment Value to add to the current matrix entry in * {@code (row, column)}. * @throws OutOfRangeException if the row or column index is not valid. * @since 2.0 */ void addToEntry(int row, int column, T increment) throws OutOfRangeException; /** * Change an entry in the specified row and column. * * @param row Row location of entry to be set. * @param column Column location of entry to be set. * @param factor Multiplication factor for the current matrix entry * in {@code (row,column)} * @throws OutOfRangeException if the row or column index is not valid. * @since 2.0 */ void multiplyEntry(int row, int column, T factor) throws OutOfRangeException; /** * Returns the transpose of this matrix. * * @return transpose matrix */ FieldMatrix<T> transpose(); /** * Returns the <a href="http://mathworld.wolfram.com/MatrixTrace.html"> * trace</a> of the matrix (the sum of the elements on the main diagonal). * * @return trace * @throws NonSquareMatrixException if the matrix is not square. */ T getTrace() throws NonSquareMatrixException; /** * Returns the result of multiplying this by the vector {@code v}. * * @param v the vector to operate on * @return {@code this * v} * @throws DimensionMismatchException if the number of columns of * {@code this} matrix is not equal to the size of the vector {@code v}. */ T[] operate(T[] v) throws DimensionMismatchException; /** * Returns the result of multiplying this by the vector {@code v}. * * @param v the vector to operate on * @return {@code this * v} * @throws DimensionMismatchException if the number of columns of * {@code this} matrix is not equal to the size of the vector {@code v}. */ FieldVector<T> operate(FieldVector<T> v) throws DimensionMismatchException; /** * Returns the (row) vector result of premultiplying this by the vector * {@code v}. * * @param v the row vector to premultiply by * @return {@code v * this} * @throws DimensionMismatchException if the number of rows of {@code this} * matrix is not equal to the size of the vector {@code v} */ T[] preMultiply(T[] v) throws DimensionMismatchException; /** * Returns the (row) vector result of premultiplying this by the vector * {@code v}. * * @param v the row vector to premultiply by * @return {@code v * this} * @throws DimensionMismatchException if the number of rows of {@code this} * matrix is not equal to the size of the vector {@code v} */ FieldVector<T> preMultiply(FieldVector<T> v) throws DimensionMismatchException; /** * Visit (and possibly change) all matrix entries in row order. * <p>Row order starts at upper left and iterating through all elements * of a row from left to right before going to the leftmost element * of the next row.</p> * @param visitor visitor used to process all matrix entries * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end * of the walk */ T walkInRowOrder(FieldMatrixChangingVisitor<T> visitor); /** * Visit (but don't change) all matrix entries in row order. * <p>Row order starts at upper left and iterating through all elements * of a row from left to right before going to the leftmost element * of the next row.</p> * @param visitor visitor used to process all matrix entries * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end * of the walk */ T walkInRowOrder(FieldMatrixPreservingVisitor<T> visitor); /** * Visit (and possibly change) some matrix entries in row order. * <p>Row order starts at upper left and iterating through all elements * of a row from left to right before going to the leftmost element * of the next row.</p> * @param visitor visitor used to process all matrix entries * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index * @throws OutOfRangeException if the indices are not valid. * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end * of the walk */ T walkInRowOrder(FieldMatrixChangingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn) throws OutOfRangeException, NumberIsTooSmallException; /** * Visit (but don't change) some matrix entries in row order. * <p>Row order starts at upper left and iterating through all elements * of a row from left to right before going to the leftmost element * of the next row.</p> * @param visitor visitor used to process all matrix entries * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index * @throws OutOfRangeException if the indices are not valid. * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end * of the walk */ T walkInRowOrder(FieldMatrixPreservingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn) throws OutOfRangeException, NumberIsTooSmallException; /** * Visit (and possibly change) all matrix entries in column order. * <p>Column order starts at upper left and iterating through all elements * of a column from top to bottom before going to the topmost element * of the next column.</p> * @param visitor visitor used to process all matrix entries * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end * of the walk */ T walkInColumnOrder(FieldMatrixChangingVisitor<T> visitor); /** * Visit (but don't change) all matrix entries in column order. * <p>Column order starts at upper left and iterating through all elements * of a column from top to bottom before going to the topmost element * of the next column.</p> * @param visitor visitor used to process all matrix entries * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end * of the walk */ T walkInColumnOrder(FieldMatrixPreservingVisitor<T> visitor); /** * Visit (and possibly change) some matrix entries in column order. * <p>Column order starts at upper left and iterating through all elements * of a column from top to bottom before going to the topmost element * of the next column.</p> * @param visitor visitor used to process all matrix entries * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @throws OutOfRangeException if the indices are not valid. * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end * of the walk */ T walkInColumnOrder(FieldMatrixChangingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn) throws NumberIsTooSmallException, OutOfRangeException; /** * Visit (but don't change) some matrix entries in column order. * <p>Column order starts at upper left and iterating through all elements * of a column from top to bottom before going to the topmost element * of the next column.</p> * @param visitor visitor used to process all matrix entries * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @throws OutOfRangeException if the indices are not valid. * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end * of the walk */ T walkInColumnOrder(FieldMatrixPreservingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn) throws NumberIsTooSmallException, OutOfRangeException; /** * Visit (and possibly change) all matrix entries using the fastest possible order. * <p>The fastest walking order depends on the exact matrix class. It may be * different from traditional row or column orders.</p> * @param visitor visitor used to process all matrix entries * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end * of the walk */ T walkInOptimizedOrder(FieldMatrixChangingVisitor<T> visitor); /** * Visit (but don't change) all matrix entries using the fastest possible order. * <p>The fastest walking order depends on the exact matrix class. It may be * different from traditional row or column orders.</p> * @param visitor visitor used to process all matrix entries * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end * of the walk */ T walkInOptimizedOrder(FieldMatrixPreservingVisitor<T> visitor); /** * Visit (and possibly change) some matrix entries using the fastest possible order. * <p>The fastest walking order depends on the exact matrix class. It may be * different from traditional row or column orders.</p> * @param visitor visitor used to process all matrix entries * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index (inclusive) * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @throws OutOfRangeException if the indices are not valid. * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixChangingVisitor#end()} at the end * of the walk */ T walkInOptimizedOrder(FieldMatrixChangingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn) throws NumberIsTooSmallException, OutOfRangeException; /** * Visit (but don't change) some matrix entries using the fastest possible order. * <p>The fastest walking order depends on the exact matrix class. It may be * different from traditional row or column orders.</p> * @param visitor visitor used to process all matrix entries * @param startRow Initial row index * @param endRow Final row index (inclusive) * @param startColumn Initial column index * @param endColumn Final column index (inclusive) * @throws NumberIsTooSmallException if {@code endRow < startRow} or * {@code endColumn < startColumn}. * @throws OutOfRangeException if the indices are not valid. * @see #walkInRowOrder(FieldMatrixChangingVisitor) * @see #walkInRowOrder(FieldMatrixPreservingVisitor) * @see #walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixChangingVisitor) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor) * @see #walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int) * @see #walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor) * @see #walkInOptimizedOrder(FieldMatrixPreservingVisitor) * @see #walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int) * @return the value returned by {@link FieldMatrixPreservingVisitor#end()} at the end * of the walk */ T walkInOptimizedOrder(FieldMatrixPreservingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn) throws NumberIsTooSmallException, OutOfRangeException; }
apache/jclouds
36,404
apis/ec2/src/test/java/org/jclouds/ec2/features/AMIApiTest.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.jclouds.ec2.features; import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.executableBy; import static org.jclouds.reflect.Reflection2.method; import java.io.IOException; import org.jclouds.Fallbacks.EmptySetOnNotFoundOr404; import org.jclouds.ec2.options.CreateImageOptions; import org.jclouds.ec2.options.DescribeImagesOptions; import org.jclouds.ec2.options.RegisterImageBackedByEbsOptions; import org.jclouds.ec2.options.RegisterImageOptions; import org.jclouds.ec2.xml.BlockDeviceMappingHandler; import org.jclouds.ec2.xml.DescribeImagesResponseHandler; import org.jclouds.ec2.xml.ImageIdHandler; import org.jclouds.ec2.xml.PermissionHandler; import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.rest.internal.GeneratedHttpRequest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.reflect.Invokable; /** * Tests behavior of {@code AMIApi} */ // NOTE:without testName, this will not call @Before* and fail w/NPE during surefire @Test(groups = "unit", testName = "AMIApiTest") public class AMIApiTest extends BaseEC2ApiTest<AMIApi> { HttpRequest createImage = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "CreateImage") .addFormParam("InstanceId", "instanceId") .addFormParam("Name", "name") .addFormParam("Signature", "MuMtOMs697BLVks2RUZUNeLdVCo6NXPHuDhh0nmNtvc=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testCreateImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "createImageInRegion", String.class, String.class, String.class, CreateImageOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "name", "instanceId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, createImage.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest createImageOptions = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "CreateImage") .addFormParam("Description", "description") .addFormParam("InstanceId", "instanceId") .addFormParam("Name", "name") .addFormParam("NoReboot", "true") .addFormParam("Signature", "8SgbaWihxOICMXDLvwk3ahy/99nhZvTvbno+8dMyvJg=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testCreateImageOptions() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "createImageInRegion", String.class, String.class, String.class, CreateImageOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "name", "instanceId", new CreateImageOptions() .withDescription("description").noReboot())); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, createImageOptions.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest describeImages = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "DescribeImages") .addFormParam("Signature", "hQxNAaRVX6OvXV0IKgx1vV0FoNbRyuHQ2fhRhaPJnS8=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testDescribeImages() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "describeImagesInRegion", String.class, DescribeImagesOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null)); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, describeImages.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeImagesResponseHandler.class); assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); checkFilters(request); } HttpRequest describeImagesOptions = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "DescribeImages") .addFormParam("ExecutableBy", "me") .addFormParam("ImageId.1", "1") .addFormParam("ImageId.2", "2") .addFormParam("Owner.1", "fred") .addFormParam("Owner.2", "nancy") .addFormParam("Signature", "cIft3g1fwMu52NgB0En9NtHyXjVhmeSx7TBP7YR+TvI=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testDescribeImagesOptions() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "describeImagesInRegion", String.class, DescribeImagesOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, executableBy("me").ownedBy("fred", "nancy").imageIds( "1", "2"))); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, describeImagesOptions.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, DescribeImagesResponseHandler.class); assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class); checkFilters(request); } HttpRequest deregisterImage = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "DeregisterImage") .addFormParam("ImageId", "imageId") .addFormParam("Signature", "tm6nGoPPJh7xt5TSdV5Ov0DJvcGTAW+YSfXL7j+TkOA=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testDeregisterImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "deregisterImageInRegion", String.class, String.class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "imageId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, deregisterImage.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest registerImageFromManifest = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "RegisterImage") .addFormParam("ImageLocation", "pathToManifest") .addFormParam("Name", "name") .addFormParam("Signature", "Ie7k7w4Bdki3uCGeSFGdJ5EKrp/ohkHvWwivbIaVLEM=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testRegisterImageFromManifest() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "registerImageFromManifestInRegion", String.class, String.class, String.class, RegisterImageOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "name", "pathToManifest")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, registerImageFromManifest.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest registerImageFromManifestOptions = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "RegisterImage") .addFormParam("Description", "description") .addFormParam("ImageLocation", "pathToManifest") .addFormParam("Name", "name") .addFormParam("Signature", "ilWV1eAWW6kTK/jHliQ+IkzJR4DRNy4ye+SKtnUjjDs=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testRegisterImageFromManifestOptions() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "registerImageFromManifestInRegion", String.class, String.class, String.class, RegisterImageOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "name", "pathToManifest", new RegisterImageOptions() .withDescription("description"))); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, registerImageFromManifestOptions.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest registerImageBackedByEBS = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "RegisterImage") .addFormParam("BlockDeviceMapping.0.DeviceName", "/dev/sda1") .addFormParam("BlockDeviceMapping.0.Ebs.SnapshotId", "snapshotId") .addFormParam("Name", "imageName") .addFormParam("RootDeviceName", "/dev/sda1") .addFormParam("Signature", "ZbZcY6uwxPbD65jFmiNZXoWeHY/2zqRuGuDmTfkt84A=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testRegisterImageBackedByEBS() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "registerUnixImageBackedByEbsInRegion", String.class, String.class, String.class, RegisterImageBackedByEbsOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "imageName", "snapshotId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, registerImageBackedByEBS.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest registerImageBackedByEBSOptions = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "RegisterImage") .addFormParam("BlockDeviceMapping.0.DeviceName", "/dev/sda1") .addFormParam("BlockDeviceMapping.0.Ebs.SnapshotId", "snapshotId") .addFormParam("BlockDeviceMapping.1.DeviceName", "/dev/device") .addFormParam("BlockDeviceMapping.1.Ebs.DeleteOnTermination", "false") .addFormParam("BlockDeviceMapping.1.Ebs.SnapshotId", "snapshot") .addFormParam("BlockDeviceMapping.2.DeviceName", "/dev/newdevice") .addFormParam("BlockDeviceMapping.2.Ebs.DeleteOnTermination", "false") .addFormParam("BlockDeviceMapping.2.Ebs.VolumeSize", "100") .addFormParam("BlockDeviceMapping.2.VirtualName", "newblock") .addFormParam("Description", "description") .addFormParam("Name", "imageName") .addFormParam("RootDeviceName", "/dev/sda1") .addFormParam("Signature", "DrNujyZMGrKvuw73A7ObFTThXvc/MRfNqjvIy8gey5g=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testRegisterImageBackedByEBSOptions() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "registerUnixImageBackedByEbsInRegion", String.class, String.class, String.class, RegisterImageBackedByEbsOptions[].class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "imageName", "snapshotId", new RegisterImageBackedByEbsOptions().withDescription("description").addBlockDeviceFromSnapshot( "/dev/device", null, "snapshot").addNewBlockDevice("/dev/newdevice", "newblock", 100))); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, registerImageBackedByEBSOptions.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest getBlockDeviceMappingsForImage = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "DescribeImageAttribute") .addFormParam("Attribute", "blockDeviceMapping") .addFormParam("ImageId", "imageId") .addFormParam("Signature", "MJCIc1roG+nIWxRSUqV9KP9Wc4AWuuiNkxeDSih5/mI=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testGetBlockDeviceMappingsForImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "getBlockDeviceMappingsForImageInRegion", String.class, String.class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "imageId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, getBlockDeviceMappingsForImage.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, BlockDeviceMappingHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest getLaunchPermissionForImage = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "DescribeImageAttribute") .addFormParam("Attribute", "launchPermission") .addFormParam("ImageId", "imageId") .addFormParam("Signature", "iN7JbsAhM1NAES3o+Ow8BaaFJ+1g9imBjcU4mFCyrxM=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testGetLaunchPermissionForImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "getLaunchPermissionForImageInRegion", String.class, String.class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "imageId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, getLaunchPermissionForImage.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, PermissionHandler.class); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest addLaunchPermission = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "ModifyImageAttribute") .addFormParam("Attribute", "launchPermission") .addFormParam("ImageId", "imageId") .addFormParam("OperationType", "add") .addFormParam("Signature", "ZuMuzW/iQDRURhUJaBzvoAdNJrE454y6X0jM24lcxxk=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("UserGroup.1", "all") .addFormParam("UserId.1", "bob") .addFormParam("UserId.2", "sue") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testAddLaunchPermissionsToImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "addLaunchPermissionsToImageInRegion", String.class, Iterable.class, Iterable.class, String.class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ImmutableList.of("bob", "sue"), ImmutableList .of("all"), "imageId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, addLaunchPermission.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest removeLaunchPermission = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "ModifyImageAttribute") .addFormParam("Attribute", "launchPermission") .addFormParam("ImageId", "imageId") .addFormParam("OperationType", "remove") .addFormParam("Signature", "HreSEawbVaUp/UMicCJbhrx+moX01f2pEphJCPz8/5g=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("UserGroup.1", "all") .addFormParam("UserId.1", "bob") .addFormParam("UserId.2", "sue") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testRemoveLaunchPermissionsFromImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "removeLaunchPermissionsFromImageInRegion", String.class, Iterable.class, Iterable.class, String.class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ImmutableList.of("bob", "sue"), ImmutableList .of("all"), "imageId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, removeLaunchPermission.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertFallbackClassEquals(method, null); checkFilters(request); } HttpRequest resetLaunchPermissionsOnImage = HttpRequest.builder().method("POST") .endpoint("https://ec2.us-east-1.amazonaws.com/") .addHeader("Host", "ec2.us-east-1.amazonaws.com") .addFormParam("Action", "ResetImageAttribute") .addFormParam("Attribute", "launchPermission") .addFormParam("ImageId", "imageId") .addFormParam("Signature", "fVCR9aGYvNX/Jt1/uqBGcUQRLrHwxtcvmNYKzpul1P4=") .addFormParam("SignatureMethod", "HmacSHA256") .addFormParam("SignatureVersion", "2") .addFormParam("Timestamp", "2009-11-08T15:54:08.897Z") .addFormParam("Version", "2010-08-31") .addFormParam("AWSAccessKeyId", "identity").build(); public void testResetLaunchPermissionsOnImage() throws SecurityException, NoSuchMethodException, IOException { Invokable<?, ?> method = method(AMIApi.class, "resetLaunchPermissionsOnImageInRegion", String.class, String.class); GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, "imageId")); request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertPayloadEquals(request, resetLaunchPermissionsOnImage.getPayload().getRawContent().toString(), "application/x-www-form-urlencoded", false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); assertFallbackClassEquals(method, null); checkFilters(request); } }
googleapis/google-cloud-java
36,577
java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/ListGeneratorsResponse.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/generator.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.dialogflow.v2beta1; /** * * * <pre> * Response of ListGenerators. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListGeneratorsResponse} */ public final class ListGeneratorsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.ListGeneratorsResponse) ListGeneratorsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListGeneratorsResponse.newBuilder() to construct. private ListGeneratorsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListGeneratorsResponse() { generators_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListGeneratorsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.GeneratorProto .internal_static_google_cloud_dialogflow_v2beta1_ListGeneratorsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.GeneratorProto .internal_static_google_cloud_dialogflow_v2beta1_ListGeneratorsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.class, com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.Builder.class); } public static final int GENERATORS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.dialogflow.v2beta1.Generator> generators_; /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.dialogflow.v2beta1.Generator> getGeneratorsList() { return generators_; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder> getGeneratorsOrBuilderList() { return generators_; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ @java.lang.Override public int getGeneratorsCount() { return generators_.size(); } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.Generator getGenerators(int index) { return generators_.get(index); } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ @java.lang.Override public com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder getGeneratorsOrBuilder(int index) { return generators_.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 < generators_.size(); i++) { output.writeMessage(1, generators_.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 < generators_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, generators_.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.v2beta1.ListGeneratorsResponse)) { return super.equals(obj); } com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse other = (com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse) obj; if (!getGeneratorsList().equals(other.getGeneratorsList())) 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 (getGeneratorsCount() > 0) { hash = (37 * hash) + GENERATORS_FIELD_NUMBER; hash = (53 * hash) + getGeneratorsList().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.v2beta1.ListGeneratorsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse 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.ListGeneratorsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse 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.ListGeneratorsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse 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.ListGeneratorsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse 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.ListGeneratorsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse 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.ListGeneratorsResponse 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.ListGeneratorsResponse 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.ListGeneratorsResponse 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 ListGenerators. * </pre> * * Protobuf type {@code google.cloud.dialogflow.v2beta1.ListGeneratorsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.ListGeneratorsResponse) com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.dialogflow.v2beta1.GeneratorProto .internal_static_google_cloud_dialogflow_v2beta1_ListGeneratorsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.dialogflow.v2beta1.GeneratorProto .internal_static_google_cloud_dialogflow_v2beta1_ListGeneratorsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.class, com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.Builder.class); } // Construct using com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (generatorsBuilder_ == null) { generators_ = java.util.Collections.emptyList(); } else { generators_ = null; generatorsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.dialogflow.v2beta1.GeneratorProto .internal_static_google_cloud_dialogflow_v2beta1_ListGeneratorsResponse_descriptor; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse getDefaultInstanceForType() { return com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse build() { com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse buildPartial() { com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse result = new com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse result) { if (generatorsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { generators_ = java.util.Collections.unmodifiableList(generators_); bitField0_ = (bitField0_ & ~0x00000001); } result.generators_ = generators_; } else { result.generators_ = generatorsBuilder_.build(); } } private void buildPartial0(com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse 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.v2beta1.ListGeneratorsResponse) { return mergeFrom((com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse other) { if (other == com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse.getDefaultInstance()) return this; if (generatorsBuilder_ == null) { if (!other.generators_.isEmpty()) { if (generators_.isEmpty()) { generators_ = other.generators_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureGeneratorsIsMutable(); generators_.addAll(other.generators_); } onChanged(); } } else { if (!other.generators_.isEmpty()) { if (generatorsBuilder_.isEmpty()) { generatorsBuilder_.dispose(); generatorsBuilder_ = null; generators_ = other.generators_; bitField0_ = (bitField0_ & ~0x00000001); generatorsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getGeneratorsFieldBuilder() : null; } else { generatorsBuilder_.addAllMessages(other.generators_); } } } 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.v2beta1.Generator m = input.readMessage( com.google.cloud.dialogflow.v2beta1.Generator.parser(), extensionRegistry); if (generatorsBuilder_ == null) { ensureGeneratorsIsMutable(); generators_.add(m); } else { generatorsBuilder_.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.v2beta1.Generator> generators_ = java.util.Collections.emptyList(); private void ensureGeneratorsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { generators_ = new java.util.ArrayList<com.google.cloud.dialogflow.v2beta1.Generator>(generators_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.Generator, com.google.cloud.dialogflow.v2beta1.Generator.Builder, com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder> generatorsBuilder_; /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2beta1.Generator> getGeneratorsList() { if (generatorsBuilder_ == null) { return java.util.Collections.unmodifiableList(generators_); } else { return generatorsBuilder_.getMessageList(); } } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public int getGeneratorsCount() { if (generatorsBuilder_ == null) { return generators_.size(); } else { return generatorsBuilder_.getCount(); } } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.Generator getGenerators(int index) { if (generatorsBuilder_ == null) { return generators_.get(index); } else { return generatorsBuilder_.getMessage(index); } } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder setGenerators(int index, com.google.cloud.dialogflow.v2beta1.Generator value) { if (generatorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGeneratorsIsMutable(); generators_.set(index, value); onChanged(); } else { generatorsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder setGenerators( int index, com.google.cloud.dialogflow.v2beta1.Generator.Builder builderForValue) { if (generatorsBuilder_ == null) { ensureGeneratorsIsMutable(); generators_.set(index, builderForValue.build()); onChanged(); } else { generatorsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder addGenerators(com.google.cloud.dialogflow.v2beta1.Generator value) { if (generatorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGeneratorsIsMutable(); generators_.add(value); onChanged(); } else { generatorsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder addGenerators(int index, com.google.cloud.dialogflow.v2beta1.Generator value) { if (generatorsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureGeneratorsIsMutable(); generators_.add(index, value); onChanged(); } else { generatorsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder addGenerators( com.google.cloud.dialogflow.v2beta1.Generator.Builder builderForValue) { if (generatorsBuilder_ == null) { ensureGeneratorsIsMutable(); generators_.add(builderForValue.build()); onChanged(); } else { generatorsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder addGenerators( int index, com.google.cloud.dialogflow.v2beta1.Generator.Builder builderForValue) { if (generatorsBuilder_ == null) { ensureGeneratorsIsMutable(); generators_.add(index, builderForValue.build()); onChanged(); } else { generatorsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder addAllGenerators( java.lang.Iterable<? extends com.google.cloud.dialogflow.v2beta1.Generator> values) { if (generatorsBuilder_ == null) { ensureGeneratorsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, generators_); onChanged(); } else { generatorsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder clearGenerators() { if (generatorsBuilder_ == null) { generators_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { generatorsBuilder_.clear(); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public Builder removeGenerators(int index) { if (generatorsBuilder_ == null) { ensureGeneratorsIsMutable(); generators_.remove(index); onChanged(); } else { generatorsBuilder_.remove(index); } return this; } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.Generator.Builder getGeneratorsBuilder(int index) { return getGeneratorsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder getGeneratorsOrBuilder( int index) { if (generatorsBuilder_ == null) { return generators_.get(index); } else { return generatorsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public java.util.List<? extends com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder> getGeneratorsOrBuilderList() { if (generatorsBuilder_ != null) { return generatorsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(generators_); } } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.Generator.Builder addGeneratorsBuilder() { return getGeneratorsFieldBuilder() .addBuilder(com.google.cloud.dialogflow.v2beta1.Generator.getDefaultInstance()); } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public com.google.cloud.dialogflow.v2beta1.Generator.Builder addGeneratorsBuilder(int index) { return getGeneratorsFieldBuilder() .addBuilder(index, com.google.cloud.dialogflow.v2beta1.Generator.getDefaultInstance()); } /** * * * <pre> * List of generators retrieved. * </pre> * * <code>repeated .google.cloud.dialogflow.v2beta1.Generator generators = 1;</code> */ public java.util.List<com.google.cloud.dialogflow.v2beta1.Generator.Builder> getGeneratorsBuilderList() { return getGeneratorsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.Generator, com.google.cloud.dialogflow.v2beta1.Generator.Builder, com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder> getGeneratorsFieldBuilder() { if (generatorsBuilder_ == null) { generatorsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.dialogflow.v2beta1.Generator, com.google.cloud.dialogflow.v2beta1.Generator.Builder, com.google.cloud.dialogflow.v2beta1.GeneratorOrBuilder>( generators_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); generators_ = null; } return generatorsBuilder_; } 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.v2beta1.ListGeneratorsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.ListGeneratorsResponse) private static final com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse(); } public static com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListGeneratorsResponse> PARSER = new com.google.protobuf.AbstractParser<ListGeneratorsResponse>() { @java.lang.Override public ListGeneratorsResponse 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<ListGeneratorsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListGeneratorsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.dialogflow.v2beta1.ListGeneratorsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,580
java-securitycentermanagement/proto-google-cloud-securitycentermanagement-v1/src/main/java/com/google/cloud/securitycentermanagement/v1/ListDescendantSecurityHealthAnalyticsCustomModulesRequest.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/securitycentermanagement/v1/security_center_management.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.securitycentermanagement.v1; /** * * * <pre> * Request message for * [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. * </pre> * * Protobuf type {@code * google.cloud.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest} */ public final class ListDescendantSecurityHealthAnalyticsCustomModulesRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest) ListDescendantSecurityHealthAnalyticsCustomModulesRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListDescendantSecurityHealthAnalyticsCustomModulesRequest.newBuilder() to construct. private ListDescendantSecurityHealthAnalyticsCustomModulesRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDescendantSecurityHealthAnalyticsCustomModulesRequest() { parent_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDescendantSecurityHealthAnalyticsCustomModulesRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto .internal_static_google_cloud_securitycentermanagement_v1_ListDescendantSecurityHealthAnalyticsCustomModulesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto .internal_static_google_cloud_securitycentermanagement_v1_ListDescendantSecurityHealthAnalyticsCustomModulesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest.class, com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Name of the parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Name of the parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PAGE_SIZE_FIELD_NUMBER = 2; private int pageSize_ = 0; /** * * * <pre> * Optional. The maximum number of results to return in a single response. * Default is 10, minimum is 1, maximum is 1000. * </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 pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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. A pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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; } } 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_); } 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_); } 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest)) { return super.equals(obj); } com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest other = (com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest) obj; if (!getParent().equals(other.getParent())) 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) + 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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 * [SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules][google.cloud.securitycentermanagement.v1.SecurityCenterManagement.ListDescendantSecurityHealthAnalyticsCustomModules]. * </pre> * * Protobuf type {@code * google.cloud.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest) com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto .internal_static_google_cloud_securitycentermanagement_v1_ListDescendantSecurityHealthAnalyticsCustomModulesRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto .internal_static_google_cloud_securitycentermanagement_v1_ListDescendantSecurityHealthAnalyticsCustomModulesRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest.class, com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest.Builder.class); } // Construct using // com.google.cloud.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest.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_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.securitycentermanagement.v1.SecurityCenterManagementProto .internal_static_google_cloud_securitycentermanagement_v1_ListDescendantSecurityHealthAnalyticsCustomModulesRequest_descriptor; } @java.lang.Override public com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest getDefaultInstanceForType() { return com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest build() { com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest buildPartial() { com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest result = new com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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_; } } @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.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest) { return mergeFrom( (com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest other) { if (other == com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest.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(); } 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 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 parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Name of the parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Name of the parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Name of the parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Name of the parent organization, folder, or project in which to * list custom modules, in one of the following formats: * * * `organizations/{organization}/locations/{location}` * * `folders/{folder}/locations/{location}` * * `projects/{project}/locations/{location}` * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private int pageSize_; /** * * * <pre> * Optional. The maximum number of results to return in a single response. * Default is 10, minimum is 1, maximum is 1000. * </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. The maximum number of results to return in a single response. * Default is 10, minimum is 1, maximum is 1000. * </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. The maximum number of results to return in a single response. * Default is 10, minimum is 1, maximum is 1000. * </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 pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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. A pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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. A pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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. A pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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. A pagination token returned from a previous request. Provide this * token to retrieve the next page of results. * * When paginating, the rest of the request must match the request that * generated 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; } @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.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest) } // @@protoc_insertion_point(class_scope:google.cloud.securitycentermanagement.v1.ListDescendantSecurityHealthAnalyticsCustomModulesRequest) private static final com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest(); } public static com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser< ListDescendantSecurityHealthAnalyticsCustomModulesRequest> PARSER = new com.google.protobuf.AbstractParser< ListDescendantSecurityHealthAnalyticsCustomModulesRequest>() { @java.lang.Override public ListDescendantSecurityHealthAnalyticsCustomModulesRequest 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< ListDescendantSecurityHealthAnalyticsCustomModulesRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDescendantSecurityHealthAnalyticsCustomModulesRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.securitycentermanagement.v1 .ListDescendantSecurityHealthAnalyticsCustomModulesRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,668
java-confidentialcomputing/proto-google-cloud-confidentialcomputing-v1/src/main/java/com/google/cloud/confidentialcomputing/v1/ConfidentialSpaceInfo.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/confidentialcomputing/v1/service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.confidentialcomputing.v1; /** * * * <pre> * ConfidentialSpaceInfo contains information related to the Confidential Space * TEE. * </pre> * * Protobuf type {@code google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo} */ public final class ConfidentialSpaceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo) ConfidentialSpaceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use ConfidentialSpaceInfo.newBuilder() to construct. private ConfidentialSpaceInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ConfidentialSpaceInfo() { signedEntities_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ConfidentialSpaceInfo(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.class, com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.Builder.class); } public static final int SIGNED_ENTITIES_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.confidentialcomputing.v1.SignedEntity> signedEntities_; /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public java.util.List<com.google.cloud.confidentialcomputing.v1.SignedEntity> getSignedEntitiesList() { return signedEntities_; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder> getSignedEntitiesOrBuilderList() { return signedEntities_; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public int getSignedEntitiesCount() { return signedEntities_.size(); } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.confidentialcomputing.v1.SignedEntity getSignedEntities(int index) { return signedEntities_.get(index); } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder getSignedEntitiesOrBuilder( int index) { return signedEntities_.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 < signedEntities_.size(); i++) { output.writeMessage(1, signedEntities_.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 < signedEntities_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, signedEntities_.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.confidentialcomputing.v1.ConfidentialSpaceInfo)) { return super.equals(obj); } com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo other = (com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo) obj; if (!getSignedEntitiesList().equals(other.getSignedEntitiesList())) 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 (getSignedEntitiesCount() > 0) { hash = (37 * hash) + SIGNED_ENTITIES_FIELD_NUMBER; hash = (53 * hash) + getSignedEntitiesList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo 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.confidentialcomputing.v1.ConfidentialSpaceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo 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.confidentialcomputing.v1.ConfidentialSpaceInfo parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo 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.confidentialcomputing.v1.ConfidentialSpaceInfo parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo 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.confidentialcomputing.v1.ConfidentialSpaceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo 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.confidentialcomputing.v1.ConfidentialSpaceInfo 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> * ConfidentialSpaceInfo contains information related to the Confidential Space * TEE. * </pre> * * Protobuf type {@code google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo) com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.class, com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.Builder.class); } // Construct using com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (signedEntitiesBuilder_ == null) { signedEntities_ = java.util.Collections.emptyList(); } else { signedEntities_ = null; signedEntitiesBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.confidentialcomputing.v1.ServiceProto .internal_static_google_cloud_confidentialcomputing_v1_ConfidentialSpaceInfo_descriptor; } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo getDefaultInstanceForType() { return com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.getDefaultInstance(); } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo build() { com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo buildPartial() { com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo result = new com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo result) { if (signedEntitiesBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { signedEntities_ = java.util.Collections.unmodifiableList(signedEntities_); bitField0_ = (bitField0_ & ~0x00000001); } result.signedEntities_ = signedEntities_; } else { result.signedEntities_ = signedEntitiesBuilder_.build(); } } private void buildPartial0( com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo 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.confidentialcomputing.v1.ConfidentialSpaceInfo) { return mergeFrom((com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo other) { if (other == com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo.getDefaultInstance()) return this; if (signedEntitiesBuilder_ == null) { if (!other.signedEntities_.isEmpty()) { if (signedEntities_.isEmpty()) { signedEntities_ = other.signedEntities_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSignedEntitiesIsMutable(); signedEntities_.addAll(other.signedEntities_); } onChanged(); } } else { if (!other.signedEntities_.isEmpty()) { if (signedEntitiesBuilder_.isEmpty()) { signedEntitiesBuilder_.dispose(); signedEntitiesBuilder_ = null; signedEntities_ = other.signedEntities_; bitField0_ = (bitField0_ & ~0x00000001); signedEntitiesBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSignedEntitiesFieldBuilder() : null; } else { signedEntitiesBuilder_.addAllMessages(other.signedEntities_); } } } 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.confidentialcomputing.v1.SignedEntity m = input.readMessage( com.google.cloud.confidentialcomputing.v1.SignedEntity.parser(), extensionRegistry); if (signedEntitiesBuilder_ == null) { ensureSignedEntitiesIsMutable(); signedEntities_.add(m); } else { signedEntitiesBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.confidentialcomputing.v1.SignedEntity> signedEntities_ = java.util.Collections.emptyList(); private void ensureSignedEntitiesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { signedEntities_ = new java.util.ArrayList<com.google.cloud.confidentialcomputing.v1.SignedEntity>( signedEntities_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.confidentialcomputing.v1.SignedEntity, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder, com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder> signedEntitiesBuilder_; /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public java.util.List<com.google.cloud.confidentialcomputing.v1.SignedEntity> getSignedEntitiesList() { if (signedEntitiesBuilder_ == null) { return java.util.Collections.unmodifiableList(signedEntities_); } else { return signedEntitiesBuilder_.getMessageList(); } } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public int getSignedEntitiesCount() { if (signedEntitiesBuilder_ == null) { return signedEntities_.size(); } else { return signedEntitiesBuilder_.getCount(); } } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.SignedEntity getSignedEntities(int index) { if (signedEntitiesBuilder_ == null) { return signedEntities_.get(index); } else { return signedEntitiesBuilder_.getMessage(index); } } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setSignedEntities( int index, com.google.cloud.confidentialcomputing.v1.SignedEntity value) { if (signedEntitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSignedEntitiesIsMutable(); signedEntities_.set(index, value); onChanged(); } else { signedEntitiesBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setSignedEntities( int index, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder builderForValue) { if (signedEntitiesBuilder_ == null) { ensureSignedEntitiesIsMutable(); signedEntities_.set(index, builderForValue.build()); onChanged(); } else { signedEntitiesBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addSignedEntities(com.google.cloud.confidentialcomputing.v1.SignedEntity value) { if (signedEntitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSignedEntitiesIsMutable(); signedEntities_.add(value); onChanged(); } else { signedEntitiesBuilder_.addMessage(value); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addSignedEntities( int index, com.google.cloud.confidentialcomputing.v1.SignedEntity value) { if (signedEntitiesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSignedEntitiesIsMutable(); signedEntities_.add(index, value); onChanged(); } else { signedEntitiesBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addSignedEntities( com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder builderForValue) { if (signedEntitiesBuilder_ == null) { ensureSignedEntitiesIsMutable(); signedEntities_.add(builderForValue.build()); onChanged(); } else { signedEntitiesBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addSignedEntities( int index, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder builderForValue) { if (signedEntitiesBuilder_ == null) { ensureSignedEntitiesIsMutable(); signedEntities_.add(index, builderForValue.build()); onChanged(); } else { signedEntitiesBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder addAllSignedEntities( java.lang.Iterable<? extends com.google.cloud.confidentialcomputing.v1.SignedEntity> values) { if (signedEntitiesBuilder_ == null) { ensureSignedEntitiesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, signedEntities_); onChanged(); } else { signedEntitiesBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearSignedEntities() { if (signedEntitiesBuilder_ == null) { signedEntities_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { signedEntitiesBuilder_.clear(); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder removeSignedEntities(int index) { if (signedEntitiesBuilder_ == null) { ensureSignedEntitiesIsMutable(); signedEntities_.remove(index); onChanged(); } else { signedEntitiesBuilder_.remove(index); } return this; } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder getSignedEntitiesBuilder( int index) { return getSignedEntitiesFieldBuilder().getBuilder(index); } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder getSignedEntitiesOrBuilder(int index) { if (signedEntitiesBuilder_ == null) { return signedEntities_.get(index); } else { return signedEntitiesBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public java.util.List<? extends com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder> getSignedEntitiesOrBuilderList() { if (signedEntitiesBuilder_ != null) { return signedEntitiesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(signedEntities_); } } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder addSignedEntitiesBuilder() { return getSignedEntitiesFieldBuilder() .addBuilder(com.google.cloud.confidentialcomputing.v1.SignedEntity.getDefaultInstance()); } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder addSignedEntitiesBuilder( int index) { return getSignedEntitiesFieldBuilder() .addBuilder( index, com.google.cloud.confidentialcomputing.v1.SignedEntity.getDefaultInstance()); } /** * * * <pre> * Optional. A list of signed entities containing container image signatures * that can be used for server-side signature verification. * </pre> * * <code> * repeated .google.cloud.confidentialcomputing.v1.SignedEntity signed_entities = 1 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public java.util.List<com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder> getSignedEntitiesBuilderList() { return getSignedEntitiesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.confidentialcomputing.v1.SignedEntity, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder, com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder> getSignedEntitiesFieldBuilder() { if (signedEntitiesBuilder_ == null) { signedEntitiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.confidentialcomputing.v1.SignedEntity, com.google.cloud.confidentialcomputing.v1.SignedEntity.Builder, com.google.cloud.confidentialcomputing.v1.SignedEntityOrBuilder>( signedEntities_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); signedEntities_ = null; } return signedEntitiesBuilder_; } @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.confidentialcomputing.v1.ConfidentialSpaceInfo) } // @@protoc_insertion_point(class_scope:google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo) private static final com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo(); } public static com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ConfidentialSpaceInfo> PARSER = new com.google.protobuf.AbstractParser<ConfidentialSpaceInfo>() { @java.lang.Override public ConfidentialSpaceInfo 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<ConfidentialSpaceInfo> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ConfidentialSpaceInfo> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.confidentialcomputing.v1.ConfidentialSpaceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
36,806
jdk/src/share/classes/java/awt/AWTEventMulticaster.java
/* * Copyright (c) 1996, 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.awt; import java.awt.event.*; import java.lang.reflect.Array; import java.util.EventListener; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; import java.util.EventListener; /** * {@code AWTEventMulticaster} implements efficient and thread-safe multi-cast * event dispatching for the AWT events defined in the {@code java.awt.event} * package. * <p> * The following example illustrates how to use this class: * * <pre><code> * public myComponent extends Component { * ActionListener actionListener = null; * * public synchronized void addActionListener(ActionListener l) { * actionListener = AWTEventMulticaster.add(actionListener, l); * } * public synchronized void removeActionListener(ActionListener l) { * actionListener = AWTEventMulticaster.remove(actionListener, l); * } * public void processEvent(AWTEvent e) { * // when event occurs which causes "action" semantic * ActionListener listener = actionListener; * if (listener != null) { * listener.actionPerformed(new ActionEvent()); * } * } * } * </code></pre> * The important point to note is the first argument to the {@code * add} and {@code remove} methods is the field maintaining the * listeners. In addition you must assign the result of the {@code add} * and {@code remove} methods to the field maintaining the listeners. * <p> * {@code AWTEventMulticaster} is implemented as a pair of {@code * EventListeners} that are set at construction time. {@code * AWTEventMulticaster} is immutable. The {@code add} and {@code * remove} methods do not alter {@code AWTEventMulticaster} in * anyway. If necessary, a new {@code AWTEventMulticaster} is * created. In this way it is safe to add and remove listeners during * the process of an event dispatching. However, event listeners * added during the process of an event dispatch operation are not * notified of the event currently being dispatched. * <p> * All of the {@code add} methods allow {@code null} arguments. If the * first argument is {@code null}, the second argument is returned. If * the first argument is not {@code null} and the second argument is * {@code null}, the first argument is returned. If both arguments are * {@code non-null}, a new {@code AWTEventMulticaster} is created using * the two arguments and returned. * <p> * For the {@code remove} methods that take two arguments, the following is * returned: * <ul> * <li>{@code null}, if the first argument is {@code null}, or * the arguments are equal, by way of {@code ==}. * <li>the first argument, if the first argument is not an instance of * {@code AWTEventMulticaster}. * <li>result of invoking {@code remove(EventListener)} on the * first argument, supplying the second argument to the * {@code remove(EventListener)} method. * </ul> * <p>Swing makes use of * {@link javax.swing.event.EventListenerList EventListenerList} for * similar logic. Refer to it for details. * * @see javax.swing.event.EventListenerList * * @author John Rose * @author Amy Fowler * @since 1.1 */ public class AWTEventMulticaster implements ComponentListener, ContainerListener, FocusListener, KeyListener, MouseListener, MouseMotionListener, WindowListener, WindowFocusListener, WindowStateListener, ActionListener, ItemListener, AdjustmentListener, TextListener, InputMethodListener, HierarchyListener, HierarchyBoundsListener, MouseWheelListener { protected final EventListener a, b; /** * Creates an event multicaster instance which chains listener-a * with listener-b. Input parameters <code>a</code> and <code>b</code> * should not be <code>null</code>, though implementations may vary in * choosing whether or not to throw <code>NullPointerException</code> * in that case. * @param a listener-a * @param b listener-b */ protected AWTEventMulticaster(EventListener a, EventListener b) { this.a = a; this.b = b; } /** * Removes a listener from this multicaster. * <p> * The returned multicaster contains all the listeners in this * multicaster with the exception of all occurrences of {@code oldl}. * If the resulting multicaster contains only one regular listener * the regular listener may be returned. If the resulting multicaster * is empty, then {@code null} may be returned instead. * <p> * No exception is thrown if {@code oldl} is {@code null}. * * @param oldl the listener to be removed * @return resulting listener */ protected EventListener remove(EventListener oldl) { if (oldl == a) return b; if (oldl == b) return a; EventListener a2 = removeInternal(a, oldl); EventListener b2 = removeInternal(b, oldl); if (a2 == a && b2 == b) { return this; // it's not here } return addInternal(a2, b2); } /** * Handles the componentResized event by invoking the * componentResized methods on listener-a and listener-b. * @param e the component event */ public void componentResized(ComponentEvent e) { ((ComponentListener)a).componentResized(e); ((ComponentListener)b).componentResized(e); } /** * Handles the componentMoved event by invoking the * componentMoved methods on listener-a and listener-b. * @param e the component event */ public void componentMoved(ComponentEvent e) { ((ComponentListener)a).componentMoved(e); ((ComponentListener)b).componentMoved(e); } /** * Handles the componentShown event by invoking the * componentShown methods on listener-a and listener-b. * @param e the component event */ public void componentShown(ComponentEvent e) { ((ComponentListener)a).componentShown(e); ((ComponentListener)b).componentShown(e); } /** * Handles the componentHidden event by invoking the * componentHidden methods on listener-a and listener-b. * @param e the component event */ public void componentHidden(ComponentEvent e) { ((ComponentListener)a).componentHidden(e); ((ComponentListener)b).componentHidden(e); } /** * Handles the componentAdded container event by invoking the * componentAdded methods on listener-a and listener-b. * @param e the component event */ public void componentAdded(ContainerEvent e) { ((ContainerListener)a).componentAdded(e); ((ContainerListener)b).componentAdded(e); } /** * Handles the componentRemoved container event by invoking the * componentRemoved methods on listener-a and listener-b. * @param e the component event */ public void componentRemoved(ContainerEvent e) { ((ContainerListener)a).componentRemoved(e); ((ContainerListener)b).componentRemoved(e); } /** * Handles the focusGained event by invoking the * focusGained methods on listener-a and listener-b. * @param e the focus event */ public void focusGained(FocusEvent e) { ((FocusListener)a).focusGained(e); ((FocusListener)b).focusGained(e); } /** * Handles the focusLost event by invoking the * focusLost methods on listener-a and listener-b. * @param e the focus event */ public void focusLost(FocusEvent e) { ((FocusListener)a).focusLost(e); ((FocusListener)b).focusLost(e); } /** * Handles the keyTyped event by invoking the * keyTyped methods on listener-a and listener-b. * @param e the key event */ public void keyTyped(KeyEvent e) { ((KeyListener)a).keyTyped(e); ((KeyListener)b).keyTyped(e); } /** * Handles the keyPressed event by invoking the * keyPressed methods on listener-a and listener-b. * @param e the key event */ public void keyPressed(KeyEvent e) { ((KeyListener)a).keyPressed(e); ((KeyListener)b).keyPressed(e); } /** * Handles the keyReleased event by invoking the * keyReleased methods on listener-a and listener-b. * @param e the key event */ public void keyReleased(KeyEvent e) { ((KeyListener)a).keyReleased(e); ((KeyListener)b).keyReleased(e); } /** * Handles the mouseClicked event by invoking the * mouseClicked methods on listener-a and listener-b. * @param e the mouse event */ public void mouseClicked(MouseEvent e) { ((MouseListener)a).mouseClicked(e); ((MouseListener)b).mouseClicked(e); } /** * Handles the mousePressed event by invoking the * mousePressed methods on listener-a and listener-b. * @param e the mouse event */ public void mousePressed(MouseEvent e) { ((MouseListener)a).mousePressed(e); ((MouseListener)b).mousePressed(e); } /** * Handles the mouseReleased event by invoking the * mouseReleased methods on listener-a and listener-b. * @param e the mouse event */ public void mouseReleased(MouseEvent e) { ((MouseListener)a).mouseReleased(e); ((MouseListener)b).mouseReleased(e); } /** * Handles the mouseEntered event by invoking the * mouseEntered methods on listener-a and listener-b. * @param e the mouse event */ public void mouseEntered(MouseEvent e) { ((MouseListener)a).mouseEntered(e); ((MouseListener)b).mouseEntered(e); } /** * Handles the mouseExited event by invoking the * mouseExited methods on listener-a and listener-b. * @param e the mouse event */ public void mouseExited(MouseEvent e) { ((MouseListener)a).mouseExited(e); ((MouseListener)b).mouseExited(e); } /** * Handles the mouseDragged event by invoking the * mouseDragged methods on listener-a and listener-b. * @param e the mouse event */ public void mouseDragged(MouseEvent e) { ((MouseMotionListener)a).mouseDragged(e); ((MouseMotionListener)b).mouseDragged(e); } /** * Handles the mouseMoved event by invoking the * mouseMoved methods on listener-a and listener-b. * @param e the mouse event */ public void mouseMoved(MouseEvent e) { ((MouseMotionListener)a).mouseMoved(e); ((MouseMotionListener)b).mouseMoved(e); } /** * Handles the windowOpened event by invoking the * windowOpened methods on listener-a and listener-b. * @param e the window event */ public void windowOpened(WindowEvent e) { ((WindowListener)a).windowOpened(e); ((WindowListener)b).windowOpened(e); } /** * Handles the windowClosing event by invoking the * windowClosing methods on listener-a and listener-b. * @param e the window event */ public void windowClosing(WindowEvent e) { ((WindowListener)a).windowClosing(e); ((WindowListener)b).windowClosing(e); } /** * Handles the windowClosed event by invoking the * windowClosed methods on listener-a and listener-b. * @param e the window event */ public void windowClosed(WindowEvent e) { ((WindowListener)a).windowClosed(e); ((WindowListener)b).windowClosed(e); } /** * Handles the windowIconified event by invoking the * windowIconified methods on listener-a and listener-b. * @param e the window event */ public void windowIconified(WindowEvent e) { ((WindowListener)a).windowIconified(e); ((WindowListener)b).windowIconified(e); } /** * Handles the windowDeiconfied event by invoking the * windowDeiconified methods on listener-a and listener-b. * @param e the window event */ public void windowDeiconified(WindowEvent e) { ((WindowListener)a).windowDeiconified(e); ((WindowListener)b).windowDeiconified(e); } /** * Handles the windowActivated event by invoking the * windowActivated methods on listener-a and listener-b. * @param e the window event */ public void windowActivated(WindowEvent e) { ((WindowListener)a).windowActivated(e); ((WindowListener)b).windowActivated(e); } /** * Handles the windowDeactivated event by invoking the * windowDeactivated methods on listener-a and listener-b. * @param e the window event */ public void windowDeactivated(WindowEvent e) { ((WindowListener)a).windowDeactivated(e); ((WindowListener)b).windowDeactivated(e); } /** * Handles the windowStateChanged event by invoking the * windowStateChanged methods on listener-a and listener-b. * @param e the window event * @since 1.4 */ public void windowStateChanged(WindowEvent e) { ((WindowStateListener)a).windowStateChanged(e); ((WindowStateListener)b).windowStateChanged(e); } /** * Handles the windowGainedFocus event by invoking the windowGainedFocus * methods on listener-a and listener-b. * @param e the window event * @since 1.4 */ public void windowGainedFocus(WindowEvent e) { ((WindowFocusListener)a).windowGainedFocus(e); ((WindowFocusListener)b).windowGainedFocus(e); } /** * Handles the windowLostFocus event by invoking the windowLostFocus * methods on listener-a and listener-b. * @param e the window event * @since 1.4 */ public void windowLostFocus(WindowEvent e) { ((WindowFocusListener)a).windowLostFocus(e); ((WindowFocusListener)b).windowLostFocus(e); } /** * Handles the actionPerformed event by invoking the * actionPerformed methods on listener-a and listener-b. * @param e the action event */ public void actionPerformed(ActionEvent e) { ((ActionListener)a).actionPerformed(e); ((ActionListener)b).actionPerformed(e); } /** * Handles the itemStateChanged event by invoking the * itemStateChanged methods on listener-a and listener-b. * @param e the item event */ public void itemStateChanged(ItemEvent e) { ((ItemListener)a).itemStateChanged(e); ((ItemListener)b).itemStateChanged(e); } /** * Handles the adjustmentValueChanged event by invoking the * adjustmentValueChanged methods on listener-a and listener-b. * @param e the adjustment event */ public void adjustmentValueChanged(AdjustmentEvent e) { ((AdjustmentListener)a).adjustmentValueChanged(e); ((AdjustmentListener)b).adjustmentValueChanged(e); } public void textValueChanged(TextEvent e) { ((TextListener)a).textValueChanged(e); ((TextListener)b).textValueChanged(e); } /** * Handles the inputMethodTextChanged event by invoking the * inputMethodTextChanged methods on listener-a and listener-b. * @param e the item event */ public void inputMethodTextChanged(InputMethodEvent e) { ((InputMethodListener)a).inputMethodTextChanged(e); ((InputMethodListener)b).inputMethodTextChanged(e); } /** * Handles the caretPositionChanged event by invoking the * caretPositionChanged methods on listener-a and listener-b. * @param e the item event */ public void caretPositionChanged(InputMethodEvent e) { ((InputMethodListener)a).caretPositionChanged(e); ((InputMethodListener)b).caretPositionChanged(e); } /** * Handles the hierarchyChanged event by invoking the * hierarchyChanged methods on listener-a and listener-b. * @param e the item event * @since 1.3 */ public void hierarchyChanged(HierarchyEvent e) { ((HierarchyListener)a).hierarchyChanged(e); ((HierarchyListener)b).hierarchyChanged(e); } /** * Handles the ancestorMoved event by invoking the * ancestorMoved methods on listener-a and listener-b. * @param e the item event * @since 1.3 */ public void ancestorMoved(HierarchyEvent e) { ((HierarchyBoundsListener)a).ancestorMoved(e); ((HierarchyBoundsListener)b).ancestorMoved(e); } /** * Handles the ancestorResized event by invoking the * ancestorResized methods on listener-a and listener-b. * @param e the item event * @since 1.3 */ public void ancestorResized(HierarchyEvent e) { ((HierarchyBoundsListener)a).ancestorResized(e); ((HierarchyBoundsListener)b).ancestorResized(e); } /** * Handles the mouseWheelMoved event by invoking the * mouseWheelMoved methods on listener-a and listener-b. * @param e the mouse event * @since 1.4 */ public void mouseWheelMoved(MouseWheelEvent e) { ((MouseWheelListener)a).mouseWheelMoved(e); ((MouseWheelListener)b).mouseWheelMoved(e); } /** * Adds component-listener-a with component-listener-b and * returns the resulting multicast listener. * @param a component-listener-a * @param b component-listener-b */ public static ComponentListener add(ComponentListener a, ComponentListener b) { return (ComponentListener)addInternal(a, b); } /** * Adds container-listener-a with container-listener-b and * returns the resulting multicast listener. * @param a container-listener-a * @param b container-listener-b */ public static ContainerListener add(ContainerListener a, ContainerListener b) { return (ContainerListener)addInternal(a, b); } /** * Adds focus-listener-a with focus-listener-b and * returns the resulting multicast listener. * @param a focus-listener-a * @param b focus-listener-b */ public static FocusListener add(FocusListener a, FocusListener b) { return (FocusListener)addInternal(a, b); } /** * Adds key-listener-a with key-listener-b and * returns the resulting multicast listener. * @param a key-listener-a * @param b key-listener-b */ public static KeyListener add(KeyListener a, KeyListener b) { return (KeyListener)addInternal(a, b); } /** * Adds mouse-listener-a with mouse-listener-b and * returns the resulting multicast listener. * @param a mouse-listener-a * @param b mouse-listener-b */ public static MouseListener add(MouseListener a, MouseListener b) { return (MouseListener)addInternal(a, b); } /** * Adds mouse-motion-listener-a with mouse-motion-listener-b and * returns the resulting multicast listener. * @param a mouse-motion-listener-a * @param b mouse-motion-listener-b */ public static MouseMotionListener add(MouseMotionListener a, MouseMotionListener b) { return (MouseMotionListener)addInternal(a, b); } /** * Adds window-listener-a with window-listener-b and * returns the resulting multicast listener. * @param a window-listener-a * @param b window-listener-b */ public static WindowListener add(WindowListener a, WindowListener b) { return (WindowListener)addInternal(a, b); } /** * Adds window-state-listener-a with window-state-listener-b * and returns the resulting multicast listener. * @param a window-state-listener-a * @param b window-state-listener-b * @since 1.4 */ public static WindowStateListener add(WindowStateListener a, WindowStateListener b) { return (WindowStateListener)addInternal(a, b); } /** * Adds window-focus-listener-a with window-focus-listener-b * and returns the resulting multicast listener. * @param a window-focus-listener-a * @param b window-focus-listener-b * @since 1.4 */ public static WindowFocusListener add(WindowFocusListener a, WindowFocusListener b) { return (WindowFocusListener)addInternal(a, b); } /** * Adds action-listener-a with action-listener-b and * returns the resulting multicast listener. * @param a action-listener-a * @param b action-listener-b */ public static ActionListener add(ActionListener a, ActionListener b) { return (ActionListener)addInternal(a, b); } /** * Adds item-listener-a with item-listener-b and * returns the resulting multicast listener. * @param a item-listener-a * @param b item-listener-b */ public static ItemListener add(ItemListener a, ItemListener b) { return (ItemListener)addInternal(a, b); } /** * Adds adjustment-listener-a with adjustment-listener-b and * returns the resulting multicast listener. * @param a adjustment-listener-a * @param b adjustment-listener-b */ public static AdjustmentListener add(AdjustmentListener a, AdjustmentListener b) { return (AdjustmentListener)addInternal(a, b); } public static TextListener add(TextListener a, TextListener b) { return (TextListener)addInternal(a, b); } /** * Adds input-method-listener-a with input-method-listener-b and * returns the resulting multicast listener. * @param a input-method-listener-a * @param b input-method-listener-b */ public static InputMethodListener add(InputMethodListener a, InputMethodListener b) { return (InputMethodListener)addInternal(a, b); } /** * Adds hierarchy-listener-a with hierarchy-listener-b and * returns the resulting multicast listener. * @param a hierarchy-listener-a * @param b hierarchy-listener-b * @since 1.3 */ public static HierarchyListener add(HierarchyListener a, HierarchyListener b) { return (HierarchyListener)addInternal(a, b); } /** * Adds hierarchy-bounds-listener-a with hierarchy-bounds-listener-b and * returns the resulting multicast listener. * @param a hierarchy-bounds-listener-a * @param b hierarchy-bounds-listener-b * @since 1.3 */ public static HierarchyBoundsListener add(HierarchyBoundsListener a, HierarchyBoundsListener b) { return (HierarchyBoundsListener)addInternal(a, b); } /** * Adds mouse-wheel-listener-a with mouse-wheel-listener-b and * returns the resulting multicast listener. * @param a mouse-wheel-listener-a * @param b mouse-wheel-listener-b * @since 1.4 */ public static MouseWheelListener add(MouseWheelListener a, MouseWheelListener b) { return (MouseWheelListener)addInternal(a, b); } /** * Removes the old component-listener from component-listener-l and * returns the resulting multicast listener. * @param l component-listener-l * @param oldl the component-listener being removed */ public static ComponentListener remove(ComponentListener l, ComponentListener oldl) { return (ComponentListener) removeInternal(l, oldl); } /** * Removes the old container-listener from container-listener-l and * returns the resulting multicast listener. * @param l container-listener-l * @param oldl the container-listener being removed */ public static ContainerListener remove(ContainerListener l, ContainerListener oldl) { return (ContainerListener) removeInternal(l, oldl); } /** * Removes the old focus-listener from focus-listener-l and * returns the resulting multicast listener. * @param l focus-listener-l * @param oldl the focus-listener being removed */ public static FocusListener remove(FocusListener l, FocusListener oldl) { return (FocusListener) removeInternal(l, oldl); } /** * Removes the old key-listener from key-listener-l and * returns the resulting multicast listener. * @param l key-listener-l * @param oldl the key-listener being removed */ public static KeyListener remove(KeyListener l, KeyListener oldl) { return (KeyListener) removeInternal(l, oldl); } /** * Removes the old mouse-listener from mouse-listener-l and * returns the resulting multicast listener. * @param l mouse-listener-l * @param oldl the mouse-listener being removed */ public static MouseListener remove(MouseListener l, MouseListener oldl) { return (MouseListener) removeInternal(l, oldl); } /** * Removes the old mouse-motion-listener from mouse-motion-listener-l * and returns the resulting multicast listener. * @param l mouse-motion-listener-l * @param oldl the mouse-motion-listener being removed */ public static MouseMotionListener remove(MouseMotionListener l, MouseMotionListener oldl) { return (MouseMotionListener) removeInternal(l, oldl); } /** * Removes the old window-listener from window-listener-l and * returns the resulting multicast listener. * @param l window-listener-l * @param oldl the window-listener being removed */ public static WindowListener remove(WindowListener l, WindowListener oldl) { return (WindowListener) removeInternal(l, oldl); } /** * Removes the old window-state-listener from window-state-listener-l * and returns the resulting multicast listener. * @param l window-state-listener-l * @param oldl the window-state-listener being removed * @since 1.4 */ public static WindowStateListener remove(WindowStateListener l, WindowStateListener oldl) { return (WindowStateListener) removeInternal(l, oldl); } /** * Removes the old window-focus-listener from window-focus-listener-l * and returns the resulting multicast listener. * @param l window-focus-listener-l * @param oldl the window-focus-listener being removed * @since 1.4 */ public static WindowFocusListener remove(WindowFocusListener l, WindowFocusListener oldl) { return (WindowFocusListener) removeInternal(l, oldl); } /** * Removes the old action-listener from action-listener-l and * returns the resulting multicast listener. * @param l action-listener-l * @param oldl the action-listener being removed */ public static ActionListener remove(ActionListener l, ActionListener oldl) { return (ActionListener) removeInternal(l, oldl); } /** * Removes the old item-listener from item-listener-l and * returns the resulting multicast listener. * @param l item-listener-l * @param oldl the item-listener being removed */ public static ItemListener remove(ItemListener l, ItemListener oldl) { return (ItemListener) removeInternal(l, oldl); } /** * Removes the old adjustment-listener from adjustment-listener-l and * returns the resulting multicast listener. * @param l adjustment-listener-l * @param oldl the adjustment-listener being removed */ public static AdjustmentListener remove(AdjustmentListener l, AdjustmentListener oldl) { return (AdjustmentListener) removeInternal(l, oldl); } public static TextListener remove(TextListener l, TextListener oldl) { return (TextListener) removeInternal(l, oldl); } /** * Removes the old input-method-listener from input-method-listener-l and * returns the resulting multicast listener. * @param l input-method-listener-l * @param oldl the input-method-listener being removed */ public static InputMethodListener remove(InputMethodListener l, InputMethodListener oldl) { return (InputMethodListener) removeInternal(l, oldl); } /** * Removes the old hierarchy-listener from hierarchy-listener-l and * returns the resulting multicast listener. * @param l hierarchy-listener-l * @param oldl the hierarchy-listener being removed * @since 1.3 */ public static HierarchyListener remove(HierarchyListener l, HierarchyListener oldl) { return (HierarchyListener) removeInternal(l, oldl); } /** * Removes the old hierarchy-bounds-listener from * hierarchy-bounds-listener-l and returns the resulting multicast * listener. * @param l hierarchy-bounds-listener-l * @param oldl the hierarchy-bounds-listener being removed * @since 1.3 */ public static HierarchyBoundsListener remove(HierarchyBoundsListener l, HierarchyBoundsListener oldl) { return (HierarchyBoundsListener) removeInternal(l, oldl); } /** * Removes the old mouse-wheel-listener from mouse-wheel-listener-l * and returns the resulting multicast listener. * @param l mouse-wheel-listener-l * @param oldl the mouse-wheel-listener being removed * @since 1.4 */ public static MouseWheelListener remove(MouseWheelListener l, MouseWheelListener oldl) { return (MouseWheelListener) removeInternal(l, oldl); } /** * Returns the resulting multicast listener from adding listener-a * and listener-b together. * If listener-a is null, it returns listener-b; * If listener-b is null, it returns listener-a * If neither are null, then it creates and returns * a new AWTEventMulticaster instance which chains a with b. * @param a event listener-a * @param b event listener-b */ protected static EventListener addInternal(EventListener a, EventListener b) { if (a == null) return b; if (b == null) return a; return new AWTEventMulticaster(a, b); } /** * Returns the resulting multicast listener after removing the * old listener from listener-l. * If listener-l equals the old listener OR listener-l is null, * returns null. * Else if listener-l is an instance of AWTEventMulticaster, * then it removes the old listener from it. * Else, returns listener l. * @param l the listener being removed from * @param oldl the listener being removed */ protected static EventListener removeInternal(EventListener l, EventListener oldl) { if (l == oldl || l == null) { return null; } else if (l instanceof AWTEventMulticaster) { return ((AWTEventMulticaster)l).remove(oldl); } else { return l; // it's not here } } /* Serialization support. */ protected void saveInternal(ObjectOutputStream s, String k) throws IOException { if (a instanceof AWTEventMulticaster) { ((AWTEventMulticaster)a).saveInternal(s, k); } else if (a instanceof Serializable) { s.writeObject(k); s.writeObject(a); } if (b instanceof AWTEventMulticaster) { ((AWTEventMulticaster)b).saveInternal(s, k); } else if (b instanceof Serializable) { s.writeObject(k); s.writeObject(b); } } protected static void save(ObjectOutputStream s, String k, EventListener l) throws IOException { if (l == null) { return; } else if (l instanceof AWTEventMulticaster) { ((AWTEventMulticaster)l).saveInternal(s, k); } else if (l instanceof Serializable) { s.writeObject(k); s.writeObject(l); } } /* * Recursive method which returns a count of the number of listeners in * EventListener, handling the (common) case of l actually being an * AWTEventMulticaster. Additionally, only listeners of type listenerType * are counted. Method modified to fix bug 4513402. -bchristi */ private static int getListenerCount(EventListener l, Class<?> listenerType) { if (l instanceof AWTEventMulticaster) { AWTEventMulticaster mc = (AWTEventMulticaster)l; return getListenerCount(mc.a, listenerType) + getListenerCount(mc.b, listenerType); } else { // Only count listeners of correct type return listenerType.isInstance(l) ? 1 : 0; } } /* * Recusive method which populates EventListener array a with EventListeners * from l. l is usually an AWTEventMulticaster. Bug 4513402 revealed that * if l differed in type from the element type of a, an ArrayStoreException * would occur. Now l is only inserted into a if it's of the appropriate * type. -bchristi */ private static int populateListenerArray(EventListener[] a, EventListener l, int index) { if (l instanceof AWTEventMulticaster) { AWTEventMulticaster mc = (AWTEventMulticaster)l; int lhs = populateListenerArray(a, mc.a, index); return populateListenerArray(a, mc.b, lhs); } else if (a.getClass().getComponentType().isInstance(l)) { a[index] = l; return index + 1; } // Skip nulls, instances of wrong class else { return index; } } /** * Returns an array of all the objects chained as * <code><em>Foo</em>Listener</code>s by the specified * <code>java.util.EventListener</code>. * <code><em>Foo</em>Listener</code>s are chained by the * <code>AWTEventMulticaster</code> using the * <code>add<em>Foo</em>Listener</code> method. * If a <code>null</code> listener is specified, this method returns an * empty array. If the specified listener is not an instance of * <code>AWTEventMulticaster</code>, this method returns an array which * contains only the specified listener. If no such listeners are chained, * this method returns an empty array. * * @param l the specified <code>java.util.EventListener</code> * @param listenerType the type of listeners requested; this parameter * should specify an interface that descends from * <code>java.util.EventListener</code> * @return an array of all objects chained as * <code><em>Foo</em>Listener</code>s by the specified multicast * listener, or an empty array if no such listeners have been * chained by the specified multicast listener * @exception NullPointerException if the specified * {@code listenertype} parameter is {@code null} * @exception ClassCastException if <code>listenerType</code> * doesn't specify a class or interface that implements * <code>java.util.EventListener</code> * * @since 1.4 */ @SuppressWarnings("unchecked") public static <T extends EventListener> T[] getListeners(EventListener l, Class<T> listenerType) { if (listenerType == null) { throw new NullPointerException ("Listener type should not be null"); } int n = getListenerCount(l, listenerType); T[] result = (T[])Array.newInstance(listenerType, n); populateListenerArray(result, l, 0); return result; } }
googleapis/google-cloud-java
36,595
java-errorreporting/proto-google-cloud-error-reporting-v1beta1/src/main/java/com/google/devtools/clouderrorreporting/v1beta1/ServiceContext.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/clouderrorreporting/v1beta1/common.proto // Protobuf Java Version: 3.25.8 package com.google.devtools.clouderrorreporting.v1beta1; /** * * * <pre> * Describes a running service that sends errors. * Its version changes over time and multiple versions can run in parallel. * </pre> * * Protobuf type {@code google.devtools.clouderrorreporting.v1beta1.ServiceContext} */ public final class ServiceContext extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.clouderrorreporting.v1beta1.ServiceContext) ServiceContextOrBuilder { private static final long serialVersionUID = 0L; // Use ServiceContext.newBuilder() to construct. private ServiceContext(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ServiceContext() { service_ = ""; version_ = ""; resourceType_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ServiceContext(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.clouderrorreporting.v1beta1.CommonProto .internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.clouderrorreporting.v1beta1.CommonProto .internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContext_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.class, com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.Builder.class); } public static final int SERVICE_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object service_ = ""; /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @return The service. */ @java.lang.Override public java.lang.String getService() { java.lang.Object ref = service_; 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(); service_ = s; return s; } } /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @return The bytes for service. */ @java.lang.Override public com.google.protobuf.ByteString getServiceBytes() { java.lang.Object ref = service_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); service_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VERSION_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object version_ = ""; /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @return The version. */ @java.lang.Override public java.lang.String getVersion() { java.lang.Object ref = version_; 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(); version_ = s; return s; } } /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @return The bytes for version. */ @java.lang.Override public com.google.protobuf.ByteString getVersionBytes() { java.lang.Object ref = version_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); version_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESOURCE_TYPE_FIELD_NUMBER = 4; @SuppressWarnings("serial") private volatile java.lang.Object resourceType_ = ""; /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @return The resourceType. */ @java.lang.Override public java.lang.String getResourceType() { java.lang.Object ref = resourceType_; 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(); resourceType_ = s; return s; } } /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @return The bytes for resourceType. */ @java.lang.Override public com.google.protobuf.ByteString getResourceTypeBytes() { java.lang.Object ref = resourceType_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resourceType_ = 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(service_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, service_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, version_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceType_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, resourceType_); } 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(service_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, service_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(version_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, version_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resourceType_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, resourceType_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.devtools.clouderrorreporting.v1beta1.ServiceContext)) { return super.equals(obj); } com.google.devtools.clouderrorreporting.v1beta1.ServiceContext other = (com.google.devtools.clouderrorreporting.v1beta1.ServiceContext) obj; if (!getService().equals(other.getService())) return false; if (!getVersion().equals(other.getVersion())) return false; if (!getResourceType().equals(other.getResourceType())) 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) + SERVICE_FIELD_NUMBER; hash = (53 * hash) + getService().hashCode(); hash = (37 * hash) + VERSION_FIELD_NUMBER; hash = (53 * hash) + getVersion().hashCode(); hash = (37 * hash) + RESOURCE_TYPE_FIELD_NUMBER; hash = (53 * hash) + getResourceType().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.devtools.clouderrorreporting.v1beta1.ServiceContext 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> * Describes a running service that sends errors. * Its version changes over time and multiple versions can run in parallel. * </pre> * * Protobuf type {@code google.devtools.clouderrorreporting.v1beta1.ServiceContext} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.clouderrorreporting.v1beta1.ServiceContext) com.google.devtools.clouderrorreporting.v1beta1.ServiceContextOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.devtools.clouderrorreporting.v1beta1.CommonProto .internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.devtools.clouderrorreporting.v1beta1.CommonProto .internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContext_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.class, com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.Builder.class); } // Construct using com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; service_ = ""; version_ = ""; resourceType_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.devtools.clouderrorreporting.v1beta1.CommonProto .internal_static_google_devtools_clouderrorreporting_v1beta1_ServiceContext_descriptor; } @java.lang.Override public com.google.devtools.clouderrorreporting.v1beta1.ServiceContext getDefaultInstanceForType() { return com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.getDefaultInstance(); } @java.lang.Override public com.google.devtools.clouderrorreporting.v1beta1.ServiceContext build() { com.google.devtools.clouderrorreporting.v1beta1.ServiceContext result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.devtools.clouderrorreporting.v1beta1.ServiceContext buildPartial() { com.google.devtools.clouderrorreporting.v1beta1.ServiceContext result = new com.google.devtools.clouderrorreporting.v1beta1.ServiceContext(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.devtools.clouderrorreporting.v1beta1.ServiceContext result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.service_ = service_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.version_ = version_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.resourceType_ = resourceType_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.devtools.clouderrorreporting.v1beta1.ServiceContext) { return mergeFrom((com.google.devtools.clouderrorreporting.v1beta1.ServiceContext) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.devtools.clouderrorreporting.v1beta1.ServiceContext other) { if (other == com.google.devtools.clouderrorreporting.v1beta1.ServiceContext.getDefaultInstance()) return this; if (!other.getService().isEmpty()) { service_ = other.service_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getVersion().isEmpty()) { version_ = other.version_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getResourceType().isEmpty()) { resourceType_ = other.resourceType_; 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 18: { service_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 18 case 26: { version_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 26 case 34: { resourceType_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; 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 service_ = ""; /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @return The service. */ public java.lang.String getService() { java.lang.Object ref = service_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); service_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @return The bytes for service. */ public com.google.protobuf.ByteString getServiceBytes() { java.lang.Object ref = service_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); service_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @param value The service to set. * @return This builder for chaining. */ public Builder setService(java.lang.String value) { if (value == null) { throw new NullPointerException(); } service_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @return This builder for chaining. */ public Builder clearService() { service_ = getDefaultInstance().getService(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * An identifier of the service, such as the name of the * executable, job, or Google App Engine service name. This field is expected * to have a low number of values that are relatively stable over time, as * opposed to `version`, which can be changed whenever new code is deployed. * * Contains the service name for error reports extracted from Google * App Engine logs or `default` if the App Engine default service is used. * </pre> * * <code>string service = 2;</code> * * @param value The bytes for service to set. * @return This builder for chaining. */ public Builder setServiceBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); service_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object version_ = ""; /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @return The version. */ public java.lang.String getVersion() { java.lang.Object ref = version_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); version_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @return The bytes for version. */ public com.google.protobuf.ByteString getVersionBytes() { java.lang.Object ref = version_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); version_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @param value The version to set. * @return This builder for chaining. */ public Builder setVersion(java.lang.String value) { if (value == null) { throw new NullPointerException(); } version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @return This builder for chaining. */ public Builder clearVersion() { version_ = getDefaultInstance().getVersion(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Represents the source code version that the developer provided, * which could represent a version label or a Git SHA-1 hash, for example. * For App Engine standard environment, the version is set to the version of * the app. * </pre> * * <code>string version = 3;</code> * * @param value The bytes for version to set. * @return This builder for chaining. */ public Builder setVersionBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); version_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object resourceType_ = ""; /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @return The resourceType. */ public java.lang.String getResourceType() { java.lang.Object ref = resourceType_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resourceType_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @return The bytes for resourceType. */ public com.google.protobuf.ByteString getResourceTypeBytes() { java.lang.Object ref = resourceType_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); resourceType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @param value The resourceType to set. * @return This builder for chaining. */ public Builder setResourceType(java.lang.String value) { if (value == null) { throw new NullPointerException(); } resourceType_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @return This builder for chaining. */ public Builder clearResourceType() { resourceType_ = getDefaultInstance().getResourceType(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * * * <pre> * Type of the MonitoredResource. List of possible values: * https://cloud.google.com/monitoring/api/resources * * Value is set automatically for incoming errors and must not be set when * reporting errors. * </pre> * * <code>string resource_type = 4;</code> * * @param value The bytes for resourceType to set. * @return This builder for chaining. */ public Builder setResourceTypeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); resourceType_ = 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.devtools.clouderrorreporting.v1beta1.ServiceContext) } // @@protoc_insertion_point(class_scope:google.devtools.clouderrorreporting.v1beta1.ServiceContext) private static final com.google.devtools.clouderrorreporting.v1beta1.ServiceContext DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.devtools.clouderrorreporting.v1beta1.ServiceContext(); } public static com.google.devtools.clouderrorreporting.v1beta1.ServiceContext getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ServiceContext> PARSER = new com.google.protobuf.AbstractParser<ServiceContext>() { @java.lang.Override public ServiceContext 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<ServiceContext> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ServiceContext> getParserForType() { return PARSER; } @java.lang.Override public com.google.devtools.clouderrorreporting.v1beta1.ServiceContext getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/ignite
37,027
modules/core/src/main/java/org/apache/ignite/Ignite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite; import java.util.Collection; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import javax.cache.CacheException; import org.apache.ignite.cache.CacheInterceptor; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cache.query.annotations.QuerySqlFunction; import org.apache.ignite.cluster.ClusterGroup; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.configuration.AtomicConfiguration; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.CollectionConfiguration; import org.apache.ignite.configuration.DataRegionConfiguration; import org.apache.ignite.configuration.DataStorageConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.util.typedef.G; import org.apache.ignite.lang.IgniteExperimental; import org.apache.ignite.lang.IgniteProductVersion; import org.apache.ignite.metric.IgniteMetrics; import org.apache.ignite.plugin.IgnitePlugin; import org.apache.ignite.plugin.PluginNotFoundException; import org.apache.ignite.session.SessionContextProvider; import org.apache.ignite.spi.metric.ReadOnlyMetricRegistry; import org.apache.ignite.spi.tracing.TracingConfigurationManager; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Main entry-point for all Ignite APIs. * You can obtain an instance of {@code Ignite} through {@link Ignition#ignite()}, * or for named grids you can use {@link Ignition#ignite(String)}. Note that you * can have multiple instances of {@code Ignite} running in the same VM by giving * each instance a different name. * <p> * Ignite provides the following functionality: * <ul> * <li>{@link IgniteCluster} - clustering functionality.</li> * <li>{@link IgniteCache} - functionality for in-memory distributed cache, including SQL, TEXT, and Predicate-based queries.</li> * <li>{@link IgniteTransactions} - distributed ACID-compliant transactions.</li> * <li>{@link IgniteDataStreamer} - functionality for streaming large amounts of data into cache.</li> * <li>{@link IgniteCompute} - functionality for executing tasks and closures on all grid nodes (inherited form {@link ClusterGroup}).</li> * <li>{@link IgniteServices} - distributed service grid functionality (e.g. singletons on the cluster).</li> * <li>{@link IgniteMessaging} - * functionality for topic-based message exchange on all grid nodes (inherited form {@link ClusterGroup}).</li> * <li>{@link IgniteEvents} - * functionality for querying and listening to events on all grid nodes (inherited form {@link ClusterGroup}).</li> * <li>{@link ExecutorService} - distributed thread pools.</li> * <li>{@link IgniteAtomicLong} - distributed atomic long.</li> * <li>{@link IgniteAtomicReference} - distributed atomic reference.</li> * <li>{@link IgniteAtomicSequence} - distributed atomic sequence.</li> * <li>{@link IgniteAtomicStamped} - distributed atomic stamped reference.</li> * <li>{@link IgniteCountDownLatch} - distributed count down latch.</li> * <li>{@link IgniteQueue} - distributed blocking queue.</li> * <li>{@link IgniteSet} - distributed concurrent set.</li> * <li>{@link IgniteScheduler} - functionality for scheduling jobs using UNIX Cron syntax.</li> * </ul> */ public interface Ignite extends AutoCloseable { /** * Gets the name of the Ignite instance. * The name allows having multiple Ignite instances with different names within the same Java VM. * <p> * If default Ignite instance is used, then {@code null} is returned. * Refer to {@link Ignition} documentation for information on how to start named ignite Instances. * * @return Name of the Ignite instance, or {@code null} for default Ignite instance. */ public String name(); /** * Gets grid's logger. * * @return Grid's logger. */ public IgniteLogger log(); /** * Gets the configuration of this Ignite instance. * <p> * <b>NOTE:</b> * <br> * SPIs obtains through this method should never be used directly. SPIs provide * internal view on the subsystem and is used internally by Ignite kernal. In rare use cases when * access to a specific implementation of this SPI is required - an instance of this SPI can be obtained * via this method to check its configuration properties or call other non-SPI * methods. * * @return Ignite configuration instance. */ public IgniteConfiguration configuration(); /** * Gets an instance of {@link IgniteCluster} interface. * * @return Instance of {@link IgniteCluster} interface. */ public IgniteCluster cluster(); /** * Gets {@code compute} facade over all cluster nodes started in server mode. * * @return Compute instance over all cluster nodes started in server mode. */ public IgniteCompute compute(); /** * Gets custom metrics facade over current node. * * @return {@link IgniteMetrics} instance for current node. */ @IgniteExperimental public IgniteMetrics metrics(); /** * Gets {@code compute} facade over the specified cluster group. All operations * on the returned {@link IgniteCompute} instance will only include nodes from * this cluster group. * * @param grp Cluster group. * @return Compute instance over given cluster group. */ public IgniteCompute compute(ClusterGroup grp); /** * Gets {@code messaging} facade over all cluster nodes. * * @return Messaging instance over all cluster nodes. */ public IgniteMessaging message(); /** * Gets {@code messaging} facade over nodes within the cluster group. All operations * on the returned {@link IgniteMessaging} instance will only include nodes from * the specified cluster group. * * @param grp Cluster group. * @return Messaging instance over given cluster group. */ public IgniteMessaging message(ClusterGroup grp); /** * Gets {@code events} facade over all cluster nodes. * * @return Events instance over all cluster nodes. */ public IgniteEvents events(); /** * Gets {@code events} facade over nodes within the cluster group. All operations * on the returned {@link IgniteEvents} instance will only include nodes from * the specified cluster group. * * @param grp Cluster group. * @return Events instance over given cluster group. */ public IgniteEvents events(ClusterGroup grp); /** * Gets {@code services} facade over all cluster nodes started in server mode. * * @return Services facade over all cluster nodes started in server mode. */ public IgniteServices services(); /** * Gets {@code services} facade over nodes within the cluster group. All operations * on the returned {@link IgniteMessaging} instance will only include nodes from * the specified cluster group. * * @param grp Cluster group. * @return {@code Services} functionality over given cluster group. */ public IgniteServices services(ClusterGroup grp); /** * Creates a new {@link ExecutorService} which will execute all submitted * {@link Callable} and {@link Runnable} jobs on all cluster nodes. * This essentially creates a <b><i>Distributed Thread Pool</i></b> that can * be used as a replacement for local thread pools. * * @return Grid-enabled {@code ExecutorService}. */ public ExecutorService executorService(); /** * Creates a new {@link ExecutorService} which will execute all submitted * {@link Callable} and {@link Runnable} jobs on nodes in the specified cluster group. * This essentially creates a <b><i>Distributed Thread Pool</i></b> that can be used as a * replacement for local thread pools. * * @param grp Cluster group. * @return {@link ExecutorService} which will execute jobs on nodes in given cluster group. */ public ExecutorService executorService(ClusterGroup grp); /** * Gets Ignite version. * * @return Ignite version. */ public IgniteProductVersion version(); /** * Gets an instance of cron-based scheduler. * * @return Instance of scheduler. */ public IgniteScheduler scheduler(); /** * Dynamically starts new cache with the given cache configuration. * <p> * If local node is an affinity node, this method will return the instance of started cache. * Otherwise, it will create a client cache on local node. * <p> * If a cache with the same name already exists in the grid, an exception will be thrown regardless * whether the given configuration matches the configuration of the existing cache or not. * * @param cacheCfg Cache configuration to use. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return Instance of started cache. * @throws CacheException If a cache with the same name already exists or other error occurs. */ public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg) throws CacheException; /** * Dynamically starts new caches with the given cache configurations. * <p> * If local node is an affinity node, this method will return the instance of started caches. * Otherwise, it will create a client caches on local node. * <p> * If for one of configurations a cache with the same name already exists in the grid, an exception will be thrown regardless * whether the given configuration matches the configuration of the existing cache or not. * * @param cacheCfgs Collection of cache configuration to use. * @return Collection of instances of started caches. * @throws CacheException If one of created caches exists or other error occurs. */ public Collection<IgniteCache> createCaches(Collection<CacheConfiguration> cacheCfgs) throws CacheException; /** * Dynamically starts new cache using template configuration. * <p> * If local node is an affinity node, this method will return the instance of started cache. * Otherwise, it will create a client cache on local node. * <p> * If a cache with the same name already exists in the grid, an exception will be thrown. * * @param cacheName Cache name. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return Instance of started cache. * @throws CacheException If a cache with the same name already exists or other error occurs. */ public <K, V> IgniteCache<K, V> createCache(String cacheName) throws CacheException; /** * Gets existing cache with the given name or creates new one with the given configuration. * <p> * If a cache with the same name already exist, this method will not check that the given * configuration matches the configuration of existing cache and will return an instance * of the existing cache. * * @param cacheCfg Cache configuration to use. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return Existing or newly created cache. * @throws CacheException If error occurs. */ public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg) throws CacheException; /** * Gets existing cache with the given name or creates new one using template configuration. * * @param cacheName Cache name. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return Existing or newly created cache. * @throws CacheException If error occurs. */ public <K, V> IgniteCache<K, V> getOrCreateCache(String cacheName) throws CacheException; /** * Gets existing caches with the given name or created one with the given configuration. * <p> * If a cache with the same name already exist, this method will not check that the given * configuration matches the configuration of existing cache and will return an instance * of the existing cache. * * @param cacheCfgs Collection of cache configuration to use. * @return Collection of existing or newly created caches. * @throws CacheException If error occurs. */ public Collection<IgniteCache> getOrCreateCaches(Collection<CacheConfiguration> cacheCfgs) throws CacheException; /** * Adds cache configuration template. * * @param cacheCfg Cache configuration template. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @throws CacheException If error occurs. */ public <K, V> void addCacheConfiguration(CacheConfiguration<K, V> cacheCfg) throws CacheException; /** * Dynamically starts new cache with the given cache configuration. * <p> * If local node is an affinity node, this method will return the instance of started cache. * Otherwise, it will create a near cache with the given configuration on local node. * <p> * If a cache with the same name already exists in the grid, an exception will be thrown regardless * whether the given configuration matches the configuration of the existing cache or not. * * @param cacheCfg Cache configuration to use. * @param nearCfg Near cache configuration to use on local node in case it is not an * affinity node. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @throws CacheException If a cache with the same name already exists or other error occurs. * @return Instance of started cache. */ public <K, V> IgniteCache<K, V> createCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) throws CacheException; /** * Gets existing cache with the given cache configuration or creates one if it does not exist. * <p> * If a cache with the same name already exist, this method will not check that the given * configuration matches the configuration of existing cache and will return an instance * of the existing cache. * <p> * If local node is not an affinity node and a client cache without near cache has been already started * on this node, an exception will be thrown. * * @param cacheCfg Cache configuration. * @param nearCfg Near cache configuration for client. * @param <K> type. * @param <V> type. * @return {@code IgniteCache} instance. * @throws CacheException If error occurs. */ public <K, V> IgniteCache<K, V> getOrCreateCache(CacheConfiguration<K, V> cacheCfg, NearCacheConfiguration<K, V> nearCfg) throws CacheException; /** * Starts a near cache on local node if cache was previously started with one of the * {@link #createCache(CacheConfiguration)} or {@link #createCache(CacheConfiguration, NearCacheConfiguration)} * methods. * * @param cacheName Cache name. * @param nearCfg Near cache configuration. * @return Cache instance. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @throws CacheException If error occurs. */ public <K, V> IgniteCache<K, V> createNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) throws CacheException; /** * Gets existing near cache with the given name or creates a new one. * * @param cacheName Cache name. * @param nearCfg Near configuration. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return {@code IgniteCache} instance. * @throws CacheException If error occurs. */ public <K, V> IgniteCache<K, V> getOrCreateNearCache(String cacheName, NearCacheConfiguration<K, V> nearCfg) throws CacheException; /** * Destroys a cache with the given name and cleans data that was written to the cache. The call will * deallocate all resources associated with the given cache on all nodes in the cluster. There is no way * to undo the action and recover destroyed data. * <p> * All existing instances of {@link IgniteCache} will be invalidated, subsequent calls to the API * will throw exceptions. * <p> * If a cache with the specified name does not exist in the grid, the operation has no effect. * * @param cacheName Cache name to destroy. * @throws CacheException If error occurs. */ public void destroyCache(String cacheName) throws CacheException; /** * Destroys caches with the given names and cleans data that was written to the caches. The call will * deallocate all resources associated with the given caches on all nodes in the cluster. There is no way * to undo the action and recover destroyed data. * <p> * All existing instances of {@link IgniteCache} will be invalidated, subsequent calls to the API * will throw exceptions. * <p> * If the specified collection contains {@code null} or an empty value, * this method will throw {@link IllegalArgumentException} and the caches will not be destroyed. * <p> * If a cache with the specified name does not exist in the grid, the specified value will be skipped. * * @param cacheNames Collection of cache names to destroy. * @throws CacheException If error occurs. */ public void destroyCaches(Collection<String> cacheNames) throws CacheException; /** * Gets an instance of {@link IgniteCache} API for the given name if one is configured or {@code null} otherwise. * {@code IgniteCache} is a fully-compatible implementation of {@code JCache (JSR 107)} specification. * * @param name Cache name. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return Instance of the cache for the specified name or {@code null} if one does not exist. * @throws CacheException If error occurs. */ public <K, V> IgniteCache<K, V> cache(String name) throws CacheException; /** * Gets the collection of names of currently available caches. * * @return Collection of names of currently available caches or an empty collection if no caches are available. */ public Collection<String> cacheNames(); /** * Gets grid transactions facade. * * @return Grid transactions facade. */ public IgniteTransactions transactions(); /** * Gets a new instance of data streamer associated with given cache name. Data streamer * is responsible for loading external data into in-memory data grid. For more information * refer to {@link IgniteDataStreamer} documentation. * * @param cacheName Cache name. * @param <K> Type of the cache key. * @param <V> Type of the cache value. * @return Data streamer. * @throws IllegalStateException If node is stopping. */ public <K, V> IgniteDataStreamer<K, V> dataStreamer(String cacheName) throws IllegalStateException; /** * Will get an atomic sequence from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. It will use configuration from {@link IgniteConfiguration#getAtomicConfiguration()}. * * @param name Sequence name. * @param initVal Initial value for sequence. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return Sequence for the given name. * @throws IgniteException If sequence could not be fetched or created. */ public IgniteAtomicSequence atomicSequence(String name, long initVal, boolean create) throws IgniteException; /** * Will get an atomic sequence from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. * * @param name Sequence name. * @param cfg Configuration. * @param initVal Initial value for sequence. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return Sequence for the given name. * @throws IgniteException If sequence could not be fetched or created. */ public IgniteAtomicSequence atomicSequence(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException; /** * Will get a atomic long from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. * * @param name Name of atomic long. * @param initVal Initial value for atomic long. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return Atomic long. * @throws IgniteException If atomic long could not be fetched or created. */ public IgniteAtomicLong atomicLong(String name, long initVal, boolean create) throws IgniteException; /** * Will get a atomic long from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. * * @param name Name of atomic long. * @param cfg Configuration. * @param initVal Initial value for atomic long. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return Atomic long. * @throws IgniteException If atomic long could not be fetched or created. */ public IgniteAtomicLong atomicLong(String name, AtomicConfiguration cfg, long initVal, boolean create) throws IgniteException; /** * Will get a atomic reference from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. It will use configuration from {@link IgniteConfiguration#getAtomicConfiguration()}. * * @param name Atomic reference name. * @param initVal Initial value for atomic reference. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @param <T> Type of object referred to by this reference. * @return Atomic reference for the given name. * @throws IgniteException If atomic reference could not be fetched or created. */ public <T> IgniteAtomicReference<T> atomicReference(String name, @Nullable T initVal, boolean create) throws IgniteException; /** * Will get a atomic reference from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. * * @param name Atomic reference name. * @param cfg Configuration. * @param initVal Initial value for atomic reference. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @param <T> Type of object referred to by this reference. * @return Atomic reference for the given name. * @throws IgniteException If atomic reference could not be fetched or created. */ public <T> IgniteAtomicReference<T> atomicReference(String name, AtomicConfiguration cfg, @Nullable T initVal, boolean create) throws IgniteException; /** * Will get a atomic stamped from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. * * @param name Atomic stamped name. * @param initVal Initial value for atomic stamped. Ignored if {@code create} flag is {@code false}. * @param initStamp Initial stamp for atomic stamped. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @param <T> Type of object referred to by this atomic. * @param <S> Type of stamp object. * @return Atomic stamped for the given name. * @throws IgniteException If atomic stamped could not be fetched or created. */ public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException; /** * Will get a atomic stamped from cache and create one if it has not been created yet and {@code create} flag * is {@code true}. * * @param name Atomic stamped name. * @param cfg Configuration. * @param initVal Initial value for atomic stamped. Ignored if {@code create} flag is {@code false}. * @param initStamp Initial stamp for atomic stamped. Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @param <T> Type of object referred to by this atomic. * @param <S> Type of stamp object. * @return Atomic stamped for the given name. * @throws IgniteException If atomic stamped could not be fetched or created. */ public <T, S> IgniteAtomicStamped<T, S> atomicStamped(String name, AtomicConfiguration cfg, @Nullable T initVal, @Nullable S initStamp, boolean create) throws IgniteException; /** * Gets or creates count down latch. If count down latch is not found in cache and {@code create} flag * is {@code true}, it is created using provided name and count parameter. * * @param name Name of the latch. * @param cnt Count for new latch creation. Ignored if {@code create} flag is {@code false}. * @param autoDel {@code True} to automatically delete latch from cache when its count reaches zero. * Ignored if {@code create} flag is {@code false}. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return Count down latch for the given name. * @throws IgniteException If latch could not be fetched or created. */ public IgniteCountDownLatch countDownLatch(String name, int cnt, boolean autoDel, boolean create) throws IgniteException; /** * Gets or creates semaphore. If semaphore is not found in cache and {@code create} flag * is {@code true}, it is created using provided name and count parameter. * * @param name Name of the semaphore. * @param cnt Count for new semaphore creation. Ignored if {@code create} flag is {@code false}. * @param failoverSafe {@code True} to create failover safe semaphore which means that * if any node leaves topology permits already acquired by that node are silently released * and become available for alive nodes to acquire. If flag is {@code false} then * all threads waiting for available permits get interrupted. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return Semaphore for the given name. * @throws IgniteException If semaphore could not be fetched or created. */ public IgniteSemaphore semaphore(String name, int cnt, boolean failoverSafe, boolean create) throws IgniteException; /** * Gets or creates reentrant lock. If reentrant lock is not found in cache and {@code create} flag * is {@code true}, it is created using provided name. * * @param name Name of the lock. * @param failoverSafe {@code True} to create failover safe lock which means that * if any node leaves topology, all locks already acquired by that node are silently released * and become available for other nodes to acquire. If flag is {@code false} then * all threads on other nodes waiting to acquire lock are interrupted. * @param fair If {@code True}, fair lock will be created. * @param create Boolean flag indicating whether data structure should be created if does not exist. * @return ReentrantLock for the given name. * @throws IgniteException If reentrant lock could not be fetched or created. */ public IgniteLock reentrantLock(String name, boolean failoverSafe, boolean fair, boolean create) throws IgniteException; /** * Will get a named queue from cache and create one if it has not been created yet and {@code cfg} is not * {@code null}. * If queue is present already, queue properties will not be changed. Use * collocation for {@link CacheMode#PARTITIONED} caches if you have lots of relatively * small queues as it will make fetching, querying, and iteration a lot faster. If you have * few very large queues, then you should consider turning off collocation as they simply * may not fit in a single node's memory. * * @param name Name of queue. * @param cap Capacity of queue, {@code 0} for unbounded queue. Ignored if {@code cfg} is {@code null}. * @param cfg Queue configuration if new queue should be created. * @param <T> Type of the elements in queue. * @return Queue with given properties. * @throws IgniteException If queue could not be fetched or created. */ public <T> IgniteQueue<T> queue(String name, int cap, @Nullable CollectionConfiguration cfg) throws IgniteException; /** * Will get a named set from cache and create one if it has not been created yet and {@code cfg} is not * {@code null}. * * @param name Set name. * @param cfg Set configuration if new set should be created. * @param <T> Type of the elements in set. * @return Set with given properties. * @throws IgniteException If set could not be fetched or created. */ public <T> IgniteSet<T> set(String name, @Nullable CollectionConfiguration cfg) throws IgniteException; /** * Gets an instance of deployed Ignite plugin. * * @param name Plugin name. * @param <T> Plugin type. * @return Plugin instance. * @throws PluginNotFoundException If plugin for the given name was not found. */ public <T extends IgnitePlugin> T plugin(String name) throws PluginNotFoundException; /** * Gets an instance of {@link IgniteBinary} interface. * * @return Instance of {@link IgniteBinary} interface. */ public IgniteBinary binary(); /** * Closes {@code this} instance of grid. This method is identical to calling * {@link G#stop(String, boolean) G.stop(igniteInstanceName, true)}. * <p> * The method is invoked automatically on objects managed by the * {@code try-with-resources} statement. * * @throws IgniteException If failed to stop grid. */ @Override public void close() throws IgniteException; /** * Gets affinity service to provide information about data partitioning and distribution. * * @param cacheName Cache name. * @param <K> Cache key type. * @return Affinity. */ public <K> Affinity<K> affinity(String cacheName); /** * Checks Ignite grid is active or not active. * * @return {@code True} if grid is active. {@code False} If grid is not active. * @deprecated Use {@link IgniteCluster#state()} instead. */ @Deprecated public boolean active(); /** * Changes Ignite grid state to active or inactive. * <p> * <b>NOTE:</b> * Deactivation clears in-memory caches (without persistence) including the system caches. * * @param active If {@code True} start activation process. If {@code False} start deactivation process. * @throws IgniteException If there is an already started transaction or lock in the same thread. * @deprecated Use {@link IgniteCluster#state(ClusterState)} instead. */ @Deprecated public void active(boolean active); /** * Clears partition's lost state and moves caches to a normal mode. * <p> * To avoid permanent data loss for persistent caches it's recommended to return all previously failed baseline * nodes to the topology before calling this method. * * @param cacheNames Name of the caches for which lost partitions is reset. */ public void resetLostPartitions(Collection<String> cacheNames); /** * @return Collection of {@link MemoryMetrics} snapshots. * @deprecated Check the {@link ReadOnlyMetricRegistry} with "name=io.dataregion.{data_region_name}" instead. */ @Deprecated public Collection<MemoryMetrics> memoryMetrics(); /** * @param dataRegionName Name of the data region. * @return {@link MemoryMetrics} snapshot or {@code null} if no memory region is configured under specified name. * @deprecated Check the {@link ReadOnlyMetricRegistry} with "name=io.dataregion.{data_region_name}" instead. */ @Deprecated @Nullable public MemoryMetrics memoryMetrics(String dataRegionName); /** * Returns a collection of {@link DataRegionMetrics} that reflects page memory usage on this Apache Ignite node * instance. * Returns the collection that contains the latest snapshots for each memory region * configured with {@link DataRegionConfiguration configuration} on this Ignite node instance. * * @return Collection of {@link DataRegionMetrics} snapshots. * @deprecated Check the {@link ReadOnlyMetricRegistry} with "name=io.dataregion.{data_region_name}" instead. */ public Collection<DataRegionMetrics> dataRegionMetrics(); /** * Returns the latest {@link DataRegionMetrics} snapshot for the memory region of the given name. * * To get the metrics for the default memory region use * {@link DataStorageConfiguration#DFLT_DATA_REG_DEFAULT_NAME} as the name * or a custom name if the default memory region has been renamed. * * @param memPlcName Name of memory region configured with {@link DataRegionConfiguration config}. * @return {@link DataRegionMetrics} snapshot or {@code null} if no memory region is configured under specified name. */ @Nullable public DataRegionMetrics dataRegionMetrics(String memPlcName); /** * Gets an instance of {@link IgniteEncryption} interface. * * @return Instance of {@link IgniteEncryption} interface. */ public IgniteEncryption encryption(); /** * @return Snapshot manager. */ public IgniteSnapshot snapshot(); /** * Returns the {@link TracingConfigurationManager} instance that allows to * <ul> * <li>Configure tracing parameters such as sampling rate for the specific tracing coordinates * such as scope and label.</li> * <li>Retrieve the most specific tracing parameters for the specified tracing coordinates (scope and label)</li> * <li>Restore the tracing parameters for the specified tracing coordinates to the default.</li> * <li>List all pairs of tracing configuration coordinates and tracing configuration parameters.</li> * </ul> * @return {@link TracingConfigurationManager} instance. */ @IgniteExperimental public @NotNull TracingConfigurationManager tracingConfiguration(); /** * Underlying operations of returned Ignite instance are aware of application attributes. * User defined functions can access the attributes with {@link SessionContextProvider} API. * List of supported types of user defined functions that have access the attributes: * <ul> * <li>{@link QuerySqlFunction}</li> * <li>{@link CacheInterceptor}</li> * </ul> * * @param attrs Application attributes. * @return Ignite instance that is aware of application attributes. */ @IgniteExperimental public Ignite withApplicationAttributes(Map<String, String> attrs); }
apache/iotdb
36,625
iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/schema/column/ColumnHeaderConstant.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.commons.schema.column; import com.google.common.collect.ImmutableList; import org.apache.tsfile.enums.TSDataType; import java.util.List; public class ColumnHeaderConstant { private ColumnHeaderConstant() { // forbidding instantiation } // column names for query statement public static final String TIME = "Time"; public static final String ENDTIME = "__endTime"; public static final String VALUE = "Value"; public static final String DEVICE = "Device"; public static final String DEVICE_ID = "DeviceID"; public static final String EXPLAIN_ANALYZE = "Explain Analyze"; // column names for schema statement public static final String DATABASE = "Database"; public static final String TIMESERIES = "Timeseries"; public static final String ALIAS = "Alias"; public static final String DATATYPE = "DataType"; public static final String ENCODING = "Encoding"; public static final String COMPRESSION = "Compression"; public static final String TAGS = "Tags"; public static final String ATTRIBUTES = "Attributes"; public static final String NOTES = "Notes"; public static final String DEADBAND = "Deadband"; public static final String DEADBAND_PARAMETERS = "DeadbandParameters"; public static final String IS_ALIGNED = "IsAligned"; public static final String TEMPLATE = "Template"; public static final String COUNT = "Count"; public static final String COLUMN_TTL = "TTL(ms)"; public static final String SCHEMA_REPLICATION_FACTOR = "SchemaReplicationFactor"; public static final String DATA_REPLICATION_FACTOR = "DataReplicationFactor"; public static final String TIME_PARTITION_ORIGIN = "TimePartitionOrigin"; public static final String TIME_PARTITION_INTERVAL = "TimePartitionInterval"; public static final String SCHEMA_REGION_GROUP_NUM = "SchemaRegionGroupNum"; public static final String MIN_SCHEMA_REGION_GROUP_NUM = "MinSchemaRegionGroupNum"; public static final String MAX_SCHEMA_REGION_GROUP_NUM = "MaxSchemaRegionGroupNum"; public static final String DATA_REGION_GROUP_NUM = "DataRegionGroupNum"; public static final String MIN_DATA_REGION_GROUP_NUM = "MinDataRegionGroupNum"; public static final String MAX_DATA_REGION_GROUP_NUM = "MaxDataRegionGroupNum"; public static final String CHILD_PATHS = "ChildPaths"; public static final String NODE_TYPES = "NodeTypes"; public static final String CHILD_NODES = "ChildNodes"; public static final String VERSION = "Version"; public static final String BUILD_INFO = "BuildInfo"; public static final String PATHS = "Paths"; public static final String PATH = "Path"; public static final String VARIABLE = "Variable"; public static final String SCOPE = "Scope"; // column names for count statement public static final String COLUMN = "Column"; public static final String COUNT_DEVICES = "count(devices)"; public static final String COUNT_NODES = "count(nodes)"; public static final String COUNT_TIMESERIES = "count(timeseries)"; public static final String COUNT_DATABASE = "count(database)"; public static final String COUNT_INSTANCES = "Count(instances)"; // column names for show cluster and show cluster details statements public static final String NODE_ID = "NodeID"; public static final String NODE_TYPE = "NodeType"; public static final String STATUS = "Status"; public static final String INTERNAL_ADDRESS = "InternalAddress"; public static final String INTERNAL_PORT = "InternalPort"; public static final String CONFIG_CONSENSUS_PORT = "ConfigConsensusPort"; public static final String RPC_ADDRESS = "RpcAddress"; public static final String RPC_PORT = "RpcPort"; public static final String DATA_CONSENSUS_PORT = "DataConsensusPort"; public static final String SCHEMA_CONSENSUS_PORT = "SchemaConsensusPort"; public static final String MPP_PORT = "MppPort"; // column names for show clusterId statement public static final String CLUSTER_ID = "ClusterId"; // column names for verify connection statement public static final String SERVICE_PROVIDER = "ServiceProvider"; public static final String SENDER = "Sender"; public static final String CONNECTION = "Connection"; // column names for show functions statement public static final String FUNCTION_NAME = "FunctionName"; public static final String FUNCTION_TYPE = "FunctionType"; public static final String CLASS_NAME_UDF = "ClassName(UDF)"; public static final String FUNCTION_STATE = "State"; // column names for show triggers statement public static final String TRIGGER_NAME = "TriggerName"; public static final String EVENT = "Event"; public static final String STATE = "State"; public static final String MODEL_TYPE = "ModelType"; public static final String CONFIGS = "Configs"; public static final String PATH_PATTERN = "PathPattern"; public static final String CLASS_NAME = "ClassName"; // column names for show pipe plugins statement public static final String PLUGIN_NAME = "PluginName"; public static final String PLUGIN_TYPE = "PluginType"; public static final String PLUGIN_JAR = "PluginJar"; // column names for show topics statement public static final String TOPIC_NAME = "TopicName"; public static final String TOPIC_CONFIGS = "TopicConfigs"; // column names for show subscriptions statement public static final String CONSUMER_GROUP_NAME = "ConsumerGroupName"; public static final String SUBSCRIBED_CONSUMERS = "SubscribedConsumers"; public static final String SUBSCRIPTION_ID = "SubscriptionID"; // show cluster status public static final String NODE_TYPE_CONFIG_NODE = "ConfigNode"; public static final String NODE_TYPE_DATA_NODE = "DataNode"; public static final String NODE_TYPE_AI_NODE = "AINode"; public static final String COLUMN_CLUSTER_NAME = "ClusterName"; public static final String CONFIG_NODE_CONSENSUS_PROTOCOL_CLASS = "ConfigNodeConsensusProtocolClass"; public static final String DATA_REGION_CONSENSUS_PROTOCOL_CLASS = "DataRegionConsensusProtocolClass"; public static final String SCHEMA_REGION_CONSENSUS_PROTOCOL_CLASS = "SchemaRegionConsensusProtocolClass"; public static final String SERIES_SLOT_NUM = "SeriesSlotNum"; public static final String SERIES_SLOT_EXECUTOR_CLASS = "SeriesSlotExecutorClass"; public static final String SCHEMA_REGION_PER_DATA_NODE = "SchemaRegionPerDataNode"; public static final String DATA_REGION_PER_DATA_NODE = "DataRegionPerDataNode"; public static final String READ_CONSISTENCY_LEVEL = "ReadConsistencyLevel"; public static final String DISK_SPACE_WARNING_THRESHOLD = "DiskSpaceWarningThreshold"; public static final String TIMESTAMP_PRECISION = "TimestampPrecision"; // column names for show region statement public static final String REGION_ID = "RegionId"; public static final String TYPE = "Type"; public static final String DATA_NODE_ID = "DataNodeId"; public static final String TIME_SLOT_NUM = "TimeSlotNum"; public static final String SERIES_SLOT_ID = "SeriesSlotId"; public static final String TIME_PARTITION = "TimePartition"; public static final String COUNT_TIME_PARTITION = "count(timePartition)"; public static final String START_TIME = "StartTime"; public static final String ROLE = "Role"; public static final String MAX_SESSION_PER_USER = "MaxSessionPerUser"; public static final String MIN_SESSION_PER_USER = "MinSessionPerUser"; public static final String CREATE_TIME = "CreateTime"; public static final String TSFILE_SIZE = "TsFileSize"; public static final String COMPRESSION_RATIO = "CompressionRatio"; // column names for show datanodes public static final String SCHEMA_REGION_NUM = "SchemaRegionNum"; public static final String DATA_REGION_NUM = "DataRegionNum"; // column names for show device template statement public static final String TEMPLATE_NAME = "TemplateName"; // column names for show pipe sink public static final String NAME = "Name"; // column names for show pipe public static final String ID = "ID"; public static final String CREATION_TIME = "CreationTime"; public static final String PIPE_EXTRACTOR = "PipeSource"; public static final String PIPE_PROCESSOR = "PipeProcessor"; public static final String PIPE_CONNECTOR = "PipeSink"; public static final String EXCEPTION_MESSAGE = "ExceptionMessage"; public static final String REMAINING_EVENT_COUNT = "RemainingEventCount"; public static final String ESTIMATED_REMAINING_SECONDS = "EstimatedRemainingSeconds"; // column names for select into public static final String SOURCE_DEVICE = "SourceDevice"; public static final String SOURCE_COLUMN = "SourceColumn"; public static final String TARGET_TIMESERIES = "TargetTimeseries"; public static final String WRITTEN = "Written"; public static final String ROWS = "Rows"; // column names for show cq public static final String CQID = "CQId"; public static final String QUERY = "Query"; // column names for show query processlist public static final String QUERY_ID = "QueryId"; public static final String ELAPSED_TIME = "ElapsedTime"; public static final String STATEMENT = "Statement"; public static final String QUERY_ID_TABLE_MODEL = "query_id"; public static final String QUERY_ID_START_TIME_TABLE_MODEL = "start_time"; public static final String DATA_NODE_ID_TABLE_MODEL = "datanode_id"; public static final String START_TIME_TABLE_MODEL = "start_time"; public static final String ELAPSED_TIME_TABLE_MODEL = "elapsed_time"; public static final String TABLE_NAME_TABLE_MODEL = "table_name"; public static final String TABLE_TYPE_TABLE_MODEL = "table_type"; public static final String COLUMN_NAME_TABLE_MODEL = "column_name"; public static final String SCHEMA_REPLICATION_FACTOR_TABLE_MODEL = "schema_replication_factor"; public static final String DATA_REPLICATION_FACTOR_TABLE_MODEL = "data_replication_factor"; public static final String TIME_PARTITION_INTERVAL_TABLE_MODEL = "time_partition_interval"; public static final String SCHEMA_REGION_GROUP_NUM_TABLE_MODEL = "schema_region_group_num"; public static final String DATA_REGION_GROUP_NUM_TABLE_MODEL = "data_region_group_num"; public static final String REGION_ID_TABLE_MODEL = "region_id"; public static final String DATANODE_ID_TABLE_MODEL = "datanode_id"; public static final String SERIES_SLOT_NUM_TABLE_MODEL = "series_slot_num"; public static final String TIME_SLOT_NUM_TABLE_MODEL = "time_slot_num"; public static final String RPC_ADDRESS_TABLE_MODEL = "rpc_address"; public static final String RPC_PORT_TABLE_MODEL = "rpc_port"; public static final String INTERNAL_ADDRESS_TABLE_MODEL = "internal_address"; public static final String CREATE_TIME_TABLE_MODEL = "create_time"; public static final String TS_FILE_SIZE_BYTES_TABLE_MODEL = "tsfile_size_bytes"; public static final String COMPRESSION_RATIO_TABLE_MODEL = "compression_ratio"; public static final String CREATION_TIME_TABLE_MODEL = "creation_time"; public static final String PIPE_SOURCE_TABLE_MODEL = "pipe_source"; public static final String PIPE_PROCESSOR_TABLE_MODEL = "pipe_processor"; public static final String PIPE_SINK_TABLE_MODEL = "pipe_sink"; public static final String EXCEPTION_MESSAGE_TABLE_MODEL = "exception_message"; public static final String REMAINING_EVENT_COUNT_TABLE_MODEL = "remaining_event_count"; public static final String ESTIMATED_REMAINING_SECONDS_TABLE_MODEL = "estimated_remaining_seconds"; public static final String PLUGIN_NAME_TABLE_MODEL = "plugin_name"; public static final String PLUGIN_TYPE_TABLE_MODEL = "plugin_type"; public static final String CLASS_NAME_TABLE_MODEL = "class_name"; public static final String PLUGIN_JAR_TABLE_MODEL = "plugin_jar"; public static final String TOPIC_NAME_TABLE_MODEL = "topic_name"; public static final String TOPIC_CONFIGS_TABLE_MODEL = "topic_configs"; public static final String CONSUMER_GROUP_NAME_TABLE_MODEL = "consumer_group_name"; public static final String SUBSCRIBED_CONSUMERS_TABLE_MODEL = "subscribed_consumers"; public static final String VIEW_DEFINITION_TABLE_MODEL = "view_definition"; public static final String MODEL_ID_TABLE_MODEL = "model_id"; public static final String MODEL_TYPE_TABLE_MODEL = "model_type"; public static final String FUNCTION_NAME_TABLE_MODEL = "function_table"; public static final String FUNCTION_TYPE_TABLE_MODEL = "function_type"; public static final String CLASS_NAME_UDF_TABLE_MODEL = "class_name(udf)"; public static final String NODE_ID_TABLE_MODEL = "node_id"; public static final String NODE_TYPE_TABLE_MODEL = "node_type"; public static final String INTERNAL_PORT_TABLE_MODEL = "internal_port"; public static final String BUILD_INFO_TABLE_MODEL = "build_info"; public static final String CONFIG_CONSENSUS_PORT_TABLE_MODEL = "config_consensus_port"; public static final String DATA_REGION_NUM_TABLE_MODEL = "data_region_num"; public static final String SCHEMA_REGION_NUM_TABLE_MODEL = "schema_region_num"; public static final String MPP_PORT_TABLE_MODEL = "mpp_port"; public static final String SCHEMA_CONSENSUS_PORT_TABLE_MODEL = "schema_consensus_port"; public static final String DATA_CONSENSUS_PORT_TABLE_MODEL = "data_consensus_port"; // column names for show space quota public static final String QUOTA_TYPE = "QuotaType"; public static final String LIMIT = "Limit"; public static final String USED = "Used"; // column names for show throttle quota public static final String USER = "User"; public static final String USER_ID = "UserId"; public static final String READ_WRITE = "Read/Write"; // column names for show models/trials public static final String MODEL_ID = "ModelId"; // column names for views (e.g. logical view) public static final String VIEW_TYPE = "ViewType"; public static final String SOURCE = "Source"; // column names for show current timestamp public static final String CURRENT_TIMESTAMP = "CurrentTimestamp"; // column names for keywords public static final String WORD = "word"; public static final String RESERVED = "reserved"; // column names for table query public static final String COLUMN_NAME = "ColumnName"; public static final String COLUMN_DATA_TYPE = "DataType"; public static final String COLUMN_CATEGORY = "Category"; public static final String TABLE_NAME = "TableName"; public static final String PRIVILEGES = "Privileges"; public static final String COMMENT = "Comment"; public static final String TABLE_TYPE = "TableType"; public static final String VIEW = "View"; public static final String CREATE_VIEW = "Create View"; public static final String TABLE = "Table"; public static final String CREATE_TABLE = "Create Table"; public static final String GRANT_OPTION = "GrantOption"; public static final String CURRENT_USER = "CurrentUser"; public static final String CURRENT_DATABASE = "CurrentDatabase"; public static final String CURRENT_SQL_DIALECT = "CurrentSqlDialect"; public static final String SHOW_CONFIGURATIONS_NAME = "name"; public static final String SHOW_CONFIGURATIONS_VALUE = "value"; public static final String SHOW_CONFIGURATIONS_DEFAULT_VALUE = "default_value"; public static final String SHOW_CONFIGURATIONS_DESCRIPTION = "description"; public static final List<ColumnHeader> lastQueryColumnHeaders = ImmutableList.of( new ColumnHeader(TIMESERIES, TSDataType.TEXT), new ColumnHeader(VALUE, TSDataType.TEXT), new ColumnHeader(DATATYPE, TSDataType.TEXT)); public static final List<ColumnHeader> showTimeSeriesColumnHeaders = ImmutableList.of( new ColumnHeader(TIMESERIES, TSDataType.TEXT), new ColumnHeader(ALIAS, TSDataType.TEXT), new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(DATATYPE, TSDataType.TEXT), new ColumnHeader(ENCODING, TSDataType.TEXT), new ColumnHeader(COMPRESSION, TSDataType.TEXT), new ColumnHeader(TAGS, TSDataType.TEXT), new ColumnHeader(ATTRIBUTES, TSDataType.TEXT), new ColumnHeader(DEADBAND, TSDataType.TEXT), new ColumnHeader(DEADBAND_PARAMETERS, TSDataType.TEXT), new ColumnHeader(VIEW_TYPE, TSDataType.TEXT)); public static final List<ColumnHeader> showDevicesWithSgColumnHeaders = ImmutableList.of( new ColumnHeader(DEVICE, TSDataType.TEXT), new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(IS_ALIGNED, TSDataType.TEXT), new ColumnHeader(TEMPLATE, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT)); public static final List<ColumnHeader> showDevicesColumnHeaders = ImmutableList.of( new ColumnHeader(DEVICE, TSDataType.TEXT), new ColumnHeader(IS_ALIGNED, TSDataType.TEXT), new ColumnHeader(TEMPLATE, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT)); public static final List<ColumnHeader> showTTLColumnHeaders = ImmutableList.of( new ColumnHeader(DEVICE, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT)); public static final List<ColumnHeader> showDatabasesColumnHeaders = ImmutableList.of( new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(SCHEMA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(DATA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(TIME_PARTITION_ORIGIN, TSDataType.INT64), new ColumnHeader(TIME_PARTITION_INTERVAL, TSDataType.INT64)); public static final List<ColumnHeader> showDatabasesDetailColumnHeaders = ImmutableList.of( new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(SCHEMA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(DATA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(TIME_PARTITION_ORIGIN, TSDataType.INT64), new ColumnHeader(TIME_PARTITION_INTERVAL, TSDataType.INT64), new ColumnHeader(SCHEMA_REGION_GROUP_NUM, TSDataType.INT32), new ColumnHeader(MIN_SCHEMA_REGION_GROUP_NUM, TSDataType.INT32), new ColumnHeader(MAX_SCHEMA_REGION_GROUP_NUM, TSDataType.INT32), new ColumnHeader(DATA_REGION_GROUP_NUM, TSDataType.INT32), new ColumnHeader(MIN_DATA_REGION_GROUP_NUM, TSDataType.INT32), new ColumnHeader(MAX_DATA_REGION_GROUP_NUM, TSDataType.INT32)); public static final List<ColumnHeader> showChildPathsColumnHeaders = ImmutableList.of( new ColumnHeader(CHILD_PATHS, TSDataType.TEXT), new ColumnHeader(NODE_TYPES, TSDataType.TEXT)); public static final List<ColumnHeader> showNodesInSchemaTemplateHeaders = ImmutableList.of( new ColumnHeader(CHILD_NODES, TSDataType.TEXT), new ColumnHeader(DATATYPE, TSDataType.TEXT), new ColumnHeader(ENCODING, TSDataType.TEXT), new ColumnHeader(COMPRESSION, TSDataType.TEXT)); public static final List<ColumnHeader> showChildNodesColumnHeaders = ImmutableList.of(new ColumnHeader(CHILD_NODES, TSDataType.TEXT)); public static final List<ColumnHeader> showVersionColumnHeaders = ImmutableList.of( new ColumnHeader(VERSION, TSDataType.TEXT), new ColumnHeader(BUILD_INFO, TSDataType.TEXT)); public static final List<ColumnHeader> showPathsUsingTemplateHeaders = ImmutableList.of(new ColumnHeader(PATHS, TSDataType.TEXT)); public static final List<ColumnHeader> showPathSetTemplateHeaders = ImmutableList.of(new ColumnHeader(PATHS, TSDataType.TEXT)); public static final List<ColumnHeader> countDevicesColumnHeaders = ImmutableList.of(new ColumnHeader(COUNT_DEVICES, TSDataType.INT64)); public static final List<ColumnHeader> countNodesColumnHeaders = ImmutableList.of(new ColumnHeader(COUNT_NODES, TSDataType.INT64)); public static final List<ColumnHeader> countLevelTimeSeriesColumnHeaders = ImmutableList.of( new ColumnHeader(COLUMN, TSDataType.TEXT), new ColumnHeader(COUNT_TIMESERIES, TSDataType.INT64)); public static final List<ColumnHeader> countTimeSeriesColumnHeaders = ImmutableList.of(new ColumnHeader(COUNT_TIMESERIES, TSDataType.INT64)); public static final List<ColumnHeader> countStorageGroupColumnHeaders = ImmutableList.of(new ColumnHeader(COUNT_DATABASE, TSDataType.INT32)); public static final List<ColumnHeader> showRegionColumnHeaders = ImmutableList.of( new ColumnHeader(REGION_ID, TSDataType.INT32), new ColumnHeader(TYPE, TSDataType.TEXT), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(SERIES_SLOT_NUM, TSDataType.INT32), new ColumnHeader(TIME_SLOT_NUM, TSDataType.INT64), new ColumnHeader(DATA_NODE_ID, TSDataType.INT32), new ColumnHeader(RPC_ADDRESS, TSDataType.TEXT), new ColumnHeader(RPC_PORT, TSDataType.INT32), new ColumnHeader(INTERNAL_ADDRESS, TSDataType.TEXT), new ColumnHeader(ROLE, TSDataType.TEXT), new ColumnHeader(CREATE_TIME, TSDataType.TEXT), new ColumnHeader(TSFILE_SIZE, TSDataType.TEXT), new ColumnHeader(COMPRESSION_RATIO, TSDataType.DOUBLE)); public static final List<ColumnHeader> showAINodesColumnHeaders = ImmutableList.of( new ColumnHeader(NODE_ID, TSDataType.INT32), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(INTERNAL_ADDRESS, TSDataType.TEXT), new ColumnHeader(INTERNAL_PORT, TSDataType.INT32)); public static final List<ColumnHeader> showDataNodesColumnHeaders = ImmutableList.of( new ColumnHeader(NODE_ID, TSDataType.INT32), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(RPC_ADDRESS, TSDataType.TEXT), new ColumnHeader(RPC_PORT, TSDataType.INT32), new ColumnHeader(DATA_REGION_NUM, TSDataType.INT32), new ColumnHeader(SCHEMA_REGION_NUM, TSDataType.INT32)); public static final List<ColumnHeader> showConfigNodesColumnHeaders = ImmutableList.of( new ColumnHeader(NODE_ID, TSDataType.INT32), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(INTERNAL_ADDRESS, TSDataType.TEXT), new ColumnHeader(INTERNAL_PORT, TSDataType.INT32), new ColumnHeader(ROLE, TSDataType.TEXT)); public static final List<ColumnHeader> showClusterColumnHeaders = ImmutableList.of( new ColumnHeader(NODE_ID, TSDataType.INT32), new ColumnHeader(NODE_TYPE, TSDataType.TEXT), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(INTERNAL_ADDRESS, TSDataType.TEXT), new ColumnHeader(INTERNAL_PORT, TSDataType.INT32), new ColumnHeader(VERSION, TSDataType.TEXT), new ColumnHeader(BUILD_INFO, TSDataType.TEXT)); public static final List<ColumnHeader> showClusterDetailsColumnHeaders = ImmutableList.of( new ColumnHeader(NODE_ID, TSDataType.INT32), new ColumnHeader(NODE_TYPE, TSDataType.TEXT), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(INTERNAL_ADDRESS, TSDataType.TEXT), new ColumnHeader(INTERNAL_PORT, TSDataType.INT32), new ColumnHeader(CONFIG_CONSENSUS_PORT, TSDataType.TEXT), new ColumnHeader(RPC_ADDRESS, TSDataType.TEXT), new ColumnHeader(RPC_PORT, TSDataType.TEXT), new ColumnHeader(MPP_PORT, TSDataType.TEXT), new ColumnHeader(SCHEMA_CONSENSUS_PORT, TSDataType.TEXT), new ColumnHeader(DATA_CONSENSUS_PORT, TSDataType.TEXT), new ColumnHeader(VERSION, TSDataType.TEXT), new ColumnHeader(BUILD_INFO, TSDataType.TEXT)); public static final List<ColumnHeader> showClusterIdColumnHeaders = ImmutableList.of(new ColumnHeader(CLUSTER_ID, TSDataType.TEXT)); public static final List<ColumnHeader> testConnectionColumnHeaders = ImmutableList.of( new ColumnHeader(SERVICE_PROVIDER, TSDataType.TEXT), new ColumnHeader(SENDER, TSDataType.TEXT), new ColumnHeader(CONNECTION, TSDataType.TEXT)); public static final List<ColumnHeader> showVariablesColumnHeaders = ImmutableList.of( new ColumnHeader(VARIABLE, TSDataType.TEXT), new ColumnHeader(VALUE, TSDataType.TEXT)); public static final List<ColumnHeader> showFunctionsColumnHeaders = ImmutableList.of( new ColumnHeader(FUNCTION_NAME, TSDataType.TEXT), new ColumnHeader(FUNCTION_TYPE, TSDataType.TEXT), new ColumnHeader(CLASS_NAME_UDF, TSDataType.TEXT), new ColumnHeader(FUNCTION_STATE, TSDataType.TEXT)); public static final List<ColumnHeader> showTriggersColumnHeaders = ImmutableList.of( new ColumnHeader(TRIGGER_NAME, TSDataType.TEXT), new ColumnHeader(EVENT, TSDataType.TEXT), new ColumnHeader(TYPE, TSDataType.TEXT), new ColumnHeader(STATE, TSDataType.TEXT), new ColumnHeader(PATH_PATTERN, TSDataType.TEXT), new ColumnHeader(CLASS_NAME, TSDataType.TEXT), new ColumnHeader(NODE_ID, TSDataType.TEXT)); public static final List<ColumnHeader> showPipePluginsColumnHeaders = ImmutableList.of( new ColumnHeader(PLUGIN_NAME, TSDataType.TEXT), new ColumnHeader(PLUGIN_TYPE, TSDataType.TEXT), new ColumnHeader(CLASS_NAME, TSDataType.TEXT), new ColumnHeader(PLUGIN_JAR, TSDataType.TEXT)); public static final List<ColumnHeader> showSchemaTemplateHeaders = ImmutableList.of(new ColumnHeader(TEMPLATE_NAME, TSDataType.TEXT)); public static final List<ColumnHeader> showPipeSinkTypeColumnHeaders = ImmutableList.of(new ColumnHeader(TYPE, TSDataType.TEXT)); public static final List<ColumnHeader> showPipeSinkColumnHeaders = ImmutableList.of( new ColumnHeader(NAME, TSDataType.TEXT), new ColumnHeader(TYPE, TSDataType.TEXT), new ColumnHeader(ATTRIBUTES, TSDataType.TEXT)); public static final List<ColumnHeader> showPipeColumnHeaders = ImmutableList.of( new ColumnHeader(ID, TSDataType.TEXT), new ColumnHeader(CREATION_TIME, TSDataType.TEXT), new ColumnHeader(STATE, TSDataType.TEXT), new ColumnHeader(PIPE_EXTRACTOR, TSDataType.TEXT), new ColumnHeader(PIPE_PROCESSOR, TSDataType.TEXT), new ColumnHeader(PIPE_CONNECTOR, TSDataType.TEXT), new ColumnHeader(EXCEPTION_MESSAGE, TSDataType.TEXT), new ColumnHeader(REMAINING_EVENT_COUNT, TSDataType.TEXT), new ColumnHeader(ESTIMATED_REMAINING_SECONDS, TSDataType.TEXT)); public static final List<ColumnHeader> showTopicColumnHeaders = ImmutableList.of( new ColumnHeader(TOPIC_NAME, TSDataType.TEXT), new ColumnHeader(TOPIC_CONFIGS, TSDataType.TEXT)); public static final List<ColumnHeader> showSubscriptionColumnHeaders = ImmutableList.of( new ColumnHeader(SUBSCRIPTION_ID, TSDataType.TEXT), new ColumnHeader(TOPIC_NAME, TSDataType.TEXT), new ColumnHeader(CONSUMER_GROUP_NAME, TSDataType.TEXT), new ColumnHeader(SUBSCRIBED_CONSUMERS, TSDataType.TEXT)); public static final List<ColumnHeader> selectIntoColumnHeaders = ImmutableList.of( new ColumnHeader(SOURCE_COLUMN, TSDataType.TEXT), new ColumnHeader(TARGET_TIMESERIES, TSDataType.TEXT), new ColumnHeader(WRITTEN, TSDataType.INT64)); public static final List<ColumnHeader> selectIntoAlignByDeviceColumnHeaders = ImmutableList.of( new ColumnHeader(SOURCE_DEVICE, TSDataType.TEXT), new ColumnHeader(SOURCE_COLUMN, TSDataType.TEXT), new ColumnHeader(TARGET_TIMESERIES, TSDataType.TEXT), new ColumnHeader(WRITTEN, TSDataType.INT64)); public static final List<ColumnHeader> selectIntoTableColumnHeaders = ImmutableList.of(new ColumnHeader(ROWS, TSDataType.INT64)); public static final List<ColumnHeader> getRegionIdColumnHeaders = ImmutableList.of(new ColumnHeader(REGION_ID, TSDataType.INT32)); public static final List<ColumnHeader> getTimeSlotListColumnHeaders = ImmutableList.of( new ColumnHeader(TIME_PARTITION, TSDataType.INT64), new ColumnHeader(START_TIME, TSDataType.TEXT)); public static final List<ColumnHeader> countTimeSlotListColumnHeaders = ImmutableList.of(new ColumnHeader(COUNT_TIME_PARTITION, TSDataType.INT64)); public static final List<ColumnHeader> getSeriesSlotListColumnHeaders = ImmutableList.of(new ColumnHeader(SERIES_SLOT_ID, TSDataType.INT32)); public static final List<ColumnHeader> showContinuousQueriesColumnHeaders = ImmutableList.of( new ColumnHeader(CQID, TSDataType.TEXT), new ColumnHeader(QUERY, TSDataType.TEXT), new ColumnHeader(STATE, TSDataType.TEXT)); public static final List<ColumnHeader> showQueriesColumnHeaders = ImmutableList.of( new ColumnHeader(QUERY_ID, TSDataType.TEXT), new ColumnHeader(DATA_NODE_ID, TSDataType.INT32), new ColumnHeader(ELAPSED_TIME, TSDataType.FLOAT), new ColumnHeader(STATEMENT, TSDataType.TEXT)); public static final List<ColumnHeader> showSpaceQuotaColumnHeaders = ImmutableList.of( new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(QUOTA_TYPE, TSDataType.TEXT), new ColumnHeader(LIMIT, TSDataType.TEXT), new ColumnHeader(USED, TSDataType.TEXT)); public static final List<ColumnHeader> showThrottleQuotaColumnHeaders = ImmutableList.of( new ColumnHeader(USER, TSDataType.TEXT), new ColumnHeader(QUOTA_TYPE, TSDataType.TEXT), new ColumnHeader(LIMIT, TSDataType.TEXT), new ColumnHeader(READ_WRITE, TSDataType.TEXT)); public static final List<ColumnHeader> showModelsColumnHeaders = ImmutableList.of( new ColumnHeader(MODEL_ID, TSDataType.TEXT), new ColumnHeader(MODEL_TYPE, TSDataType.TEXT), new ColumnHeader(COLUMN_CATEGORY, TSDataType.TEXT), new ColumnHeader(STATE, TSDataType.TEXT)); public static final List<ColumnHeader> showLoadedModelsColumnHeaders = ImmutableList.of( new ColumnHeader(DEVICE_ID, TSDataType.TEXT), new ColumnHeader(MODEL_TYPE, TSDataType.TEXT), new ColumnHeader(COUNT_INSTANCES, TSDataType.INT32)); public static final List<ColumnHeader> showAIDevicesColumnHeaders = ImmutableList.of(new ColumnHeader(DEVICE_ID, TSDataType.TEXT)); public static final List<ColumnHeader> showLogicalViewColumnHeaders = ImmutableList.of( new ColumnHeader(TIMESERIES, TSDataType.TEXT), new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(DATATYPE, TSDataType.TEXT), new ColumnHeader(TAGS, TSDataType.TEXT), new ColumnHeader(ATTRIBUTES, TSDataType.TEXT), new ColumnHeader(VIEW_TYPE, TSDataType.TEXT), new ColumnHeader(SOURCE, TSDataType.TEXT)); public static final List<ColumnHeader> showDBColumnHeaders = ImmutableList.of( new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT), new ColumnHeader(SCHEMA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(DATA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(TIME_PARTITION_INTERVAL, TSDataType.INT64)); public static final List<ColumnHeader> showDBDetailsColumnHeaders = ImmutableList.of( new ColumnHeader(DATABASE, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT), new ColumnHeader(SCHEMA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(DATA_REPLICATION_FACTOR, TSDataType.INT32), new ColumnHeader(TIME_PARTITION_INTERVAL, TSDataType.INT64), new ColumnHeader(SCHEMA_REGION_GROUP_NUM, TSDataType.INT32), new ColumnHeader(DATA_REGION_GROUP_NUM, TSDataType.INT32)); public static final List<ColumnHeader> describeTableColumnHeaders = ImmutableList.of( new ColumnHeader(COLUMN_NAME, TSDataType.TEXT), new ColumnHeader(COLUMN_DATA_TYPE, TSDataType.TEXT), new ColumnHeader(COLUMN_CATEGORY, TSDataType.TEXT)); public static final List<ColumnHeader> describeTableDetailsColumnHeaders = ImmutableList.of( new ColumnHeader(COLUMN_NAME, TSDataType.TEXT), new ColumnHeader(COLUMN_DATA_TYPE, TSDataType.TEXT), new ColumnHeader(COLUMN_CATEGORY, TSDataType.TEXT), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(COMMENT, TSDataType.TEXT)); public static final List<ColumnHeader> showCreateViewColumnHeaders = ImmutableList.of( new ColumnHeader(VIEW, TSDataType.TEXT), new ColumnHeader(CREATE_VIEW, TSDataType.TEXT)); public static final List<ColumnHeader> showCreateTableColumnHeaders = ImmutableList.of( new ColumnHeader(TABLE, TSDataType.TEXT), new ColumnHeader(CREATE_TABLE, TSDataType.TEXT)); public static final List<ColumnHeader> LIST_USER_COLUMN_HEADERS = ImmutableList.of( new ColumnHeader(USER_ID, TSDataType.INT64), new ColumnHeader(USER, TSDataType.TEXT)); public static final List<ColumnHeader> showTablesColumnHeaders = ImmutableList.of( new ColumnHeader(TABLE_NAME, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT)); public static final List<ColumnHeader> showTablesDetailsColumnHeaders = ImmutableList.of( new ColumnHeader(TABLE_NAME, TSDataType.TEXT), new ColumnHeader(COLUMN_TTL, TSDataType.TEXT), new ColumnHeader(STATUS, TSDataType.TEXT), new ColumnHeader(COMMENT, TSDataType.TEXT), new ColumnHeader(TABLE_TYPE, TSDataType.TEXT)); public static final List<ColumnHeader> LIST_USER_OR_ROLE_PRIVILEGES_COLUMN_HEADERS = ImmutableList.of( new ColumnHeader(ROLE, TSDataType.TEXT), new ColumnHeader(SCOPE, TSDataType.TEXT), new ColumnHeader(PRIVILEGES, TSDataType.TEXT), new ColumnHeader(GRANT_OPTION, TSDataType.BOOLEAN)); public static final List<ColumnHeader> SHOW_CURRENT_USER_COLUMN_HEADERS = ImmutableList.of(new ColumnHeader(CURRENT_USER, TSDataType.STRING)); public static final List<ColumnHeader> SHOW_CURRENT_DATABASE_COLUMN_HEADERS = ImmutableList.of(new ColumnHeader(CURRENT_DATABASE, TSDataType.STRING)); public static final List<ColumnHeader> SHOW_CURRENT_SQL_DIALECT_COLUMN_HEADERS = ImmutableList.of(new ColumnHeader(CURRENT_SQL_DIALECT, TSDataType.STRING)); public static final List<ColumnHeader> SHOW_CURRENT_TIMESTAMP_COLUMN_HEADERS = ImmutableList.of(new ColumnHeader(CURRENT_TIMESTAMP, TSDataType.TIMESTAMP)); public static final List<ColumnHeader> SHOW_CONFIGURATIONS_COLUMN_HEADERS = ImmutableList.of( new ColumnHeader(SHOW_CONFIGURATIONS_NAME, TSDataType.TEXT), new ColumnHeader(SHOW_CONFIGURATIONS_VALUE, TSDataType.TEXT), new ColumnHeader(SHOW_CONFIGURATIONS_DEFAULT_VALUE, TSDataType.TEXT)); public static final List<ColumnHeader> SHOW_CONFIGURATIONS_COLUMN_HEADERS_WITH_DESCRIPTION = ImmutableList.of( new ColumnHeader(SHOW_CONFIGURATIONS_NAME, TSDataType.TEXT), new ColumnHeader(SHOW_CONFIGURATIONS_VALUE, TSDataType.TEXT), new ColumnHeader(SHOW_CONFIGURATIONS_DEFAULT_VALUE, TSDataType.TEXT), new ColumnHeader(SHOW_CONFIGURATIONS_DESCRIPTION, TSDataType.TEXT)); }
oracle/graalpython
36,816
graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/formatting/InternalFormat.java
/* * Copyright (c) 2017, 2025, 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.exception.PythonErrorType.OverflowError; import static com.oracle.graal.python.runtime.exception.PythonErrorType.ValueError; import static com.oracle.graal.python.runtime.formatting.InternalFormat.Spec.NONE; import static com.oracle.graal.python.runtime.formatting.InternalFormat.Spec.specified; import static com.oracle.graal.python.util.PythonUtils.toTruffleStringUncached; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; import com.oracle.graal.python.nodes.ErrorMessages; import com.oracle.graal.python.nodes.PRaiseNode; import com.oracle.graal.python.runtime.PythonContext; import com.oracle.graal.python.runtime.exception.PException; import com.oracle.graal.python.runtime.locale.PythonLocale; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.strings.TruffleString; //Copyright (c) Jython Developers public class InternalFormat { /** * Create a {@link Spec} object by parsing a format specification. * * @param text to parse * @return parsed equivalent to text */ @TruffleBoundary public static Spec fromText(TruffleString text, char defaultType, char defaultAlignment, Node raisingNode) { Parser parser = new Parser(text.toJavaStringUncached()); return parser.parse(defaultType, defaultAlignment, raisingNode); } /** * A class that provides the base for implementations of type-specific 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 static class Formatter implements Appendable { protected final Node raisingNode; /** The specification according to which we format any number supplied to the method. */ protected final Spec spec; /** The (partial) result. */ protected final FormattingBuffer result; /** * Signals the client's intention to make a PyBytes (or other byte-like) interpretation of * {@link #result}, rather than a PyUnicode one. */ protected boolean bytes; /** The start of the formatted data for padding purposes, &lt;={@link #start} */ protected final int mark; /** The latest number we are working on floats at the end of the result, and starts here. */ protected int start; /** If it contains no sign, this length is zero, and &gt;0 otherwise. */ protected int lenSign; /** The length of the whole part (to left of the decimal point or exponent) */ protected int lenWhole; /** The actual "thousands" grouping used in the end (spec.grouping may be overridden) */ protected char actualGrouping; /** The actual "thousands" group size used in the end */ protected int actualGroupSize; /** * Construct the formatter from a client-supplied buffer and a specification. Sets * {@link #mark} and {@link #start} to the end of the buffer. The new formatted object will * therefore be appended there and, when the time comes, padding will be applied to (just) * the new text. * * @param result destination buffer * @param spec parsed conversion specification */ protected Formatter(FormattingBuffer result, Spec spec, Node raisingNode) { this.raisingNode = raisingNode; this.spec = spec; this.result = result; this.start = this.mark = result.length(); } /** * Signals the client's intention to make a PyBytes (or other byte-like) interpretation of * {@link #result}, rather than a PyUnicode one. Only formatters that could produce * characters &gt;255 are affected by this (e.g. c-format). Idiom: * * <pre> * MyFormatter f = new MyFormatter(InternalFormatter.fromText(formatSpec)); * f.setBytes(!(formatSpec instanceof PyUnicode)); * // ... formatting work * return f.getPyResult(); * </pre> * * @param bytes true to signal the intention to make a byte-like interpretation */ public void setBytes(boolean bytes) { this.bytes = bytes; } /** * Current (possibly final) result of the formatting, as a <code>String</code>. * * @return formatted result */ public TruffleString getResult() { return toTruffleStringUncached(result.toString()); } /* * Implement Appendable interface by delegation to the result buffer. * * @see java.lang.Appendable#append(char) */ @Override public Formatter append(char c) { result.append(c); return this; } @Override public Formatter append(CharSequence csq) { result.append(csq); return this; } @Override public Formatter append(CharSequence csq, int begin, int end) // throws IndexOutOfBoundsException { result.append(csq, begin, end); return this; } /** * Clear the instance variables describing the latest object in {@link #result}, ready to * receive a new one: sets {@link #start} and calls {@link #reset()}. This is necessary when * a <code>Formatter</code> is to be re-used. Note that this leaves {@link #mark} where it * is. In the core, we need this to support <code>complex</code>: two floats in the same * format, but padded as a unit. */ public void setStart() { // The new value will float at the current end of the result buffer. start = result.length(); actualGrouping = spec.grouping; actualGroupSize = spec.getGroupingSize(); // If anything has been added since construction, reset all state. if (start > mark) { // Clear the variable describing the latest number in result. reset(); } } /** * Clear the instance variables describing the latest object in {@link #result}, ready to * receive a new one. This is called from {@link #setStart()}. Subclasses override this * method and call {@link #setStart()} at the start of their format method. */ protected void reset() { // Clear the variables describing the latest object in result. lenSign = lenWhole = 0; } /** * Supports {@link #toString()} by returning the lengths of the successive sections in the * result buffer, used for navigation relative to {@link #start}. The <code>toString</code> * method shows a '|' character between each section when it prints out the buffer. Override * this when you define more lengths in the subclass. * * @return the lengths of the successive sections */ protected int[] sectionLengths() { return new int[]{lenSign, lenWhole}; } /** * {@inheritDoc} * <p> * Overridden to provide a debugging view in which the actual text is shown divided up by * the <code>len*</code> member variables. If the dividers don't look right, those variables * have not remained consistent with the text. */ @Override public String toString() { if (result == null) { return ("[]"); } else { FormattingBuffer.StringFormattingBuffer buf = new FormattingBuffer.StringFormattingBuffer(result.length() + 20); buf.append(result); try { int p = start; buf.insert(p++, '['); for (int len : sectionLengths()) { p += len; buf.insert(p++, '|'); } buf.setCharAt(p - 1, ']'); } catch (IndexOutOfBoundsException e) { // Some length took us beyond the end of the result buffer. Pass. } return buf.toString(); } } protected static DecimalFormat getCurrentDecimalFormat() { Locale currLocale = PythonContext.get(null).getCurrentLocale().category(PythonLocale.LC_NUMERIC); NumberFormat numberFormat = NumberFormat.getInstance(currLocale); return numberFormat instanceof DecimalFormat ? (DecimalFormat) numberFormat : null; } protected void setGroupingAndGroupSize(DecimalFormat format) { if (format != null) { boolean useGrouping = format.isGroupingUsed(); if (useGrouping) { DecimalFormatSymbols symbols = format.getDecimalFormatSymbols(); actualGrouping = symbols.getGroupingSeparator(); actualGroupSize = format.getGroupingSize(); useGrouping = actualGroupSize > 0; } if (!useGrouping) { actualGrouping = NONE; actualGroupSize = -1; } } } protected void groupWholePartIfRequired() { if (specified(actualGrouping)) { groupDigits(actualGroupSize, actualGrouping); } } /** * Insert grouping characters (conventionally commas) into the whole part of the number. * {@link #lenWhole} will increase correspondingly. * * @param groupSize normally 3. * @param comma or some other character to use as a separator. */ protected void groupDigits(int groupSize, char comma) { // Work out how many commas (or whatever) it takes to group the whole-number part. int commasNeeded = (lenWhole - 1) / groupSize; if (commasNeeded > 0) { // Index *just after* the current last digit of the whole part of the number. int from = start + lenSign + lenWhole; // Open a space into which the whole part will expand. makeSpaceAt(from, commasNeeded); // Index *just after* the end of that space. int to = from + commasNeeded; // The whole part will be longer by the number of commas to be inserted. lenWhole += commasNeeded; /* * Now working from high to low, copy all the digits that have to move. Each pass * copies one group and inserts a comma, which makes the to-pointer move one place * extra. The to-pointer descends upon the from-pointer from the right. */ while (to > from) { // Copy a group for (int i = 0; i < groupSize; i++) { result.setCharAt(--to, result.charAt(--from)); } // Write the comma that precedes it. result.setCharAt(--to, comma); } } } /** * Make a space in {@link #result} of a certain size and position. On return, the segment * lengths are likely to be invalid until the caller adjusts them corresponding to the * insertion. There is no guarantee what the opened space contains. * * @param pos at which to make the space * @param size of the space */ protected void makeSpaceAt(int pos, int size) { int n = result.length(); if (pos < n) { // Space is not at the end: must copy what's to the right of pos. String tail = result.substring(pos); result.setLength(n + size); result.replace(pos + size, n + size, tail); } else { // Space is at the end. result.setLength(n + size); } } /** * Convert letters in the representation of the current number (in {@link #result}) to upper * case. */ protected void uppercase() { int end = result.length(); for (int i = start; i < end; i++) { char c = result.charAt(i); result.setCharAt(i, Character.toUpperCase(c)); } } /** * Pad the result so far (defined as the contents of {@link #result} from {@link #mark} to * the end) using the alignment, target width and fill character defined in {@link #spec}. * The action of padding will increase the length of this segment to the target width, if * that is greater than the current length. * <p> * When the padding method has decided that that it needs to add n padding characters, it * will affect {@link #start} or {@link #lenWhole} as follows. <table border style> * <tr> * <th>align</th> * <th>meaning</th> * <th>start</th> * <th>lenWhole</th> * <th>result.length()</th> * </tr> * <tr> * <th>&lt;</th> * <td>left-aligned</td> * <td>+0</td> * <td>+0</td> * <td>+n</td> * </tr> * <tr> * <th>></th> * <td>right-aligned</td> * <td>+n</td> * <td>+0</td> * <td>+n</td> * </tr> * <tr> * <th>^</th> * <td>centred</td> * <td>+(n/2)</td> * <td>+0</td> * <td>+n</td> * </tr> * <tr> * <th>=</th> * <td>pad after sign</td> * <td>+0</td> * <td>+n</td> * <td>+n</td> * </tr> * </table> * Note that in the "pad after sign" mode, only the last number into the buffer receives the * padding. This padding gets incorporated into the whole part of the number. (In other * modes, the padding is around <code>result[mark:]</code>.) When this would not be * appropriate, it is up to the client to disallow this (which <code>complex</code> does). * * @return this Formatter object */ public Formatter pad() { // We'll need this many pad characters (if>0). Note Spec.UNDEFINED<0. int n = spec.width - (result.length() - mark); if (n > 0) { pad(mark, n); } return this; } /** * Pad the last result (defined as the contents of {@link #result} from argument * <code>leftIndex</code> to the end) using the alignment, by <code>n</code> repetitions of * the fill character defined in {@link #spec}, and distributed according to * <code>spec.align</code>. The value of <code>leftIndex</code> is only used if the * alignment is '&gt;' (left) or '^' (both). The value of the critical lengths (lenWhole, * lenSign, etc.) are not affected, because we assume that <code>leftIndex &lt;= </code> * {@link #start}. * * @param leftIndexArg the index in result at which to insert left-fill characters. * @param n number of fill characters to insert. */ protected void pad(int leftIndexArg, int n) { int leftIndex = leftIndexArg; char align = spec.getAlign('>'); // Right for numbers (strings will supply '<' align) char fill = spec.getFill(' '); // Start by assuming padding is all leading ('>' case or '=') int leading = n; // Split the total padding according to the alignment if (align == '^') { // Half the padding before leading = n / 2; } else if (align == '<') { // All the padding after leading = 0; } // All padding that is not leading is trailing int trailing = n - leading; // Insert the leading space if (leading > 0) { if (align == '=') { // Incorporate into the (latest) whole part leftIndex = start + lenSign; lenWhole += leading; } else { // Default is to insert at the stated leftIndex <= start. start += leading; } makeSpaceAt(leftIndex, leading); for (int i = 0; i < leading; i++) { result.setCharAt(leftIndex + i, fill); } } // Append the trailing space for (int i = 0; i < trailing; i++) { result.append(fill); } // Check for special case if (align == '=' && fill == '0' && specified(actualGrouping)) { // We must extend the grouping separator into the padding zeroPadAfterSignWithGroupingFixup(actualGroupSize, actualGrouping); } } /** * Fix-up the zero-padding of the last formatted number in #result in the special case where * a sign-aware padding (<code>{@link #spec}.align='='</code>) was requested, the fill * character is <code>'0'</code>, and the digits are to be grouped. In these exact * circumstances, the grouping, which must already have been applied to the (whole part) * number itself, has to be extended into the zero-padding. * * <pre> * &gt;&gt;&gt; format(-12e8, " =30,.3f") * '- 1,200,000,000.000' * &gt;&gt;&gt; format(-12e8, "*=30,.3f") * '-************1,200,000,000.000' * &gt;&gt;&gt; format(-12e8, "*&gt;30,.3f") * '************-1,200,000,000.000' * &gt;&gt;&gt; format(-12e8, "0&gt;30,.3f") * '000000000000-1,200,000,000.000' * &gt;&gt;&gt; format(-12e8, "0=30,.3f") * '-0,000,000,001,200,000,000.000' * </pre> * * The padding has increased the overall length of the result to the target width. About one * in three calls to this method adds one to the width, because the whole part cannot start * with a comma. * * <pre> * &gt;&gt;&gt; format(-12e8, " =30,.4f") * '- 1,200,000,000.0000' * &gt;&gt;&gt; format(-12e8, "0=30,.4f") * '-<b>0</b>,000,000,001,200,000,000.0000' * </pre> * * @param groupSize normally 3. * @param comma or some other character to use as a separator. */ protected void zeroPadAfterSignWithGroupingFixup(int groupSize, char comma) { /* * Suppose the format call was format(-12e8, "0=30,.3f"). At this point, we have * something like this in result: .. [-|0000000000001,200,000,000|.|000||] * * All we need do is over-write some of the zeros with the separator comma, in the * portion marked as the whole-part: [-|0,000,000,001,200,000,000|.|000||] */ // First digit of the whole-part. int firstZero = start + lenSign; // One beyond last digit of the whole-part. int p = firstZero + lenWhole; // Step back down the result array visiting the commas. (Easiest to do all of them.) int step = groupSize + 1; for (p = p - step; p >= firstZero; p -= step) { result.setCharAt(p, comma); } // Sometimes the last write was exactly at the first padding zero. if (p + step == firstZero) { /* * Suppose the format call was format(-12e8, "0=30,.4f"). At the beginning, we had * something like this in result: . [-|000000000001,200,000,000|.|0000||] * * And now, result looks like this: [-|,000,000,001,200,000,000|.|0000||] in which * the first comma is wrong, but so would be a zero. We have to insert another zero, * even though this makes the result longer than we were asked for. */ result.insert(firstZero, '0'); lenWhole += 1; } } /** * Convenience method returning a Py#ValueError reporting: * <p> * <code>"Unknown format code '"+code+"' for object of type '"+forType+"'"</code> * * @param code the presentation type * @param forType the type it was found applied to * @return exception to throw */ public static PException unknownFormat(char code, String forType, Node raisingNode) { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.UNKNOWN_FORMAT_CODE, code, forType); } /** * Convenience method returning a OverflowError reporting: * <p> * <code>"formatted "+type+" is too long (precision too large?)"</code> * * @param type of formatting ("integer", "float") * @return exception to throw */ public PException precisionTooLarge(String type) { throw PRaiseNode.raiseStatic(raisingNode, OverflowError, ErrorMessages.FORMATED_S_TOO_LONG, type); } } /** * Parsed PEP-3101 format specification of a single field, encapsulating the format for use by * formatting methods. This class holds the several attributes that might be decoded from a * format specifier. Each attribute has a reserved value used to indicate "unspecified". * <code>Spec</code> objects may be merged such that one <code>Spec</code> provides values, * during the construction of a new <code>Spec</code>, for attributes that are unspecified in a * primary source. * <p> * This structure is returned by factory method #fromText(String)}, and having public final * members is freely accessed by formatters such as {@link FloatFormatter}, and the __format__ * methods of client object types. * <p> * The fields correspond to the elements of a format specification. The grammar of a format * specification is: * * <pre> * [[fill]align][sign][#][0][width][,][.precision][type] * </pre> * * A typical idiom is: * * <pre> * InternalFormat.Spec spec = InternalFormat.fromText(specString, Spec.NONE, '>'); * ... // Validation of spec.type, and other attributes, for this type. * FloatFormatter f = new FloatFormatter(spec); * String result = f.format(value).getResult(); * * </pre> */ public static class Spec { /** The fill character specified, or U+FFFF if unspecified. */ public final char fill; /** * Alignment indicator is one of {<code>'&lt;', '^', '>', '='</code>, or U+FFFF if * unspecified. */ public final char align; /** * Sign-handling flag, one of <code>'+'</code>, <code>'-'</code>, or <code>' '</code>, or * U+FFFF if unspecified. */ public final char sign; /** The alternative format flag '#' was given. */ public final boolean alternate; /** Width to which to pad the result, or -1 if unspecified. */ public final int width; /** Insert the grouping separator. It may be dot or underscore for oct/hex/bin. */ public final char grouping; /** Precision decoded from the format, or -1 if unspecified. */ public final int precision; /** Type key from the format, or U+FFFF if unspecified. */ public final char type; /** * Non-character code point used to represent "no value" in <code>char</code> attributes. */ public static final char NONE = '\uffff'; /** Negative value used to represent "no value" in <code>int</code> attributes. */ public static final int UNSPECIFIED = -1; /** * Test to see if an attribute has been specified. * * @param c attribute * @return true only if the attribute is not equal to {@link #NONE} */ public static boolean specified(char c) { return c != NONE; } /** * Test to see if an attribute has been specified. * * @param value of attribute * @return true only if the attribute is >=0 (meaning that it has been specified). */ public static boolean specified(int value) { return value >= 0; } /** * Constructor to set all the fields in the format specifier. * * <pre> * [[fill]align][sign][#][0][width][,][.precision][type] * </pre> * * @param fill fill character (or {@link #NONE} * @param align alignment indicator, one of {<code>'&lt;', '^', '>', '='</code> * @param sign policy, one of <code>'+'</code>, <code>'-'</code>, or <code>' '</code>. * @param alternate true to request alternate formatting mode (<code>'#'</code> flag). * @param width of field after padding or -1 to default * @param grouping true to request comma-separated groups * @param precision (e.g. decimal places) or -1 to default * @param type indicator character */ public Spec(char fill, char align, char sign, boolean alternate, int width, char grouping, int precision, char type) { this.fill = fill; this.align = align; this.sign = sign; this.alternate = alternate; this.width = width; this.grouping = grouping; this.precision = precision; this.type = type; } /** * Return a format specifier (text) equivalent to the value of this Spec. */ @Override public String toString() { FormattingBuffer.StringFormattingBuffer buf = new FormattingBuffer.StringFormattingBuffer(); if (specified(fill)) { buf.append(fill); } if (specified(align)) { buf.append(align); } if (specified(sign)) { buf.append(sign); } if (alternate) { buf.append('#'); } if (specified(width)) { buf.append(width); } if (specified(grouping)) { buf.append(grouping); } if (specified(precision)) { buf.append('.').append(precision); } if (specified(type)) { buf.append(type); } return buf.toString(); } /** * Constructor offering just precision and type. * * <pre> * [.precision][type] * </pre> * * @param precision (e.g. decimal places) * @param type indicator character */ public Spec(int precision, char type) { this(' ', '>', NONE, false, UNSPECIFIED, NONE, precision, type); } /** The alignment from the parsed format specification, or default. */ public char getFill(char defaultFill) { return specified(fill) ? fill : defaultFill; } /** The alignment from the parsed format specification, or default. */ public char getAlign(char defaultAlign) { return specified(align) ? align : defaultAlign; } /** The precision from the parsed format specification, or default. */ public int getPrecision(int defaultPrecision) { return specified(precision) ? precision : defaultPrecision; } /** The type code from the parsed format specification, or default supplied. */ public char getType(char defaultType) { return specified(type) ? type : defaultType; } public int getGroupingSize() { if (!specified(grouping)) { return -1; } switch (type) { case 'b': case 'o': case 'x': case 'X': assert grouping == '_'; return 4; } return 3; } } /** * Parser for PEP-3101 field format specifications. This class provides a * {@link #parse(char, char, Node)} method that translates the format specification into an * <code>Spec</code> object. */ private static class Parser { private final String spec; private int ptr; /** * Constructor simply holds the specification string ahead of the * {@link #parse(char, char, Node)} operation. * * @param spec format specifier to parse (e.g. "&lt;+12.3f") */ Parser(String spec) { this.spec = spec; this.ptr = 0; } /** * Parse the specification with which this object was initialised into an {@link Spec}, * which is an object encapsulating the format for use by formatting methods. This parser * deals only with the format specifiers themselves, as accepted by the * <code>__format__</code> method of a type, or the <code>format()</code> built-in, not * format strings in general as accepted by <code>str.format()</code>. * * @return the <code>Spec</code> equivalent to the string given. */ /* * This method is the equivalent of CPython's parse_internal_render_format_spec() in * ~/Objects/stringlib/formatter.h. */ Spec parse(char defaultType, char defaultAlignment, Node raisingNode) { char type = defaultType; char align = NONE; char fill = NONE; char sign = NONE; boolean alternate; char grouping = NONE; int width = Spec.UNSPECIFIED, precision = Spec.UNSPECIFIED; // Scan [[fill]align] ... if (isAlign()) { // First is alignment. fill not specified. align = spec.charAt(ptr++); } else { // Peek ahead ptr += 1; if (isAlign()) { // Second character is alignment, so first is fill fill = spec.charAt(0); align = spec.charAt(ptr++); } else { // Second character is not alignment. We are still at square zero. ptr = 0; } } // Scan [sign] ... if (isAt("+- ")) { sign = spec.charAt(ptr++); } // Scan [#] ... alternate = scanPast('#'); // Scan [0] ... if (scanPast('0')) { // Accept 0 here as equivalent to zero-fill but only not set already. if (!Spec.specified(fill)) { fill = '0'; if (!Spec.specified(align) && defaultAlignment == '>') { // Also accept it as equivalent to "=" alignment but only not set already. align = '='; } } } if (!Spec.specified(align)) { align = defaultAlignment; } // Scan [width] if (isDigit()) { try { width = scanInteger(); } catch (NumberFormatException ex) { // CPython seems to happily parse big ints and then it chokes on the allocation throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.WIDTH_TOO_BIG); } } // Scan [,|_][.precision][type] if (scanPast(',')) { grouping = ','; } if (scanPast('_')) { if (specified(grouping)) { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.CANNOT_SPECIFY_BOTH_COMMA_AND_UNDERSCORE); } grouping = '_'; if (scanPast(',')) { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.CANNOT_SPECIFY_BOTH_COMMA_AND_UNDERSCORE); } } // Scan [.precision] if (scanPast('.')) { if (isDigit()) { try { precision = scanInteger(); } catch (NumberFormatException ex) { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.PRECISION_TOO_BIG); } } else { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.FMT_SPECIFIER_MISSING_PRECISION); } } // Scan [type] if (ptr < spec.length()) { type = spec.charAt(ptr++); } // If we haven't reached the end, something is wrong if (ptr != spec.length()) { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.INVALID_CONVERSION_SPECIFICATION); } // Some basic validation if (specified(grouping)) { boolean valid; switch (type) { case 'd': case 'e': case 'f': case 'g': case 'E': case 'G': case '%': case 'F': case '\0': case NONE: // These are allowed. See PEP 378 valid = true; break; case 'b': case 'o': case 'x': case 'X': // Only underscore allowed for those. See PEP 515 valid = grouping == '_'; break; default: valid = false; } if (!valid) { throw PRaiseNode.raiseStatic(raisingNode, ValueError, ErrorMessages.CANNOT_SPECIFY_C_WITH_C, grouping, type); } } // Create a specification return new Spec(fill, align, sign, alternate, width, grouping, precision, type); } /** * Test that the next character is exactly the one specified, and advance past it if it is. */ private boolean scanPast(char c) { if (ptr < spec.length() && spec.charAt(ptr) == c) { ptr++; return true; } else { return false; } } /** Test that the next character is one of a specified set. */ private boolean isAt(String chars) { return ptr < spec.length() && (chars.indexOf(spec.charAt(ptr)) >= 0); } /** Test that the next character is one of the alignment characters. */ private boolean isAlign() { return ptr < spec.length() && ("<^>=".indexOf(spec.charAt(ptr)) >= 0); } /** Test that the next character is a digit. */ private boolean isDigit() { return ptr < spec.length() && Character.isDigit(spec.charAt(ptr)); } /** The current character is a digit (maybe a sign). Scan the integer, */ private int scanInteger() throws NumberFormatException { int p = ptr++; while (isDigit()) { ptr++; } return Integer.parseInt(spec.substring(p, ptr)); } } }
google-ar/arcore-android-sdk
36,758
samples/hardwarebuffer_java/app/src/main/java/com/google/ar/core/examples/java/helloarhardwarebuffer/HelloArHardwareBufferActivity.java
/* * Copyright 2017 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.ar.core.examples.java.helloarhardwarebuffer; import android.content.DialogInterface; import android.content.res.Resources; import android.hardware.HardwareBuffer; import android.media.Image; import android.opengl.GLES30; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.ImageButton; import android.widget.PopupMenu; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import com.google.ar.core.Anchor; import com.google.ar.core.ArCoreApk; import com.google.ar.core.Camera; import com.google.ar.core.Config; import com.google.ar.core.Config.InstantPlacementMode; import com.google.ar.core.DepthPoint; import com.google.ar.core.Frame; import com.google.ar.core.HitResult; import com.google.ar.core.InstantPlacementPoint; import com.google.ar.core.LightEstimate; import com.google.ar.core.Plane; import com.google.ar.core.Point; import com.google.ar.core.Point.OrientationMode; import com.google.ar.core.PointCloud; import com.google.ar.core.Session; import com.google.ar.core.Trackable; import com.google.ar.core.TrackingFailureReason; import com.google.ar.core.TrackingState; import com.google.ar.core.examples.java.common.helpers.CameraPermissionHelper; import com.google.ar.core.examples.java.common.helpers.DepthSettings; import com.google.ar.core.examples.java.common.helpers.DisplayRotationHelper; import com.google.ar.core.examples.java.common.helpers.FullScreenHelper; import com.google.ar.core.examples.java.common.helpers.InstantPlacementSettings; import com.google.ar.core.examples.java.common.helpers.SnackbarHelper; import com.google.ar.core.examples.java.common.helpers.TapHelper; import com.google.ar.core.examples.java.common.helpers.TrackingStateHelper; import com.google.ar.core.examples.java.common.samplerender.Framebuffer; import com.google.ar.core.examples.java.common.samplerender.GLError; import com.google.ar.core.examples.java.common.samplerender.Mesh; import com.google.ar.core.examples.java.common.samplerender.SampleRender; import com.google.ar.core.examples.java.common.samplerender.Shader; import com.google.ar.core.examples.java.common.samplerender.Texture; import com.google.ar.core.examples.java.common.samplerender.VertexBuffer; import com.google.ar.core.examples.java.common.samplerender.arcore.BackgroundRenderer; import com.google.ar.core.examples.java.common.samplerender.arcore.PlaneRenderer; import com.google.ar.core.examples.java.common.samplerender.arcore.SpecularCubemapFilter; import com.google.ar.core.exceptions.CameraNotAvailableException; import com.google.ar.core.exceptions.NotYetAvailableException; import com.google.ar.core.exceptions.UnavailableApkTooOldException; import com.google.ar.core.exceptions.UnavailableArcoreNotInstalledException; import com.google.ar.core.exceptions.UnavailableDeviceNotCompatibleException; import com.google.ar.core.exceptions.UnavailableSdkTooOldException; import com.google.ar.core.exceptions.UnavailableUserDeclinedInstallationException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * This is a simple example that shows how to create an augmented reality (AR) application using the * ARCore API. The application will display any detected planes and will allow the user to tap on a * plane to place a 3D model. */ public class HelloArHardwareBufferActivity extends AppCompatActivity implements SampleRender.Renderer { private static final String TAG = HelloArHardwareBufferActivity.class.getSimpleName(); private static final String SEARCHING_PLANE_MESSAGE = "Searching for surfaces..."; private static final String WAITING_FOR_TAP_MESSAGE = "Tap on a surface to place an object."; // See the definition of updateSphericalHarmonicsCoefficients for an explanation of these // constants. private static final float[] sphericalHarmonicFactors = { 0.282095f, -0.325735f, 0.325735f, -0.325735f, 0.273137f, -0.273137f, 0.078848f, -0.273137f, 0.136569f, }; private static final float Z_NEAR = 0.1f; private static final float Z_FAR = 100f; private static final int CUBEMAP_RESOLUTION = 16; private static final int CUBEMAP_NUMBER_OF_IMPORTANCE_SAMPLES = 32; // Rendering. The Renderers are created here, and initialized when the GL surface is created. private GLSurfaceView surfaceView; private boolean installRequested; private Session session; private final SnackbarHelper messageSnackbarHelper = new SnackbarHelper(); private DisplayRotationHelper displayRotationHelper; private final TrackingStateHelper trackingStateHelper = new TrackingStateHelper(this); private TapHelper tapHelper; private SampleRender render; private PlaneRenderer planeRenderer; private BackgroundRenderer backgroundRenderer; private Framebuffer virtualSceneFramebuffer; private boolean hasSetTextureNames = false; private final DepthSettings depthSettings = new DepthSettings(); private boolean[] depthSettingsMenuDialogCheckboxes = new boolean[2]; private final InstantPlacementSettings instantPlacementSettings = new InstantPlacementSettings(); private boolean[] instantPlacementSettingsMenuDialogCheckboxes = new boolean[1]; // Assumed distance from the device camera to the surface on which user will try to place objects. // This value affects the apparent scale of objects while the tracking method of the // Instant Placement point is SCREENSPACE_WITH_APPROXIMATE_DISTANCE. // Values in the [0.2, 2.0] meter range are a good choice for most AR experiences. Use lower // values for AR experiences where users are expected to place objects on surfaces close to the // camera. Use larger values for experiences where the user will likely be standing and trying to // place an object on the ground or floor in front of them. private static final float APPROXIMATE_DISTANCE_METERS = 2.0f; // Point Cloud private VertexBuffer pointCloudVertexBuffer; private Mesh pointCloudMesh; private Shader pointCloudShader; // Keep track of the last point cloud rendered to avoid updating the VBO if point cloud // was not changed. Do this using the timestamp since we can't compare PointCloud objects. private long lastPointCloudTimestamp = 0; // Virtual object (ARCore pawn) private Mesh virtualObjectMesh; private Shader virtualObjectShader; private Texture virtualObjectAlbedoTexture; private Texture virtualObjectAlbedoInstantPlacementTexture; private final List<WrappedAnchor> wrappedAnchors = new ArrayList<>(); // Environmental HDR private Texture dfgTexture; private SpecularCubemapFilter cubemapFilter; private long imageAddress = 0; // Temporary matrix allocated here to reduce number of allocations for each frame. private final float[] modelMatrix = new float[16]; private final float[] viewMatrix = new float[16]; private final float[] projectionMatrix = new float[16]; private final float[] modelViewMatrix = new float[16]; // view x model private final float[] modelViewProjectionMatrix = new float[16]; // projection x view x model private final float[] sphericalHarmonicsCoefficients = new float[9 * 3]; private final float[] viewInverseMatrix = new float[16]; private final float[] worldLightDirection = {0.0f, 0.0f, 0.0f, 0.0f}; private final float[] viewLightDirection = new float[4]; // view x world light direction @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); surfaceView = findViewById(R.id.surfaceview); displayRotationHelper = new DisplayRotationHelper(/* context= */ this); // Set up touch listener. tapHelper = new TapHelper(/* context= */ this); surfaceView.setOnTouchListener(tapHelper); // Set up renderer. render = new SampleRender(surfaceView, this, getAssets()); installRequested = false; depthSettings.onCreate(this); instantPlacementSettings.onCreate(this); ImageButton settingsButton = findViewById(R.id.settings_button); settingsButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(HelloArHardwareBufferActivity.this, v); popup.setOnMenuItemClickListener(HelloArHardwareBufferActivity.this::settingsMenuClick); popup.inflate(R.menu.settings_menu); popup.show(); } }); } /** Menu button to launch feature specific settings. */ protected boolean settingsMenuClick(MenuItem item) { if (item.getItemId() == R.id.depth_settings) { launchDepthSettingsMenuDialog(); return true; } else if (item.getItemId() == R.id.instant_placement_settings) { launchInstantPlacementSettingsMenuDialog(); return true; } return false; } @Override protected void onDestroy() { if (session != null) { // Explicitly close ARCore Session to release native resources. // Review the API reference for important considerations before calling close() in apps with // more complicated lifecycle requirements: // https://developers.google.com/ar/reference/java/arcore/reference/com/google/ar/core/Session#close() session.close(); session = null; } super.onDestroy(); } @Override protected void onResume() { super.onResume(); if (session == null) { Exception exception = null; String message = null; try { switch (ArCoreApk.getInstance().requestInstall(this, !installRequested)) { case INSTALL_REQUESTED: installRequested = true; return; case INSTALLED: break; } // ARCore requires camera permissions to operate. If we did not yet obtain runtime // permission on Android M and above, now is a good time to ask the user for it. if (!CameraPermissionHelper.hasCameraPermission(this)) { CameraPermissionHelper.requestCameraPermission(this); return; } // Create the session. session = new Session(/* context= */ this); } catch (UnavailableArcoreNotInstalledException | UnavailableUserDeclinedInstallationException e) { message = "Please install ARCore"; exception = e; } catch (UnavailableApkTooOldException e) { message = "Please update ARCore"; exception = e; } catch (UnavailableSdkTooOldException e) { message = "Please update this app"; exception = e; } catch (UnavailableDeviceNotCompatibleException e) { message = "This device does not support AR"; exception = e; } catch (Exception e) { message = "Failed to create AR session"; exception = e; } if (message != null) { messageSnackbarHelper.showError(this, message); Log.e(TAG, "Exception creating session", exception); return; } } // Note that order matters - see the note in onPause(), the reverse applies here. try { configureSession(); // To record a live camera session for later playback, call // `session.startRecording(recordingConfig)` at anytime. To playback a previously recorded AR // session instead of using the live camera feed, call // `session.setPlaybackDatasetUri(Uri)` before calling `session.resume()`. To // learn more about recording and playback, see: // https://developers.google.com/ar/develop/java/recording-and-playback session.resume(); } catch (CameraNotAvailableException e) { messageSnackbarHelper.showError(this, "Camera not available. Try restarting the app."); session = null; return; } catch (Exception e) { messageSnackbarHelper.showError(this, "Got error while configuring the session."); session = null; return; } surfaceView.onResume(); displayRotationHelper.onResume(); } @Override public void onPause() { super.onPause(); if (session != null) { // Note that the order matters - GLSurfaceView is paused first so that it does not try // to query the session. If Session is paused before GLSurfaceView, GLSurfaceView may // still call session.update() and get a SessionPausedException. displayRotationHelper.onPause(); surfaceView.onPause(); session.pause(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] results) { super.onRequestPermissionsResult(requestCode, permissions, results); if (!CameraPermissionHelper.hasCameraPermission(this)) { // Use toast instead of snackbar here since the activity will exit. Toast.makeText(this, "Camera permission is needed to run this application", Toast.LENGTH_LONG) .show(); if (!CameraPermissionHelper.shouldShowRequestPermissionRationale(this)) { // Permission denied with checking "Do not ask again". CameraPermissionHelper.launchPermissionSettings(this); } finish(); } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); FullScreenHelper.setFullScreenOnWindowFocusChanged(this, hasFocus); } @Override public void onSurfaceCreated(SampleRender render) { // Prepare the rendering objects. This involves reading shaders and 3D model files, so may throw // an IOException. try { planeRenderer = new PlaneRenderer(render); backgroundRenderer = new BackgroundRenderer(render); virtualSceneFramebuffer = new Framebuffer(render, /* width= */ 1, /* height= */ 1); cubemapFilter = new SpecularCubemapFilter( render, CUBEMAP_RESOLUTION, CUBEMAP_NUMBER_OF_IMPORTANCE_SAMPLES); // Load DFG lookup table for environmental lighting dfgTexture = new Texture( render, Texture.Target.TEXTURE_2D, Texture.WrapMode.CLAMP_TO_EDGE, /* useMipmaps= */ false); // The dfg.raw file is a raw half-float texture with two channels. final int dfgResolution = 64; final int dfgChannels = 2; final int halfFloatSize = 2; ByteBuffer buffer = ByteBuffer.allocateDirect(dfgResolution * dfgResolution * dfgChannels * halfFloatSize); try (InputStream is = getAssets().open("models/dfg.raw")) { is.read(buffer.array()); } // SampleRender abstraction leaks here. GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, dfgTexture.getTextureId()); GLError.maybeThrowGLException("Failed to bind DFG texture", "glBindTexture"); GLES30.glTexImage2D( GLES30.GL_TEXTURE_2D, /* level= */ 0, GLES30.GL_RG16F, /* width= */ dfgResolution, /* height= */ dfgResolution, /* border= */ 0, GLES30.GL_RG, GLES30.GL_HALF_FLOAT, buffer); GLError.maybeThrowGLException("Failed to populate DFG texture", "glTexImage2D"); // Point cloud pointCloudShader = Shader.createFromAssets( render, "shaders/point_cloud.vert", "shaders/point_cloud.frag", /* defines= */ null) .setVec4( "u_Color", new float[] {31.0f / 255.0f, 188.0f / 255.0f, 210.0f / 255.0f, 1.0f}) .setFloat("u_PointSize", 5.0f); // four entries per vertex: X, Y, Z, confidence pointCloudVertexBuffer = new VertexBuffer(render, /* numberOfEntriesPerVertex= */ 4, /* entries= */ null); final VertexBuffer[] pointCloudVertexBuffers = {pointCloudVertexBuffer}; pointCloudMesh = new Mesh( render, Mesh.PrimitiveMode.POINTS, /* indexBuffer= */ null, pointCloudVertexBuffers); // Virtual object to render (ARCore pawn) virtualObjectAlbedoTexture = Texture.createFromAsset( render, "models/pawn_albedo.png", Texture.WrapMode.CLAMP_TO_EDGE, Texture.ColorFormat.SRGB); virtualObjectAlbedoInstantPlacementTexture = Texture.createFromAsset( render, "models/pawn_albedo_instant_placement.png", Texture.WrapMode.CLAMP_TO_EDGE, Texture.ColorFormat.SRGB); Texture virtualObjectPbrTexture = Texture.createFromAsset( render, "models/pawn_roughness_metallic_ao.png", Texture.WrapMode.CLAMP_TO_EDGE, Texture.ColorFormat.LINEAR); virtualObjectMesh = Mesh.createFromAsset(render, "models/pawn.obj"); virtualObjectShader = Shader.createFromAssets( render, "shaders/environmental_hdr.vert", "shaders/environmental_hdr.frag", /* defines= */ new HashMap<String, String>() { { put( "NUMBER_OF_MIPMAP_LEVELS", Integer.toString(cubemapFilter.getNumberOfMipmapLevels())); } }) .setTexture("u_AlbedoTexture", virtualObjectAlbedoTexture) .setTexture("u_RoughnessMetallicAmbientOcclusionTexture", virtualObjectPbrTexture) .setTexture("u_Cubemap", cubemapFilter.getFilteredCubemapTexture()) .setTexture("u_DfgTexture", dfgTexture); } catch (IOException e) { Log.e(TAG, "Failed to read a required asset file", e); messageSnackbarHelper.showError(this, "Failed to read a required asset file: " + e); } } @Override public void onSurfaceChanged(SampleRender render, int width, int height) { displayRotationHelper.onSurfaceChanged(width, height); virtualSceneFramebuffer.resize(width, height); } @Override public void onDrawFrame(SampleRender render) { if (session == null) { return; } // -- Update per-frame state // Notify ARCore session that the view size changed so that the perspective matrix and // the video background can be properly adjusted. displayRotationHelper.updateSessionIfNeeded(session); // Obtain the current frame from the AR Session. When the configuration is set to // UpdateMode.BLOCKING (it is by default), this will throttle the rendering to the // camera framerate. Frame frame; try { frame = session.update(); } catch (CameraNotAvailableException e) { messageSnackbarHelper.showError(this, "Camera not available. Try restarting the app."); return; } Camera camera = frame.getCamera(); // Update BackgroundRenderer state to match the depth settings. try { backgroundRenderer.setUseDepthVisualization( render, depthSettings.depthColorVisualizationEnabled()); backgroundRenderer.setUseOcclusion(render, depthSettings.useDepthForOcclusion()); } catch (IOException e) { Log.e(TAG, "Failed to read a required asset file", e); messageSnackbarHelper.showError(this, "Failed to read a required asset file: " + e); return; } // BackgroundRenderer.updateDisplayGeometry must be called every frame to update the coordinates // used to draw the background camera image. backgroundRenderer.updateDisplayGeometry(frame); // Get Hardware Buffer and attach it to the texture; HardwareBuffer hardwareBuffer = null; try { hardwareBuffer = frame.getHardwareBuffer(); if (hardwareBuffer == null) { Log.d(TAG, "Hardware Buffer hasn't been available yet."); return; } } catch (Exception e) { Log.e(TAG, "Error in fetching Hardware Buffer.", e); messageSnackbarHelper.showError(this, "Error in fetching Hardware Buffer."); return; } if (imageAddress != 0) { JniInterface.destroyEglImage(imageAddress); } imageAddress = JniInterface.createEglImage(hardwareBuffer); JniInterface.bindEglImageToTexture( imageAddress, backgroundRenderer.getCameraColorTexture().getTextureId()); if (camera.getTrackingState() == TrackingState.TRACKING && (depthSettings.useDepthForOcclusion() || depthSettings.depthColorVisualizationEnabled())) { try (Image depthImage = frame.acquireDepthImage16Bits()) { backgroundRenderer.updateCameraDepthTexture(depthImage); } catch (NotYetAvailableException e) { // This normally means that depth data is not available yet. This is normal so we will not // spam the logcat with this. } } // Handle one tap per frame. handleTap(frame, camera); // Keep the screen unlocked while tracking, but allow it to lock when tracking stops. trackingStateHelper.updateKeepScreenOnFlag(camera.getTrackingState()); // Show a message based on whether tracking has failed, if planes are detected, and if the user // has placed any objects. String message = null; if (camera.getTrackingState() == TrackingState.PAUSED) { if (camera.getTrackingFailureReason() == TrackingFailureReason.NONE) { message = SEARCHING_PLANE_MESSAGE; } else { message = TrackingStateHelper.getTrackingFailureReasonString(camera); } } else if (hasTrackingPlane()) { if (wrappedAnchors.isEmpty()) { message = WAITING_FOR_TAP_MESSAGE; } } else { message = SEARCHING_PLANE_MESSAGE; } if (message == null) { messageSnackbarHelper.hide(this); } else { messageSnackbarHelper.showMessage(this, message); } // -- Draw background if (frame.getTimestamp() != 0) { // Suppress rendering if the camera did not produce the first frame yet. This is to avoid // drawing possible leftover data from previous sessions if the texture is reused. backgroundRenderer.drawBackground(render); } // If not tracking, don't draw 3D objects. if (camera.getTrackingState() == TrackingState.PAUSED) { return; } // -- Draw non-occluded virtual objects (planes, point cloud) // Get projection matrix. camera.getProjectionMatrix(projectionMatrix, 0, Z_NEAR, Z_FAR); // Get camera matrix and draw. camera.getViewMatrix(viewMatrix, 0); // Visualize tracked points. // Use try-with-resources to automatically release the point cloud. try (PointCloud pointCloud = frame.acquirePointCloud()) { if (pointCloud.getTimestamp() > lastPointCloudTimestamp) { pointCloudVertexBuffer.set(pointCloud.getPoints()); lastPointCloudTimestamp = pointCloud.getTimestamp(); } Matrix.multiplyMM(modelViewProjectionMatrix, 0, projectionMatrix, 0, viewMatrix, 0); pointCloudShader.setMat4("u_ModelViewProjection", modelViewProjectionMatrix); render.draw(pointCloudMesh, pointCloudShader); } // Visualize planes. planeRenderer.drawPlanes( render, session.getAllTrackables(Plane.class), camera.getDisplayOrientedPose(), projectionMatrix); // -- Draw occluded virtual objects // Update lighting parameters in the shader updateLightEstimation(frame.getLightEstimate(), viewMatrix); // Visualize anchors created by touch. render.clear(virtualSceneFramebuffer, 0f, 0f, 0f, 0f); for (WrappedAnchor wrappedAnchor : wrappedAnchors) { Anchor anchor = wrappedAnchor.getAnchor(); Trackable trackable = wrappedAnchor.getTrackable(); if (anchor.getTrackingState() != TrackingState.TRACKING) { continue; } // Get the current pose of an Anchor in world space. The Anchor pose is updated // during calls to session.update() as ARCore refines its estimate of the world. anchor.getPose().toMatrix(modelMatrix, 0); // Calculate model/view/projection matrices Matrix.multiplyMM(modelViewMatrix, 0, viewMatrix, 0, modelMatrix, 0); Matrix.multiplyMM(modelViewProjectionMatrix, 0, projectionMatrix, 0, modelViewMatrix, 0); // Update shader properties and draw virtualObjectShader.setMat4("u_ModelView", modelViewMatrix); virtualObjectShader.setMat4("u_ModelViewProjection", modelViewProjectionMatrix); if (trackable instanceof InstantPlacementPoint && ((InstantPlacementPoint) trackable).getTrackingMethod() == InstantPlacementPoint.TrackingMethod.SCREENSPACE_WITH_APPROXIMATE_DISTANCE) { virtualObjectShader.setTexture( "u_AlbedoTexture", virtualObjectAlbedoInstantPlacementTexture); } else { virtualObjectShader.setTexture("u_AlbedoTexture", virtualObjectAlbedoTexture); } render.draw(virtualObjectMesh, virtualObjectShader, virtualSceneFramebuffer); } // Compose the virtual scene with the background. backgroundRenderer.drawVirtualScene(render, virtualSceneFramebuffer, Z_NEAR, Z_FAR); } // Handle only one tap per frame, as taps are usually low frequency compared to frame rate. private void handleTap(Frame frame, Camera camera) { MotionEvent tap = tapHelper.poll(); if (tap != null && camera.getTrackingState() == TrackingState.TRACKING) { List<HitResult> hitResultList; if (instantPlacementSettings.isInstantPlacementEnabled()) { hitResultList = frame.hitTestInstantPlacement(tap.getX(), tap.getY(), APPROXIMATE_DISTANCE_METERS); } else { hitResultList = frame.hitTest(tap); } for (HitResult hit : hitResultList) { // If any plane, Oriented Point, or Instant Placement Point was hit, create an anchor. Trackable trackable = hit.getTrackable(); // If a plane was hit, check that it was hit inside the plane polygon. // DepthPoints are only returned if Config.DepthMode is set to AUTOMATIC. if ((trackable instanceof Plane && ((Plane) trackable).isPoseInPolygon(hit.getHitPose()) && (PlaneRenderer.calculateDistanceToPlane(hit.getHitPose(), camera.getPose()) > 0)) || (trackable instanceof Point && ((Point) trackable).getOrientationMode() == OrientationMode.ESTIMATED_SURFACE_NORMAL) || (trackable instanceof InstantPlacementPoint) || (trackable instanceof DepthPoint)) { // Cap the number of objects created. This avoids overloading both the // rendering system and ARCore. if (wrappedAnchors.size() >= 20) { wrappedAnchors.get(0).getAnchor().detach(); wrappedAnchors.remove(0); } // Adding an Anchor tells ARCore that it should track this position in // space. This anchor is created on the Plane to place the 3D model // in the correct position relative both to the world and to the plane. wrappedAnchors.add(new WrappedAnchor(hit.createAnchor(), trackable)); // For devices that support the Depth API, shows a dialog to suggest enabling // depth-based occlusion. This dialog needs to be spawned on the UI thread. this.runOnUiThread(this::showOcclusionDialogIfNeeded); // Hits are sorted by depth. Consider only closest hit on a plane, Oriented Point, or // Instant Placement Point. break; } } } } /** * Shows a pop-up dialog on the first call, determining whether the user wants to enable * depth-based occlusion. The result of this dialog can be retrieved with useDepthForOcclusion(). */ private void showOcclusionDialogIfNeeded() { boolean isDepthSupported = session.isDepthModeSupported(Config.DepthMode.AUTOMATIC); if (!depthSettings.shouldShowDepthEnableDialog() || !isDepthSupported) { return; // Don't need to show dialog. } // Asks the user whether they want to use depth-based occlusion. new AlertDialog.Builder(this) .setTitle(R.string.options_title_with_depth) .setMessage(R.string.depth_use_explanation) .setPositiveButton( R.string.button_text_enable_depth, (DialogInterface dialog, int which) -> { depthSettings.setUseDepthForOcclusion(true); }) .setNegativeButton( R.string.button_text_disable_depth, (DialogInterface dialog, int which) -> { depthSettings.setUseDepthForOcclusion(false); }) .show(); } private void launchInstantPlacementSettingsMenuDialog() { resetSettingsMenuDialogCheckboxes(); Resources resources = getResources(); new AlertDialog.Builder(this) .setTitle(R.string.options_title_instant_placement) .setMultiChoiceItems( resources.getStringArray(R.array.instant_placement_options_array), instantPlacementSettingsMenuDialogCheckboxes, (DialogInterface dialog, int which, boolean isChecked) -> instantPlacementSettingsMenuDialogCheckboxes[which] = isChecked) .setPositiveButton( R.string.done, (DialogInterface dialogInterface, int which) -> applySettingsMenuDialogCheckboxes()) .setNegativeButton( android.R.string.cancel, (DialogInterface dialog, int which) -> resetSettingsMenuDialogCheckboxes()) .show(); } /** Shows checkboxes to the user to facilitate toggling of depth-based effects. */ private void launchDepthSettingsMenuDialog() { // Retrieves the current settings to show in the checkboxes. resetSettingsMenuDialogCheckboxes(); // Shows the dialog to the user. Resources resources = getResources(); if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) { // With depth support, the user can select visualization options. new AlertDialog.Builder(this) .setTitle(R.string.options_title_with_depth) .setMultiChoiceItems( resources.getStringArray(R.array.depth_options_array), depthSettingsMenuDialogCheckboxes, (DialogInterface dialog, int which, boolean isChecked) -> depthSettingsMenuDialogCheckboxes[which] = isChecked) .setPositiveButton( R.string.done, (DialogInterface dialogInterface, int which) -> applySettingsMenuDialogCheckboxes()) .setNegativeButton( android.R.string.cancel, (DialogInterface dialog, int which) -> resetSettingsMenuDialogCheckboxes()) .show(); } else { // Without depth support, no settings are available. new AlertDialog.Builder(this) .setTitle(R.string.options_title_without_depth) .setPositiveButton( R.string.done, (DialogInterface dialogInterface, int which) -> applySettingsMenuDialogCheckboxes()) .show(); } } private void applySettingsMenuDialogCheckboxes() { depthSettings.setUseDepthForOcclusion(depthSettingsMenuDialogCheckboxes[0]); depthSettings.setDepthColorVisualizationEnabled(depthSettingsMenuDialogCheckboxes[1]); instantPlacementSettings.setInstantPlacementEnabled( instantPlacementSettingsMenuDialogCheckboxes[0]); configureSession(); } private void resetSettingsMenuDialogCheckboxes() { depthSettingsMenuDialogCheckboxes[0] = depthSettings.useDepthForOcclusion(); depthSettingsMenuDialogCheckboxes[1] = depthSettings.depthColorVisualizationEnabled(); instantPlacementSettingsMenuDialogCheckboxes[0] = instantPlacementSettings.isInstantPlacementEnabled(); } /** Checks if we detected at least one plane. */ private boolean hasTrackingPlane() { for (Plane plane : session.getAllTrackables(Plane.class)) { if (plane.getTrackingState() == TrackingState.TRACKING) { return true; } } return false; } /** Update state based on the current frame's light estimation. */ private void updateLightEstimation(LightEstimate lightEstimate, float[] viewMatrix) { if (lightEstimate.getState() != LightEstimate.State.VALID) { virtualObjectShader.setBool("u_LightEstimateIsValid", false); return; } virtualObjectShader.setBool("u_LightEstimateIsValid", true); Matrix.invertM(viewInverseMatrix, 0, viewMatrix, 0); virtualObjectShader.setMat4("u_ViewInverse", viewInverseMatrix); updateMainLight( lightEstimate.getEnvironmentalHdrMainLightDirection(), lightEstimate.getEnvironmentalHdrMainLightIntensity(), viewMatrix); updateSphericalHarmonicsCoefficients( lightEstimate.getEnvironmentalHdrAmbientSphericalHarmonics()); cubemapFilter.update(lightEstimate.acquireEnvironmentalHdrCubeMap()); } private void updateMainLight(float[] direction, float[] intensity, float[] viewMatrix) { // We need the direction in a vec4 with 0.0 as the final component to transform it to view space worldLightDirection[0] = direction[0]; worldLightDirection[1] = direction[1]; worldLightDirection[2] = direction[2]; Matrix.multiplyMV(viewLightDirection, 0, viewMatrix, 0, worldLightDirection, 0); virtualObjectShader.setVec4("u_ViewLightDirection", viewLightDirection); virtualObjectShader.setVec3("u_LightIntensity", intensity); } private void updateSphericalHarmonicsCoefficients(float[] coefficients) { // Pre-multiply the spherical harmonics coefficients before passing them to the shader. The // constants in sphericalHarmonicFactors were derived from three terms: // // 1. The normalized spherical harmonics basis functions (y_lm) // // 2. The lambertian diffuse BRDF factor (1/pi) // // 3. A <cos> convolution. This is done to so that the resulting function outputs the irradiance // of all incoming light over a hemisphere for a given surface normal, which is what the shader // (environmental_hdr.frag) expects. // // You can read more details about the math here: // https://google.github.io/filament/Filament.html#annex/sphericalharmonics if (coefficients.length != 9 * 3) { throw new IllegalArgumentException( "The given coefficients array must be of length 27 (3 components per 9 coefficients"); } // Apply each factor to every component of each coefficient for (int i = 0; i < 9 * 3; ++i) { sphericalHarmonicsCoefficients[i] = coefficients[i] * sphericalHarmonicFactors[i / 3]; } virtualObjectShader.setVec3Array( "u_SphericalHarmonicsCoefficients", sphericalHarmonicsCoefficients); } /** Configures the session with feature settings. */ private void configureSession() { Config config = session.getConfig(); config.setLightEstimationMode(Config.LightEstimationMode.ENVIRONMENTAL_HDR); if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) { config.setDepthMode(Config.DepthMode.AUTOMATIC); } else { config.setDepthMode(Config.DepthMode.DISABLED); } if (instantPlacementSettings.isInstantPlacementEnabled()) { config.setInstantPlacementMode(InstantPlacementMode.LOCAL_Y_UP); } else { config.setInstantPlacementMode(InstantPlacementMode.DISABLED); } Config unused = config.setTextureUpdateMode(Config.TextureUpdateMode.EXPOSE_HARDWARE_BUFFER); session.configure(config); } } /** * Associates an Anchor with the trackable it was attached to. This is used to be able to check * whether or not an Anchor originally was attached to an {@link InstantPlacementPoint}. */ class WrappedAnchor { private Anchor anchor; private Trackable trackable; public WrappedAnchor(Anchor anchor, Trackable trackable) { this.anchor = anchor; this.trackable = trackable; } public Anchor getAnchor() { return anchor; } public Trackable getTrackable() { return trackable; } }
apache/phoenix
36,607
phoenix-core-server/src/main/java/org/apache/phoenix/mapreduce/OrphanViewTool.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.mapreduce; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_FAMILY; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.LINK_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CHILD_LINK_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_SCHEM; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TENANT_ID; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.VIEW_TYPE; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.mapreduce.util.ConnectionUtil; import org.apache.phoenix.parse.DropTableStatement; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.query.QueryServicesOptions; import org.apache.phoenix.schema.MetaDataClient; import org.apache.phoenix.schema.PTable; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.TableNotFoundException; import org.apache.phoenix.util.EnvironmentEdgeManager; import org.apache.phoenix.util.PhoenixRuntime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.phoenix.thirdparty.org.apache.commons.cli.CommandLine; import org.apache.phoenix.thirdparty.org.apache.commons.cli.CommandLineParser; import org.apache.phoenix.thirdparty.org.apache.commons.cli.DefaultParser; import org.apache.phoenix.thirdparty.org.apache.commons.cli.HelpFormatter; import org.apache.phoenix.thirdparty.org.apache.commons.cli.Option; import org.apache.phoenix.thirdparty.org.apache.commons.cli.Options; import org.apache.phoenix.thirdparty.org.apache.commons.cli.ParseException; /** * A tool to identify orphan views and links, and drop them */ public class OrphanViewTool extends Configured implements Tool { private static final Logger LOGGER = LoggerFactory.getLogger(OrphanViewTool.class); // Query all the views that are not "MAPPED" views private static final String viewQuery = "SELECT " + TENANT_ID + ", " + TABLE_SCHEM + "," + TABLE_NAME + " FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_TYPE + " = '" + PTableType.VIEW.getSerializedValue() + "' AND NOT " + VIEW_TYPE + " = " + PTable.ViewType.MAPPED.getSerializedValue(); // Query all physical links private static final String physicalLinkQuery = "SELECT " + TENANT_ID + ", " + TABLE_SCHEM + ", " + TABLE_NAME + ", " + COLUMN_NAME + " AS PHYSICAL_TABLE_TENANT_ID, " + COLUMN_FAMILY + " AS PHYSICAL_TABLE_FULL_NAME " + " FROM " + SYSTEM_CATALOG_NAME + " WHERE " + LINK_TYPE + " = " + PTable.LinkType.PHYSICAL_TABLE.getSerializedValue(); // Query all child-parent links private static final String childParentLinkQuery = "SELECT " + TENANT_ID + ", " + TABLE_SCHEM + ", " + TABLE_NAME + ", " + COLUMN_NAME + " AS PARENT_VIEW_TENANT_ID, " + COLUMN_FAMILY + " AS PARENT_VIEW_FULL_NAME " + " FROM " + SYSTEM_CATALOG_NAME + " WHERE " + LINK_TYPE + " = " + PTable.LinkType.PARENT_TABLE.getSerializedValue(); // Query all parent-child links private static final String parentChildLinkQuery = "SELECT " + TENANT_ID + ", " + TABLE_SCHEM + ", " + TABLE_NAME + ", " + COLUMN_NAME + " AS CHILD_VIEW_TENANT_ID, " + COLUMN_FAMILY + " AS CHILD_VIEW_FULL_NAME " + " FROM " + SYSTEM_CHILD_LINK_NAME + " WHERE " + LINK_TYPE + " = " + PTable.LinkType.CHILD_TABLE.getSerializedValue(); // Query all the tables that can be a base table private static final String candidateBaseTableQuery = "SELECT " + TENANT_ID + ", " + TABLE_SCHEM + ", " + TABLE_NAME + " FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_TYPE + " != '" + PTableType.VIEW.getSerializedValue() + "' AND " + TABLE_TYPE + " != '" + PTableType.INDEX.getSerializedValue() + "'"; // The path of the directory of the output files private String outputPath; // The path of the directory of the input files private String inputPath; // The flag to indicate if the orphan views and links will be deleted private boolean clean = false; // The maximum level found in a view tree private int maxViewLevel = 0; // The age of a view private static final long defaultAgeMs = 24 * 60 * 60 * 1000; // 1 day private long ageMs = 0; // A separate file is maintained to list orphan views, and each type of orphan links public static final byte VIEW = 0; public static final byte PHYSICAL_TABLE_LINK = 1; public static final byte PARENT_TABLE_LINK = 2; public static final byte CHILD_TABLE_LINK = 3; public static final byte ORPHAN_TYPE_COUNT = 4; BufferedWriter writer[] = new BufferedWriter[ORPHAN_TYPE_COUNT]; BufferedReader reader[] = new BufferedReader[ORPHAN_TYPE_COUNT]; // The set of orphan views HashMap<Key, View> orphanViewSet = new HashMap<>(); // The array list of set of views such that the views in the first set are the first level views // and the views // in the second set is the second level views, and so on List<HashMap<Key, View>> viewSetArray = new ArrayList<HashMap<Key, View>>(); // The set of base tables HashMap<Key, Base> baseSet = new HashMap<>(); // The set of orphan links. These links can be CHILD_TABLE, PARENT_TABLE, or PHYSICAL_TABLE links HashSet<Link> orphanLinkSet = new HashSet<>(); public static final String fileName[] = { "OrphanView.txt", "OrphanPhysicalTableLink.txt", "OrphanParentTableLink.txt", "OrphanChildTableLink.txt" }; private static final Option OUTPUT_PATH_OPTION = new Option("op", "output-path", true, "Output path where the files listing orphan views and links are written"); private static final Option INPUT_PATH_OPTION = new Option("ip", "input-path", true, "Input path where the files listing orphan views and links are read"); private static final Option CLEAN_ORPHAN_VIEWS_OPTION = new Option("c", "clean", false, "If specified, cleans orphan views and links"); private static final Option IDENTIFY_ORPHAN_VIEWS_OPTION = new Option("i", "identify", false, "If specified, identifies orphan views and links"); private static final Option AGE_OPTION = new Option("a", "age", true, "The minimum age (in milliseconds) for the views (default value is " + Long.toString(defaultAgeMs) + ", i.e. 1 day)"); private static final Option HELP_OPTION = new Option("h", "help", false, "Help"); private Options getOptions() { final Options options = new Options(); options.addOption(OUTPUT_PATH_OPTION); options.addOption(INPUT_PATH_OPTION); options.addOption(CLEAN_ORPHAN_VIEWS_OPTION); options.addOption(IDENTIFY_ORPHAN_VIEWS_OPTION); options.addOption(AGE_OPTION); options.addOption(HELP_OPTION); return options; } /** * Parses the commandline arguments, throws IllegalStateException if mandatory arguments are * missing. * @param args supplied command line arguments */ private void parseOptions(String[] args) throws Exception { final Options options = getOptions(); CommandLineParser parser = DefaultParser.builder().setAllowPartialMatching(false) .setStripLeadingAndTrailingQuotes(false).build(); CommandLine cmdLine = null; try { cmdLine = parser.parse(options, args); } catch (ParseException e) { printHelpAndExit("Error parsing command line options: " + e.getMessage(), options); } if (cmdLine.hasOption(HELP_OPTION.getOpt())) { printHelpAndExit(options, 0); } if ( cmdLine.hasOption(OUTPUT_PATH_OPTION.getOpt()) && cmdLine.hasOption(INPUT_PATH_OPTION.getOpt()) ) { throw new IllegalStateException( "Specify either " + OUTPUT_PATH_OPTION.getLongOpt() + " or " + INPUT_PATH_OPTION.getOpt()); } if ( cmdLine.hasOption(INPUT_PATH_OPTION.getOpt()) && !cmdLine.hasOption(CLEAN_ORPHAN_VIEWS_OPTION.getOpt()) ) { throw new IllegalStateException(INPUT_PATH_OPTION.getLongOpt() + " is only used with " + IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt()); } if ( cmdLine.hasOption(IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt()) && cmdLine.hasOption(CLEAN_ORPHAN_VIEWS_OPTION.getOpt()) ) { throw new IllegalStateException("Specify either " + IDENTIFY_ORPHAN_VIEWS_OPTION.getLongOpt() + " or " + IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt()); } if ( cmdLine.hasOption(OUTPUT_PATH_OPTION.getOpt()) && (!cmdLine.hasOption(IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt()) && !cmdLine.hasOption(CLEAN_ORPHAN_VIEWS_OPTION.getOpt())) ) { throw new IllegalStateException(OUTPUT_PATH_OPTION.getLongOpt() + " requires either " + IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt() + " or " + CLEAN_ORPHAN_VIEWS_OPTION.getOpt()); } if (cmdLine.hasOption(CLEAN_ORPHAN_VIEWS_OPTION.getOpt())) { clean = true; } else if (!cmdLine.hasOption(IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt())) { throw new IllegalStateException("Specify either " + IDENTIFY_ORPHAN_VIEWS_OPTION.getOpt() + " or " + CLEAN_ORPHAN_VIEWS_OPTION.getOpt()); } if (cmdLine.hasOption(AGE_OPTION.getOpt())) { ageMs = Long.parseLong(cmdLine.getOptionValue(AGE_OPTION.getOpt())); } outputPath = cmdLine.getOptionValue(OUTPUT_PATH_OPTION.getOpt()); inputPath = cmdLine.getOptionValue(INPUT_PATH_OPTION.getOpt()); } private void printHelpAndExit(String errorMessage, Options options) { System.err.println(errorMessage); printHelpAndExit(options, 1); } private void printHelpAndExit(Options options, int exitCode) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("help", options); System.exit(exitCode); } /** * The key that uniquely identifies a table (i.e., a base table or table view) */ private static class Key { private String serializedValue; public Key(String tenantId, String schemaName, String tableName) throws IllegalArgumentException { if (tableName == null) { throw new IllegalArgumentException(); } serializedValue = (tenantId != null ? tenantId + "," : ",") + (schemaName != null ? schemaName + "," : ",") + tableName; } public Key(String tenantId, String fullTableName) { String[] columns = fullTableName.split("\\."); String schemaName; String tableName; if (columns.length == 1) { schemaName = null; tableName = fullTableName; } else { schemaName = columns[0]; tableName = columns[1]; } if (tableName == null || tableName.compareTo("") == 0) { throw new IllegalArgumentException(); } serializedValue = (tenantId != null ? tenantId + "," : ",") + (schemaName != null ? schemaName + "," : ",") + tableName; } public Key(String serializedKey) { serializedValue = serializedKey; if (this.getTableName() == null || this.getTableName().compareTo("") == 0) { throw new IllegalArgumentException(); } } public String getTenantId() { String[] columns = serializedValue.split(","); return columns[0].compareTo("") == 0 ? null : columns[0]; } public String getSchemaName() { String[] columns = serializedValue.split(","); return columns[1].compareTo("") == 0 ? null : columns[1]; } public String getTableName() { String[] columns = serializedValue.split(","); return columns[2]; } public String getSerializedValue() { return serializedValue; } @Override public int hashCode() { return Objects.hash(getSerializedValue()); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (getClass() != obj.getClass()) return false; Key other = (Key) obj; if (this.getSerializedValue().compareTo(other.getSerializedValue()) != 0) return false; return true; } } /** * An abstract class to represent a table that can be a base table or table view */ private static abstract class Table { protected Key key; protected List<Key> childViews; public void addChild(Key childView) { if (childViews == null) { childViews = new LinkedList<>(); } childViews.add(childView); } public boolean isParent() { if (childViews == null || childViews.isEmpty()) { return false; } return true; } } /** * A class to represents a base table */ private static class Base extends Table { public Base(Key key) { this.key = key; } } /** * A class to represents a table view */ private static class View extends Table { Key parent; Key base; public View(Key key) { this.key = key; } public void setParent(Key parent) { this.parent = parent; } public void setBase(Key base) { this.base = base; } } private static class Link { Key src; Key dst; PTable.LinkType type; public Link(Key src, Key dst, PTable.LinkType type) { this.src = src; this.dst = dst; this.type = type; } public String serialize() { return src.getSerializedValue() + "," + dst.getSerializedValue() + "," + type.toString(); } @Override public int hashCode() { return Objects.hash(serialize()); } } private void gracefullyDropView(PhoenixConnection phoenixConnection, Configuration configuration, Key key) throws Exception { PhoenixConnection tenantConnection = null; boolean newConn = false; try { if (key.getTenantId() != null) { Properties tenantProps = new Properties(); tenantProps.setProperty(PhoenixRuntime.TENANT_ID_ATTRIB, key.getTenantId()); tenantConnection = ConnectionUtil.getInputConnection(configuration, tenantProps) .unwrap(PhoenixConnection.class); newConn = true; } else { tenantConnection = phoenixConnection; } MetaDataClient client = new MetaDataClient(tenantConnection); org.apache.phoenix.parse.TableName pTableName = org.apache.phoenix.parse.TableName.create(key.getSchemaName(), key.getTableName()); try { client.dropTable(new DropTableStatement(pTableName, PTableType.VIEW, false, true, true)); } catch (TableNotFoundException e) { LOGGER.info("Ignoring view " + pTableName + " as it has already been dropped"); } } finally { if (newConn) { // TODO can this be rewritten with try-with-resources ? tryClosingConnection(tenantConnection); } } } private void removeLink(PhoenixConnection phoenixConnection, Key src, Key dst, PTable.LinkType linkType) throws Exception { String delTable = (linkType == PTable.LinkType.PHYSICAL_TABLE || linkType == PTable.LinkType.PARENT_TABLE) ? SYSTEM_CATALOG_NAME : SYSTEM_CHILD_LINK_NAME; String deleteQuery = String.format( " DELETE FROM %s WHERE " + TENANT_ID + " %s AND " + TABLE_SCHEM + " %s AND " + TABLE_NAME + " = ? AND " + COLUMN_NAME + " %s AND " + COLUMN_FAMILY + " = ? ", delTable, src.getTenantId() == null ? " IS NULL" : " = ? ", src.getSchemaName() == null ? " IS NULL " : " = ? ", dst.getTenantId() == null ? " IS NULL" : " = ?"); try (PreparedStatement delStmt = phoenixConnection.prepareStatement(deleteQuery)) { int param = 0; if (src.getTenantId() != null) { delStmt.setString(++param, src.getTenantId()); } if (src.getSchemaName() != null) { delStmt.setString(++param, src.getSchemaName()); } delStmt.setString(++param, src.getTableName()); if (dst.getTenantId() != null) { delStmt.setString(++param, dst.getTenantId()); } if (dst.getSchemaName() == null) { delStmt.setString(++param, dst.getTableName()); } else { delStmt.setString(++param, dst.getSchemaName() + "." + dst.getTableName()); } delStmt.execute(); phoenixConnection.commit(); } } private byte getLinkType(PTable.LinkType linkType) { byte type; if (linkType == PTable.LinkType.PHYSICAL_TABLE) { type = PHYSICAL_TABLE_LINK; } else if (linkType == PTable.LinkType.PARENT_TABLE) { type = PARENT_TABLE_LINK; } else if (linkType == PTable.LinkType.CHILD_TABLE) { type = CHILD_TABLE_LINK; } else { throw new AssertionError("Unknown Link Type"); } return type; } private PTable.LinkType getLinkType(byte linkType) { PTable.LinkType type; if (linkType == PHYSICAL_TABLE_LINK) { type = PTable.LinkType.PHYSICAL_TABLE; } else if (linkType == PARENT_TABLE_LINK) { type = PTable.LinkType.PARENT_TABLE; } else if (linkType == CHILD_TABLE_LINK) { type = PTable.LinkType.CHILD_TABLE; } else { throw new AssertionError("Unknown Link Type"); } return type; } private void removeOrLogOrphanLinks(PhoenixConnection phoenixConnection) { for (Link link : orphanLinkSet) { try { byte linkType = getLinkType(link.type); if (outputPath != null) { writer[linkType] .write(link.src.getSerializedValue() + "-->" + link.dst.getSerializedValue()); writer[linkType].newLine(); } else if (!clean) { System.out.println(link.src.getSerializedValue() + "-(" + link.type + ")->" + link.dst.getSerializedValue()); } if (clean) { removeLink(phoenixConnection, link.src, link.dst, link.type); } } catch (Exception e) { // ignore } } } private void forcefullyDropView(PhoenixConnection phoenixConnection, Key key) throws Exception { String deleteRowsFromCatalog = String.format( "DELETE FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TENANT_ID + " %s AND " + TABLE_SCHEM + " %s AND " + TABLE_NAME + " = ? ", key.getTenantId() == null ? " IS NULL" : " = ? ", key.getSchemaName() == null ? " IS NULL " : " = ? "); String deleteRowsFromChildLink = String.format("DELETE FROM " + SYSTEM_CHILD_LINK_NAME + " WHERE " + COLUMN_NAME + " %s AND " + COLUMN_FAMILY + " = ? ", key.getTenantId() == null ? " IS NULL" : " = ? "); try { try ( PreparedStatement delSysCat = phoenixConnection.prepareStatement(deleteRowsFromCatalog)) { int param = 0; if (key.getTenantId() != null) { delSysCat.setString(++param, key.getTenantId()); } if (key.getSchemaName() != null) { delSysCat.setString(++param, key.getSchemaName()); } delSysCat.setString(++param, key.getTableName()); delSysCat.execute(); } try ( PreparedStatement delChLink = phoenixConnection.prepareStatement(deleteRowsFromChildLink)) { int param = 0; if (key.getTenantId() != null) { delChLink.setString(++param, key.getTenantId()); } delChLink.setString(++param, key.getSchemaName() == null ? key.getTableName() : (key.getSchemaName() + "." + key.getTableName())); delChLink.execute(); } phoenixConnection.commit(); } catch (SQLException e) { throw new IOException(e); } } private void dropOrLogOrphanViews(PhoenixConnection phoenixConnection, Configuration configuration, Key key) throws Exception { if (outputPath != null) { writer[VIEW].write(key.getSerializedValue()); writer[VIEW].newLine(); } else if (!clean) { System.out.println(key.getSerializedValue()); return; } if (!clean) { return; } gracefullyDropView(phoenixConnection, configuration, key); } /** * Go through all the views in the system catalog table and add them to orphanViewSet */ private void populateOrphanViewSet(PhoenixConnection phoenixConnection) throws Exception { ResultSet viewRS = phoenixConnection.createStatement().executeQuery(viewQuery); while (viewRS.next()) { String tenantId = viewRS.getString(1); String schemaName = viewRS.getString(2); String tableName = viewRS.getString(3); Key key = new Key(tenantId, schemaName, tableName); View view = new View(key); orphanViewSet.put(key, view); } } /** * Go through all the tables in the system catalog table and update baseSet */ private void populateBaseSet(PhoenixConnection phoenixConnection) throws Exception { ResultSet baseTableRS = phoenixConnection.createStatement().executeQuery(candidateBaseTableQuery); while (baseTableRS.next()) { String tenantId = baseTableRS.getString(1); String schemaName = baseTableRS.getString(2); String tableName = baseTableRS.getString(3); Key key = new Key(tenantId, schemaName, tableName); Base base = new Base(key); baseSet.put(key, base); } } /** * Go through all the physical links in the system catalog table and update the base table info of * the view objects in orphanViewSet. If the base or view object does not exist for a given link, * then add the link to orphanLinkSet */ private void processPhysicalLinks(PhoenixConnection phoenixConnection) throws Exception { ResultSet physicalLinkRS = phoenixConnection.createStatement().executeQuery(physicalLinkQuery); while (physicalLinkRS.next()) { String tenantId = physicalLinkRS.getString(1); String schemaName = physicalLinkRS.getString(2); String tableName = physicalLinkRS.getString(3); Key viewKey = new Key(tenantId, schemaName, tableName); View view = orphanViewSet.get(viewKey); String baseTenantId = physicalLinkRS.getString(4); String baseFullTableName = physicalLinkRS.getString(5); Key baseKey = new Key(baseTenantId, baseFullTableName); Base base = baseSet.get(baseKey); if (view == null || base == null) { orphanLinkSet.add(new Link(viewKey, baseKey, PTable.LinkType.PHYSICAL_TABLE)); } else { view.setBase(baseKey); } } } /** * Go through all the child-parent links and update the parent field of the view objects of * orphanViewSet. Check if the child does not exist add the link to orphanLinkSet. */ private void processChildParentLinks(PhoenixConnection phoenixConnection) throws Exception { ResultSet childParentLinkRS = phoenixConnection.createStatement().executeQuery(childParentLinkQuery); while (childParentLinkRS.next()) { String childTenantId = childParentLinkRS.getString(1); String childSchemaName = childParentLinkRS.getString(2); String childTableName = childParentLinkRS.getString(3); Key childKey = new Key(childTenantId, childSchemaName, childTableName); View childView = orphanViewSet.get(childKey); String parentTenantId = childParentLinkRS.getString(4); String parentFullTableName = childParentLinkRS.getString(5); Key parentKey = new Key(parentTenantId, parentFullTableName); View parentView = orphanViewSet.get(parentKey); // Check if parentTenantId is not set but it should have been the same as the childTenantId. // Is this a bug? if ( childView != null && parentView == null && parentTenantId == null && childTenantId != null ) { Key anotherParentKey = new Key(childTenantId, parentFullTableName); parentView = orphanViewSet.get(anotherParentKey); if (parentView != null) { parentKey = anotherParentKey; } } if (childView == null || parentView == null) { orphanLinkSet.add(new Link(childKey, parentKey, PTable.LinkType.PARENT_TABLE)); } else { childView.setParent(parentKey); } } } /** * Go through all the parent-child links and update the parent field of the child view objects of * orphanViewSet and the child links of the parent objects (which can be a view from orphanViewSet * or a base table from baseSet. Check if the child or parent does not exist, and if so, add the * link to orphanLinkSet. */ private void processParentChildLinks(PhoenixConnection phoenixConnection) throws Exception { ResultSet parentChildLinkRS = phoenixConnection.createStatement().executeQuery(parentChildLinkQuery); while (parentChildLinkRS.next()) { String tenantId = parentChildLinkRS.getString(1); String schemaName = parentChildLinkRS.getString(2); String tableName = parentChildLinkRS.getString(3); Key parentKey = new Key(tenantId, schemaName, tableName); Base base = baseSet.get(parentKey); View parentView = orphanViewSet.get(parentKey); String childTenantId = parentChildLinkRS.getString(4); String childFullTableName = parentChildLinkRS.getString(5); Key childKey = new Key(childTenantId, childFullTableName); View childView = orphanViewSet.get(childKey); if (childView == null) { // No child for this link orphanLinkSet.add(new Link(parentKey, childKey, PTable.LinkType.CHILD_TABLE)); } else if (base != null) { base.addChild(childKey); } else if (parentView != null) { parentView.addChild(childKey); } else { // No parent for this link orphanLinkSet.add(new Link(parentKey, childKey, PTable.LinkType.CHILD_TABLE)); } } } private void removeBaseTablesWithNoChildViewFromBaseSet() { Iterator<Map.Entry<Key, Base>> iterator = baseSet.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Key, Base> entry = iterator.next(); if (entry.getValue().childViews == null || entry.getValue().childViews.isEmpty()) { iterator.remove(); } } } /** * Starting from the child views of the base tables from baseSet, visit views level by level and * identify missing or broken links, and thereby identify orphan vies */ private void visitViewsLevelByLevelAndIdentifyOrphanViews() { if (baseSet.isEmpty()) return; HashMap<Key, View> viewSet = new HashMap<>(); viewSetArray.add(0, viewSet); // Remove the child views of the tables of baseSet from orphanViewSet and add them to // viewSetArray[0] // if these views have the correct physical link for (Map.Entry<Key, Base> baseEntry : baseSet.entrySet()) { for (Key child : baseEntry.getValue().childViews) { View childView = orphanViewSet.get(child); if ( childView != null && childView.base != null && childView.base.equals(baseEntry.getKey()) ) { orphanViewSet.remove(child); viewSet.put(child, childView); } } } HashMap<Key, View> parentViewSet = viewSet; // Remove the child views of viewSetArray[N] from orphanViewSet and add them to // viewSetArray[N+1] // if these view have the correct physical link and parent link maxViewLevel = 1; for (int i = 1; !parentViewSet.isEmpty(); i++) { HashMap<Key, View> childViewSet = new HashMap<>(); viewSetArray.add(i, childViewSet); for (Map.Entry<Key, View> viewEntry : parentViewSet.entrySet()) { View parentView = viewEntry.getValue(); Key parentKey = viewEntry.getKey(); if (parentView.isParent()) { for (Key child : parentView.childViews) { View childView = orphanViewSet.get(child); if ( childView != null && childView.parent != null && childView.parent.equals(parentKey) && childView.base != null && childView.base.equals(parentView.base) ) { orphanViewSet.remove(child); childViewSet.put(child, childView); } } } } parentViewSet = childViewSet; maxViewLevel += 1; } } private void identifyOrphanViews(PhoenixConnection phoenixConnection) throws Exception { if (inputPath != null) { readOrphanViews(); return; } // Go through the views and add them to orphanViewSet populateOrphanViewSet(phoenixConnection); // Go through the candidate base tables and add them to baseSet populateBaseSet(phoenixConnection); // Go through physical links and update the views of orphanLinkSet processPhysicalLinks(phoenixConnection); // Go through the parent-child links and update the views of orphanViewSet and the tables of // baseSet processParentChildLinks(phoenixConnection); // Go through index-view links and update the views of orphanLinkSet processChildParentLinks(phoenixConnection); if (baseSet == null) return; // Remove the base tables with no child from baseSet removeBaseTablesWithNoChildViewFromBaseSet(); // Starting from the child views of the base tables, visit views level by level and identify // missing or broken links and thereby identify orphan vies visitViewsLevelByLevelAndIdentifyOrphanViews(); } private void createSnapshot(PhoenixConnection phoenixConnection, long scn) throws Exception { try (Admin admin = phoenixConnection.getQueryServices().getAdmin()) { admin.snapshot("OrphanViewTool." + scn, TableName.valueOf(SYSTEM_CATALOG_NAME)); admin.snapshot("OrphanViewTool." + (scn + 1), TableName.valueOf(SYSTEM_CHILD_LINK_NAME)); } } private void readOrphanViews() throws Exception { String aLine; reader[VIEW] = new BufferedReader(new InputStreamReader( new FileInputStream(Paths.get(inputPath, fileName[VIEW]).toFile()), StandardCharsets.UTF_8)); while ((aLine = reader[VIEW].readLine()) != null) { Key key = new Key(aLine); orphanViewSet.put(key, new View(key)); } } private void readAndRemoveOrphanLinks(PhoenixConnection phoenixConnection) throws Exception { String aLine; for (byte i = VIEW + 1; i < ORPHAN_TYPE_COUNT; i++) { reader[i] = new BufferedReader(new InputStreamReader( new FileInputStream(Paths.get(inputPath, fileName[i]).toFile()), StandardCharsets.UTF_8)); while ((aLine = reader[i].readLine()) != null) { String ends[] = aLine.split("-->"); removeLink(phoenixConnection, new Key(ends[0]), new Key(ends[1]), getLinkType(i)); } } } private void closeConnectionAndFiles(Connection connection) throws IOException { tryClosingConnection(connection); for (byte i = VIEW; i < ORPHAN_TYPE_COUNT; i++) { if (writer[i] != null) { writer[i].close(); } if (reader[i] != null) { reader[i].close(); } } } /** * Try closing a connection if it is not null * @param connection connection object * @throws RuntimeException if closing the connection fails */ private void tryClosingConnection(Connection connection) { try { if (connection != null) { connection.close(); } } catch (SQLException sqlE) { LOGGER.error("Failed to close connection: ", sqlE); throw new RuntimeException("Failed to close connection with exception: ", sqlE); } } /** * Examples for input arguments: -c : cleans orphan views -c -op /tmp/ : cleans orphan views and * links, and logs their names to the files named Orphan*.txt in /tmp/ -i : identifies orphan * views and links, and prints their names on the console -i -op /tmp/ : identifies orphan views * and links, and logs the name of their names to files named Orphan*.txt in /tmp/ -c -ip /tmp/ : * cleans the views listed in files at /tmp/ */ @Override public int run(String[] args) throws Exception { Connection connection = null; try { final Configuration configuration = HBaseConfiguration.addHbaseResources(getConf()); try { parseOptions(args); } catch (IllegalStateException e) { printHelpAndExit(e.getMessage(), getOptions()); } if (outputPath != null) { // Create files to log orphan views and links for (int i = VIEW; i < ORPHAN_TYPE_COUNT; i++) { File file = Paths.get(outputPath, fileName[i]).toFile(); if (file.exists()) { file.delete(); } file.createNewFile(); writer[i] = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); } } Properties props = new Properties(); long scn = EnvironmentEdgeManager.currentTimeMillis() - ageMs; props.setProperty("CurrentSCN", Long.toString(scn)); connection = ConnectionUtil.getInputConnection(configuration, props); PhoenixConnection phoenixConnection = connection.unwrap(PhoenixConnection.class); identifyOrphanViews(phoenixConnection); if (clean) { // Close the connection with SCN phoenixConnection.close(); connection = ConnectionUtil.getInputConnection(configuration); phoenixConnection = connection.unwrap(PhoenixConnection.class); // Take a snapshot of system tables to be modified createSnapshot(phoenixConnection, scn); } for (Map.Entry<Key, View> entry : orphanViewSet.entrySet()) { try { dropOrLogOrphanViews(phoenixConnection, configuration, entry.getKey()); } catch (Exception e) { // Ignore } } ; if (clean) { // Wait for the view drop tasks in the SYSTEM.TASK table to be processed long timeInterval = configuration.getLong(QueryServices.TASK_HANDLING_INTERVAL_MS_ATTRIB, QueryServicesOptions.DEFAULT_TASK_HANDLING_INTERVAL_MS); Thread.sleep(maxViewLevel * timeInterval); // Clean up any remaining orphan view records from system tables for (Map.Entry<Key, View> entry : orphanViewSet.entrySet()) { try { forcefullyDropView(phoenixConnection, entry.getKey()); } catch (Exception e) { // Ignore } } ; } if (inputPath == null) { removeOrLogOrphanLinks(phoenixConnection); } else { readAndRemoveOrphanLinks(phoenixConnection); } return 0; } catch (Exception ex) { LOGGER.error("Orphan View Tool : An exception occurred " + ExceptionUtils.getMessage(ex) + " at:\n" + ExceptionUtils.getStackTrace(ex)); return -1; } finally { // TODO use try-with-resources at least for the Connection ? closeConnectionAndFiles(connection); } } public static void main(final String[] args) throws Exception { int result = ToolRunner.run(new OrphanViewTool(), args); System.exit(result); } }
googleapis/google-cloud-java
36,603
java-cloudbuild/proto-google-cloud-build-v1/src/main/java/com/google/cloudbuild/v1/ListWorkerPoolsResponse.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> * Response containing existing `WorkerPools`. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.ListWorkerPoolsResponse} */ public final class ListWorkerPoolsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.devtools.cloudbuild.v1.ListWorkerPoolsResponse) ListWorkerPoolsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListWorkerPoolsResponse.newBuilder() to construct. private ListWorkerPoolsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListWorkerPoolsResponse() { workerPools_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListWorkerPoolsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_ListWorkerPoolsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_ListWorkerPoolsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.ListWorkerPoolsResponse.class, com.google.cloudbuild.v1.ListWorkerPoolsResponse.Builder.class); } public static final int WORKER_POOLS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloudbuild.v1.WorkerPool> workerPools_; /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloudbuild.v1.WorkerPool> getWorkerPoolsList() { return workerPools_; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloudbuild.v1.WorkerPoolOrBuilder> getWorkerPoolsOrBuilderList() { return workerPools_; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ @java.lang.Override public int getWorkerPoolsCount() { return workerPools_.size(); } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ @java.lang.Override public com.google.cloudbuild.v1.WorkerPool getWorkerPools(int index) { return workerPools_.get(index); } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ @java.lang.Override public com.google.cloudbuild.v1.WorkerPoolOrBuilder getWorkerPoolsOrBuilder(int index) { return workerPools_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < workerPools_.size(); i++) { output.writeMessage(1, workerPools_.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 < workerPools_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, workerPools_.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.cloudbuild.v1.ListWorkerPoolsResponse)) { return super.equals(obj); } com.google.cloudbuild.v1.ListWorkerPoolsResponse other = (com.google.cloudbuild.v1.ListWorkerPoolsResponse) obj; if (!getWorkerPoolsList().equals(other.getWorkerPoolsList())) 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 (getWorkerPoolsCount() > 0) { hash = (37 * hash) + WORKER_POOLS_FIELD_NUMBER; hash = (53 * hash) + getWorkerPoolsList().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.cloudbuild.v1.ListWorkerPoolsResponse parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse 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.ListWorkerPoolsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse 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.ListWorkerPoolsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse 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.ListWorkerPoolsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse 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.ListWorkerPoolsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse 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.ListWorkerPoolsResponse 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 containing existing `WorkerPools`. * </pre> * * Protobuf type {@code google.devtools.cloudbuild.v1.ListWorkerPoolsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.devtools.cloudbuild.v1.ListWorkerPoolsResponse) com.google.cloudbuild.v1.ListWorkerPoolsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_ListWorkerPoolsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_ListWorkerPoolsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloudbuild.v1.ListWorkerPoolsResponse.class, com.google.cloudbuild.v1.ListWorkerPoolsResponse.Builder.class); } // Construct using com.google.cloudbuild.v1.ListWorkerPoolsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (workerPoolsBuilder_ == null) { workerPools_ = java.util.Collections.emptyList(); } else { workerPools_ = null; workerPoolsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloudbuild.v1.Cloudbuild .internal_static_google_devtools_cloudbuild_v1_ListWorkerPoolsResponse_descriptor; } @java.lang.Override public com.google.cloudbuild.v1.ListWorkerPoolsResponse getDefaultInstanceForType() { return com.google.cloudbuild.v1.ListWorkerPoolsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloudbuild.v1.ListWorkerPoolsResponse build() { com.google.cloudbuild.v1.ListWorkerPoolsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloudbuild.v1.ListWorkerPoolsResponse buildPartial() { com.google.cloudbuild.v1.ListWorkerPoolsResponse result = new com.google.cloudbuild.v1.ListWorkerPoolsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloudbuild.v1.ListWorkerPoolsResponse result) { if (workerPoolsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { workerPools_ = java.util.Collections.unmodifiableList(workerPools_); bitField0_ = (bitField0_ & ~0x00000001); } result.workerPools_ = workerPools_; } else { result.workerPools_ = workerPoolsBuilder_.build(); } } private void buildPartial0(com.google.cloudbuild.v1.ListWorkerPoolsResponse 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.cloudbuild.v1.ListWorkerPoolsResponse) { return mergeFrom((com.google.cloudbuild.v1.ListWorkerPoolsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloudbuild.v1.ListWorkerPoolsResponse other) { if (other == com.google.cloudbuild.v1.ListWorkerPoolsResponse.getDefaultInstance()) return this; if (workerPoolsBuilder_ == null) { if (!other.workerPools_.isEmpty()) { if (workerPools_.isEmpty()) { workerPools_ = other.workerPools_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureWorkerPoolsIsMutable(); workerPools_.addAll(other.workerPools_); } onChanged(); } } else { if (!other.workerPools_.isEmpty()) { if (workerPoolsBuilder_.isEmpty()) { workerPoolsBuilder_.dispose(); workerPoolsBuilder_ = null; workerPools_ = other.workerPools_; bitField0_ = (bitField0_ & ~0x00000001); workerPoolsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getWorkerPoolsFieldBuilder() : null; } else { workerPoolsBuilder_.addAllMessages(other.workerPools_); } } } 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.cloudbuild.v1.WorkerPool m = input.readMessage( com.google.cloudbuild.v1.WorkerPool.parser(), extensionRegistry); if (workerPoolsBuilder_ == null) { ensureWorkerPoolsIsMutable(); workerPools_.add(m); } else { workerPoolsBuilder_.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.cloudbuild.v1.WorkerPool> workerPools_ = java.util.Collections.emptyList(); private void ensureWorkerPoolsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { workerPools_ = new java.util.ArrayList<com.google.cloudbuild.v1.WorkerPool>(workerPools_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloudbuild.v1.WorkerPool, com.google.cloudbuild.v1.WorkerPool.Builder, com.google.cloudbuild.v1.WorkerPoolOrBuilder> workerPoolsBuilder_; /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public java.util.List<com.google.cloudbuild.v1.WorkerPool> getWorkerPoolsList() { if (workerPoolsBuilder_ == null) { return java.util.Collections.unmodifiableList(workerPools_); } else { return workerPoolsBuilder_.getMessageList(); } } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public int getWorkerPoolsCount() { if (workerPoolsBuilder_ == null) { return workerPools_.size(); } else { return workerPoolsBuilder_.getCount(); } } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public com.google.cloudbuild.v1.WorkerPool getWorkerPools(int index) { if (workerPoolsBuilder_ == null) { return workerPools_.get(index); } else { return workerPoolsBuilder_.getMessage(index); } } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder setWorkerPools(int index, com.google.cloudbuild.v1.WorkerPool value) { if (workerPoolsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWorkerPoolsIsMutable(); workerPools_.set(index, value); onChanged(); } else { workerPoolsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder setWorkerPools( int index, com.google.cloudbuild.v1.WorkerPool.Builder builderForValue) { if (workerPoolsBuilder_ == null) { ensureWorkerPoolsIsMutable(); workerPools_.set(index, builderForValue.build()); onChanged(); } else { workerPoolsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder addWorkerPools(com.google.cloudbuild.v1.WorkerPool value) { if (workerPoolsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWorkerPoolsIsMutable(); workerPools_.add(value); onChanged(); } else { workerPoolsBuilder_.addMessage(value); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder addWorkerPools(int index, com.google.cloudbuild.v1.WorkerPool value) { if (workerPoolsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureWorkerPoolsIsMutable(); workerPools_.add(index, value); onChanged(); } else { workerPoolsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder addWorkerPools(com.google.cloudbuild.v1.WorkerPool.Builder builderForValue) { if (workerPoolsBuilder_ == null) { ensureWorkerPoolsIsMutable(); workerPools_.add(builderForValue.build()); onChanged(); } else { workerPoolsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder addWorkerPools( int index, com.google.cloudbuild.v1.WorkerPool.Builder builderForValue) { if (workerPoolsBuilder_ == null) { ensureWorkerPoolsIsMutable(); workerPools_.add(index, builderForValue.build()); onChanged(); } else { workerPoolsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder addAllWorkerPools( java.lang.Iterable<? extends com.google.cloudbuild.v1.WorkerPool> values) { if (workerPoolsBuilder_ == null) { ensureWorkerPoolsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, workerPools_); onChanged(); } else { workerPoolsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder clearWorkerPools() { if (workerPoolsBuilder_ == null) { workerPools_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { workerPoolsBuilder_.clear(); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public Builder removeWorkerPools(int index) { if (workerPoolsBuilder_ == null) { ensureWorkerPoolsIsMutable(); workerPools_.remove(index); onChanged(); } else { workerPoolsBuilder_.remove(index); } return this; } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public com.google.cloudbuild.v1.WorkerPool.Builder getWorkerPoolsBuilder(int index) { return getWorkerPoolsFieldBuilder().getBuilder(index); } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public com.google.cloudbuild.v1.WorkerPoolOrBuilder getWorkerPoolsOrBuilder(int index) { if (workerPoolsBuilder_ == null) { return workerPools_.get(index); } else { return workerPoolsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public java.util.List<? extends com.google.cloudbuild.v1.WorkerPoolOrBuilder> getWorkerPoolsOrBuilderList() { if (workerPoolsBuilder_ != null) { return workerPoolsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(workerPools_); } } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public com.google.cloudbuild.v1.WorkerPool.Builder addWorkerPoolsBuilder() { return getWorkerPoolsFieldBuilder() .addBuilder(com.google.cloudbuild.v1.WorkerPool.getDefaultInstance()); } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public com.google.cloudbuild.v1.WorkerPool.Builder addWorkerPoolsBuilder(int index) { return getWorkerPoolsFieldBuilder() .addBuilder(index, com.google.cloudbuild.v1.WorkerPool.getDefaultInstance()); } /** * * * <pre> * `WorkerPools` for the specified project. * </pre> * * <code>repeated .google.devtools.cloudbuild.v1.WorkerPool worker_pools = 1;</code> */ public java.util.List<com.google.cloudbuild.v1.WorkerPool.Builder> getWorkerPoolsBuilderList() { return getWorkerPoolsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloudbuild.v1.WorkerPool, com.google.cloudbuild.v1.WorkerPool.Builder, com.google.cloudbuild.v1.WorkerPoolOrBuilder> getWorkerPoolsFieldBuilder() { if (workerPoolsBuilder_ == null) { workerPoolsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloudbuild.v1.WorkerPool, com.google.cloudbuild.v1.WorkerPool.Builder, com.google.cloudbuild.v1.WorkerPoolOrBuilder>( workerPools_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); workerPools_ = null; } return workerPoolsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Continuation token used to page through large result sets. Provide this * value in a subsequent ListWorkerPoolsRequest to return the next page of * results. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.devtools.cloudbuild.v1.ListWorkerPoolsResponse) } // @@protoc_insertion_point(class_scope:google.devtools.cloudbuild.v1.ListWorkerPoolsResponse) private static final com.google.cloudbuild.v1.ListWorkerPoolsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloudbuild.v1.ListWorkerPoolsResponse(); } public static com.google.cloudbuild.v1.ListWorkerPoolsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListWorkerPoolsResponse> PARSER = new com.google.protobuf.AbstractParser<ListWorkerPoolsResponse>() { @java.lang.Override public ListWorkerPoolsResponse 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<ListWorkerPoolsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListWorkerPoolsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloudbuild.v1.ListWorkerPoolsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/kafka
36,870
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/distributed/DistributedConfig.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.connect.runtime.distributed; import org.apache.kafka.clients.CommonClientConfigs; import org.apache.kafka.clients.MetadataRecoveryStrategy; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.config.ConfigDef; import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.common.config.TopicConfig; import org.apache.kafka.common.security.auth.SecurityProtocol; import org.apache.kafka.common.utils.Utils; import org.apache.kafka.connect.runtime.WorkerConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.crypto.KeyGenerator; import static org.apache.kafka.common.config.ConfigDef.CaseInsensitiveValidString.in; import static org.apache.kafka.common.config.ConfigDef.Range.atLeast; import static org.apache.kafka.common.config.ConfigDef.Range.between; import static org.apache.kafka.common.utils.Utils.enumOptions; import static org.apache.kafka.connect.runtime.TopicCreationConfig.PARTITIONS_VALIDATOR; import static org.apache.kafka.connect.runtime.TopicCreationConfig.REPLICATION_FACTOR_VALIDATOR; /** * Provides configuration for Kafka Connect workers running in distributed mode. */ public final class DistributedConfig extends WorkerConfig { private static final Logger log = LoggerFactory.getLogger(DistributedConfig.class); /* * NOTE: DO NOT CHANGE EITHER CONFIG STRINGS OR THEIR JAVA VARIABLE NAMES AS * THESE ARE PART OF THE PUBLIC API AND CHANGE WILL BREAK USER CODE. */ /** * <code>group.id</code> */ public static final String GROUP_ID_CONFIG = CommonClientConfigs.GROUP_ID_CONFIG; private static final String GROUP_ID_DOC = "A unique string that identifies the Connect cluster group this worker belongs to."; /** * <code>session.timeout.ms</code> */ public static final String SESSION_TIMEOUT_MS_CONFIG = CommonClientConfigs.SESSION_TIMEOUT_MS_CONFIG; private static final String SESSION_TIMEOUT_MS_DOC = "The timeout used to detect worker failures. " + "The worker sends periodic heartbeats to indicate its liveness to the broker. If no heartbeats are " + "received by the broker before the expiration of this session timeout, then the broker will remove the " + "worker from the group and initiate a rebalance. Note that the value must be in the allowable range as " + "configured in the broker configuration by <code>group.min.session.timeout.ms</code> " + "and <code>group.max.session.timeout.ms</code>."; /** * <code>heartbeat.interval.ms</code> */ public static final String HEARTBEAT_INTERVAL_MS_CONFIG = CommonClientConfigs.HEARTBEAT_INTERVAL_MS_CONFIG; private static final String HEARTBEAT_INTERVAL_MS_DOC = "The expected time between heartbeats to the group " + "coordinator when using Kafka's group management facilities. Heartbeats are used to ensure that the " + "worker's session stays active and to facilitate rebalancing when new members join or leave the group. " + "The value must be set lower than <code>session.timeout.ms</code>, but typically should be set no higher " + "than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances."; /** * <code>rebalance.timeout.ms</code> */ public static final String REBALANCE_TIMEOUT_MS_CONFIG = CommonClientConfigs.REBALANCE_TIMEOUT_MS_CONFIG; private static final String REBALANCE_TIMEOUT_MS_DOC = CommonClientConfigs.REBALANCE_TIMEOUT_MS_DOC; public static final String METADATA_RECOVERY_STRATEGY_CONFIG = CommonClientConfigs.METADATA_RECOVERY_STRATEGY_CONFIG; private static final String METADATA_RECOVERY_STRATEGY_DOC = CommonClientConfigs.METADATA_RECOVERY_STRATEGY_DOC; public static final String DEFAULT_METADATA_RECOVERY_STRATEGY = CommonClientConfigs.DEFAULT_METADATA_RECOVERY_STRATEGY; public static final String METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_CONFIG = CommonClientConfigs.METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_CONFIG; private static final String METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_DOC = CommonClientConfigs.METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_DOC; public static final long DEFAULT_METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS = CommonClientConfigs.DEFAULT_METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS; /** * <code>worker.sync.timeout.ms</code> */ public static final String WORKER_SYNC_TIMEOUT_MS_CONFIG = "worker.sync.timeout.ms"; private static final String WORKER_SYNC_TIMEOUT_MS_DOC = "When the worker is out of sync with other workers and needs" + " to resynchronize configurations, wait up to this amount of time before giving up, leaving the group, and" + " waiting a backoff period before rejoining."; /** * <code>group.unsync.timeout.ms</code> */ public static final String WORKER_UNSYNC_BACKOFF_MS_CONFIG = "worker.unsync.backoff.ms"; private static final String WORKER_UNSYNC_BACKOFF_MS_DOC = "When the worker is out of sync with other workers and " + " fails to catch up within the <code>worker.sync.timeout.ms</code>, leave the Connect cluster for this long before rejoining."; public static final int WORKER_UNSYNC_BACKOFF_MS_DEFAULT = 5 * 60 * 1000; public static final String CONFIG_STORAGE_PREFIX = "config.storage."; public static final String OFFSET_STORAGE_PREFIX = "offset.storage."; public static final String STATUS_STORAGE_PREFIX = "status.storage."; public static final String TOPIC_SUFFIX = "topic"; public static final String PARTITIONS_SUFFIX = "partitions"; public static final String REPLICATION_FACTOR_SUFFIX = "replication.factor"; /** * <code>offset.storage.topic</code> */ public static final String OFFSET_STORAGE_TOPIC_CONFIG = OFFSET_STORAGE_PREFIX + TOPIC_SUFFIX; private static final String OFFSET_STORAGE_TOPIC_CONFIG_DOC = "The name of the Kafka topic where source connector offsets are stored"; /** * <code>offset.storage.partitions</code> */ public static final String OFFSET_STORAGE_PARTITIONS_CONFIG = OFFSET_STORAGE_PREFIX + PARTITIONS_SUFFIX; private static final String OFFSET_STORAGE_PARTITIONS_CONFIG_DOC = "The number of partitions used when creating the offset storage topic"; /** * <code>offset.storage.replication.factor</code> */ public static final String OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG = OFFSET_STORAGE_PREFIX + REPLICATION_FACTOR_SUFFIX; private static final String OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG_DOC = "Replication factor used when creating the offset storage topic"; /** * <code>config.storage.topic</code> */ public static final String CONFIG_TOPIC_CONFIG = CONFIG_STORAGE_PREFIX + TOPIC_SUFFIX; private static final String CONFIG_TOPIC_CONFIG_DOC = "The name of the Kafka topic where connector configurations are stored"; /** * <code>config.storage.replication.factor</code> */ public static final String CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG = CONFIG_STORAGE_PREFIX + REPLICATION_FACTOR_SUFFIX; private static final String CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG_DOC = "Replication factor used when creating the configuration storage topic"; /** * <code>status.storage.topic</code> */ public static final String STATUS_STORAGE_TOPIC_CONFIG = STATUS_STORAGE_PREFIX + TOPIC_SUFFIX; public static final String STATUS_STORAGE_TOPIC_CONFIG_DOC = "The name of the Kafka topic where connector and task status are stored"; /** * <code>status.storage.partitions</code> */ public static final String STATUS_STORAGE_PARTITIONS_CONFIG = STATUS_STORAGE_PREFIX + PARTITIONS_SUFFIX; private static final String STATUS_STORAGE_PARTITIONS_CONFIG_DOC = "The number of partitions used when creating the status storage topic"; /** * <code>status.storage.replication.factor</code> */ public static final String STATUS_STORAGE_REPLICATION_FACTOR_CONFIG = STATUS_STORAGE_PREFIX + REPLICATION_FACTOR_SUFFIX; private static final String STATUS_STORAGE_REPLICATION_FACTOR_CONFIG_DOC = "Replication factor used when creating the status storage topic"; /** * <code>connect.protocol</code> */ public static final String CONNECT_PROTOCOL_CONFIG = "connect.protocol"; public static final String CONNECT_PROTOCOL_DOC = "Compatibility mode for Kafka Connect Protocol"; public static final String CONNECT_PROTOCOL_DEFAULT = ConnectProtocolCompatibility.SESSIONED.toString(); /** * <code>scheduled.rebalance.max.delay.ms</code> */ public static final String SCHEDULED_REBALANCE_MAX_DELAY_MS_CONFIG = "scheduled.rebalance.max.delay.ms"; public static final String SCHEDULED_REBALANCE_MAX_DELAY_MS_DOC = "The maximum delay that is " + "scheduled in order to wait for the return of one or more departed workers before " + "rebalancing and reassigning their connectors and tasks to the group. During this " + "period the connectors and tasks of the departed workers remain unassigned"; public static final int SCHEDULED_REBALANCE_MAX_DELAY_MS_DEFAULT = Math.toIntExact(TimeUnit.SECONDS.toMillis(300)); public static final String INTER_WORKER_KEY_GENERATION_ALGORITHM_CONFIG = "inter.worker.key.generation.algorithm"; public static final String INTER_WORKER_KEY_GENERATION_ALGORITHM_DEFAULT = "HmacSHA256"; public static final String INTER_WORKER_KEY_GENERATION_ALGORITHM_DOC = "The algorithm to use for generating internal request keys. " + "The algorithm '" + INTER_WORKER_KEY_GENERATION_ALGORITHM_DEFAULT + "' will be used as a default on JVMs that support it; " + "on other JVMs, no default is used and a value for this property must be manually specified in the worker config."; public static final String INTER_WORKER_KEY_SIZE_CONFIG = "inter.worker.key.size"; public static final String INTER_WORKER_KEY_SIZE_DOC = "The size of the key to use for signing internal requests, in bits. " + "If null, the default key size for the key generation algorithm will be used."; public static final Long INTER_WORKER_KEY_SIZE_DEFAULT = null; public static final String INTER_WORKER_KEY_TTL_MS_CONFIG = "inter.worker.key.ttl.ms"; public static final String INTER_WORKER_KEY_TTL_MS_DOC = "The TTL of generated session keys used for " + "internal request validation (in milliseconds)"; public static final int INTER_WORKER_KEY_TTL_MS_DEFAULT = Math.toIntExact(TimeUnit.HOURS.toMillis(1)); public static final String INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG = "inter.worker.signature.algorithm"; public static final String INTER_WORKER_SIGNATURE_ALGORITHM_DEFAULT = "HmacSHA256"; public static final String INTER_WORKER_SIGNATURE_ALGORITHM_DOC = "The algorithm used to sign internal requests. " + "The algorithm '" + INTER_WORKER_SIGNATURE_ALGORITHM_DEFAULT + "' will be used as a default on JVMs that support it; " + "on other JVMs, no default is used and a value for this property must be manually specified in the worker config."; public static final String INTER_WORKER_VERIFICATION_ALGORITHMS_CONFIG = "inter.worker.verification.algorithms"; public static final List<String> INTER_WORKER_VERIFICATION_ALGORITHMS_DEFAULT = List.of(INTER_WORKER_SIGNATURE_ALGORITHM_DEFAULT); public static final String INTER_WORKER_VERIFICATION_ALGORITHMS_DOC = "A list of permitted algorithms for verifying internal requests, " + "which must include the algorithm used for the <code>" + INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG + "</code> property. " + "The algorithm(s) '" + INTER_WORKER_VERIFICATION_ALGORITHMS_DEFAULT + "' will be used as a default on JVMs that provide them; " + "on other JVMs, no default is used and a value for this property must be manually specified in the worker config."; private final Crypto crypto; public enum ExactlyOnceSourceSupport { DISABLED(false), PREPARING(true), ENABLED(true); public final boolean usesTransactionalLeader; ExactlyOnceSourceSupport(boolean usesTransactionalLeader) { this.usesTransactionalLeader = usesTransactionalLeader; } public static ExactlyOnceSourceSupport fromProperty(String property) { return ExactlyOnceSourceSupport.valueOf(property.toUpperCase(Locale.ROOT)); } @Override public String toString() { return name().toLowerCase(Locale.ROOT); } } public static final String EXACTLY_ONCE_SOURCE_SUPPORT_CONFIG = "exactly.once.source.support"; public static final String EXACTLY_ONCE_SOURCE_SUPPORT_DOC = "Whether to enable exactly-once support for source connectors in the cluster " + "by using transactions to write source records and their source offsets, and by proactively fencing out old task generations before bringing up new ones.\n" + "To enable exactly-once source support on a new cluster, set this property to '" + ExactlyOnceSourceSupport.ENABLED + "'. " + "To enable support on an existing cluster, first set to '" + ExactlyOnceSourceSupport.PREPARING + "' on every worker in the cluster, " + "then set to '" + ExactlyOnceSourceSupport.ENABLED + "'. A rolling upgrade may be used for both changes. " + "For more information on this feature, see the " + "<a href=\"https://kafka.apache.org/documentation.html#connect_exactlyoncesource\">exactly-once source support documentation</a>."; public static final String EXACTLY_ONCE_SOURCE_SUPPORT_DEFAULT = ExactlyOnceSourceSupport.DISABLED.toString(); private static Object defaultKeyGenerationAlgorithm(Crypto crypto) { try { validateKeyAlgorithm(crypto, INTER_WORKER_KEY_GENERATION_ALGORITHM_CONFIG, INTER_WORKER_KEY_GENERATION_ALGORITHM_DEFAULT); return INTER_WORKER_KEY_GENERATION_ALGORITHM_DEFAULT; } catch (Throwable t) { log.info( "The default key generation algorithm '{}' does not appear to be available on this worker." + "A key algorithm will have to be manually specified via the '{}' worker property", INTER_WORKER_KEY_GENERATION_ALGORITHM_DEFAULT, INTER_WORKER_KEY_GENERATION_ALGORITHM_CONFIG ); return ConfigDef.NO_DEFAULT_VALUE; } } private static Object defaultSignatureAlgorithm(Crypto crypto) { try { validateSignatureAlgorithm(crypto, INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG, INTER_WORKER_SIGNATURE_ALGORITHM_DEFAULT); return INTER_WORKER_SIGNATURE_ALGORITHM_DEFAULT; } catch (Throwable t) { log.info( "The default signature algorithm '{}' does not appear to be available on this worker." + "A signature algorithm will have to be manually specified via the '{}' worker property", INTER_WORKER_SIGNATURE_ALGORITHM_DEFAULT, INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG ); return ConfigDef.NO_DEFAULT_VALUE; } } private static Object defaultVerificationAlgorithms(Crypto crypto) { List<String> result = new ArrayList<>(); for (String verificationAlgorithm : INTER_WORKER_VERIFICATION_ALGORITHMS_DEFAULT) { try { validateSignatureAlgorithm(crypto, INTER_WORKER_VERIFICATION_ALGORITHMS_CONFIG, verificationAlgorithm); result.add(verificationAlgorithm); } catch (Throwable t) { log.trace("Verification algorithm '{}' not found", verificationAlgorithm); } } if (result.isEmpty()) { log.info( "The default verification algorithm '{}' does not appear to be available on this worker." + "One or more verification algorithms will have to be manually specified via the '{}' worker property", INTER_WORKER_VERIFICATION_ALGORITHMS_DEFAULT, INTER_WORKER_VERIFICATION_ALGORITHMS_CONFIG ); return ConfigDef.NO_DEFAULT_VALUE; } return result; } @SuppressWarnings("unchecked") private static ConfigDef config(Crypto crypto) { return baseConfigDef() .define(GROUP_ID_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, GROUP_ID_DOC) .define(SESSION_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, Math.toIntExact(TimeUnit.SECONDS.toMillis(10)), ConfigDef.Importance.HIGH, SESSION_TIMEOUT_MS_DOC) .define(REBALANCE_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, Math.toIntExact(TimeUnit.MINUTES.toMillis(1)), ConfigDef.Importance.HIGH, REBALANCE_TIMEOUT_MS_DOC) .define(HEARTBEAT_INTERVAL_MS_CONFIG, ConfigDef.Type.INT, Math.toIntExact(TimeUnit.SECONDS.toMillis(3)), ConfigDef.Importance.HIGH, HEARTBEAT_INTERVAL_MS_DOC) .define(EXACTLY_ONCE_SOURCE_SUPPORT_CONFIG, ConfigDef.Type.STRING, EXACTLY_ONCE_SOURCE_SUPPORT_DEFAULT, in(enumOptions(ExactlyOnceSourceSupport.class)), ConfigDef.Importance.HIGH, EXACTLY_ONCE_SOURCE_SUPPORT_DOC) .define(CommonClientConfigs.METADATA_MAX_AGE_CONFIG, ConfigDef.Type.LONG, TimeUnit.MINUTES.toMillis(5), atLeast(0), ConfigDef.Importance.LOW, CommonClientConfigs.METADATA_MAX_AGE_DOC) .define(CommonClientConfigs.CLIENT_ID_CONFIG, ConfigDef.Type.STRING, "", ConfigDef.Importance.LOW, CommonClientConfigs.CLIENT_ID_DOC) .define(CommonClientConfigs.SEND_BUFFER_CONFIG, ConfigDef.Type.INT, 128 * 1024, atLeast(CommonClientConfigs.SEND_BUFFER_LOWER_BOUND), ConfigDef.Importance.MEDIUM, CommonClientConfigs.SEND_BUFFER_DOC) .define(CommonClientConfigs.RECEIVE_BUFFER_CONFIG, ConfigDef.Type.INT, 32 * 1024, atLeast(CommonClientConfigs.RECEIVE_BUFFER_LOWER_BOUND), ConfigDef.Importance.MEDIUM, CommonClientConfigs.RECEIVE_BUFFER_DOC) .define(CommonClientConfigs.RECONNECT_BACKOFF_MS_CONFIG, ConfigDef.Type.LONG, 50L, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.RECONNECT_BACKOFF_MS_DOC) .define(CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_CONFIG, ConfigDef.Type.LONG, TimeUnit.SECONDS.toMillis(1), atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.RECONNECT_BACKOFF_MAX_MS_DOC) .define(CommonClientConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG, ConfigDef.Type.LONG, CommonClientConfigs.DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MS, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MS_DOC) .define(CommonClientConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG, ConfigDef.Type.LONG, CommonClientConfigs.DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_DOC) .define(CommonClientConfigs.RETRY_BACKOFF_MS_CONFIG, ConfigDef.Type.LONG, CommonClientConfigs.DEFAULT_RETRY_BACKOFF_MS, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.RETRY_BACKOFF_MS_DOC) .define(CommonClientConfigs.RETRY_BACKOFF_MAX_MS_CONFIG, ConfigDef.Type.LONG, CommonClientConfigs.DEFAULT_RETRY_BACKOFF_MAX_MS, atLeast(0L), ConfigDef.Importance.LOW, CommonClientConfigs.RETRY_BACKOFF_MAX_MS_DOC) .define(CommonClientConfigs.REQUEST_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, Math.toIntExact(TimeUnit.SECONDS.toMillis(40)), atLeast(0), ConfigDef.Importance.MEDIUM, CommonClientConfigs.REQUEST_TIMEOUT_MS_DOC) /* default is set to be a bit lower than the server default (10 min), to avoid both client and server closing connection at same time */ .define(CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_CONFIG, ConfigDef.Type.LONG, TimeUnit.MINUTES.toMillis(9), ConfigDef.Importance.MEDIUM, CommonClientConfigs.CONNECTIONS_MAX_IDLE_MS_DOC) // security support .define(CommonClientConfigs.SECURITY_PROTOCOL_CONFIG, ConfigDef.Type.STRING, CommonClientConfigs.DEFAULT_SECURITY_PROTOCOL, in(Utils.enumOptions(SecurityProtocol.class)), ConfigDef.Importance.MEDIUM, CommonClientConfigs.SECURITY_PROTOCOL_DOC) .withClientSaslSupport() .define(WORKER_SYNC_TIMEOUT_MS_CONFIG, ConfigDef.Type.INT, 3000, ConfigDef.Importance.MEDIUM, WORKER_SYNC_TIMEOUT_MS_DOC) .define(WORKER_UNSYNC_BACKOFF_MS_CONFIG, ConfigDef.Type.INT, WORKER_UNSYNC_BACKOFF_MS_DEFAULT, ConfigDef.Importance.MEDIUM, WORKER_UNSYNC_BACKOFF_MS_DOC) .define(OFFSET_STORAGE_TOPIC_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, OFFSET_STORAGE_TOPIC_CONFIG_DOC) .define(OFFSET_STORAGE_PARTITIONS_CONFIG, ConfigDef.Type.INT, 25, PARTITIONS_VALIDATOR, ConfigDef.Importance.LOW, OFFSET_STORAGE_PARTITIONS_CONFIG_DOC) .define(OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG, ConfigDef.Type.SHORT, (short) 3, REPLICATION_FACTOR_VALIDATOR, ConfigDef.Importance.LOW, OFFSET_STORAGE_REPLICATION_FACTOR_CONFIG_DOC) .define(CONFIG_TOPIC_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, CONFIG_TOPIC_CONFIG_DOC) .define(CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG, ConfigDef.Type.SHORT, (short) 3, REPLICATION_FACTOR_VALIDATOR, ConfigDef.Importance.LOW, CONFIG_STORAGE_REPLICATION_FACTOR_CONFIG_DOC) .define(STATUS_STORAGE_TOPIC_CONFIG, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, STATUS_STORAGE_TOPIC_CONFIG_DOC) .define(STATUS_STORAGE_PARTITIONS_CONFIG, ConfigDef.Type.INT, 5, PARTITIONS_VALIDATOR, ConfigDef.Importance.LOW, STATUS_STORAGE_PARTITIONS_CONFIG_DOC) .define(STATUS_STORAGE_REPLICATION_FACTOR_CONFIG, ConfigDef.Type.SHORT, (short) 3, REPLICATION_FACTOR_VALIDATOR, ConfigDef.Importance.LOW, STATUS_STORAGE_REPLICATION_FACTOR_CONFIG_DOC) .define(CONNECT_PROTOCOL_CONFIG, ConfigDef.Type.STRING, CONNECT_PROTOCOL_DEFAULT, ConfigDef.LambdaValidator.with( (name, value) -> { try { ConnectProtocolCompatibility.compatibility((String) value); } catch (Throwable t) { throw new ConfigException(name, value, "Invalid Connect protocol " + "compatibility"); } }, () -> Arrays.stream(ConnectProtocolCompatibility.values()).map(ConnectProtocolCompatibility::toString) .collect(Collectors.joining(", ", "[", "]"))), ConfigDef.Importance.LOW, CONNECT_PROTOCOL_DOC) .define(SCHEDULED_REBALANCE_MAX_DELAY_MS_CONFIG, ConfigDef.Type.INT, SCHEDULED_REBALANCE_MAX_DELAY_MS_DEFAULT, between(0, Integer.MAX_VALUE), ConfigDef.Importance.LOW, SCHEDULED_REBALANCE_MAX_DELAY_MS_DOC) .define(INTER_WORKER_KEY_TTL_MS_CONFIG, ConfigDef.Type.INT, INTER_WORKER_KEY_TTL_MS_DEFAULT, between(0, Integer.MAX_VALUE), ConfigDef.Importance.LOW, INTER_WORKER_KEY_TTL_MS_DOC) .define(INTER_WORKER_KEY_GENERATION_ALGORITHM_CONFIG, ConfigDef.Type.STRING, defaultKeyGenerationAlgorithm(crypto), ConfigDef.LambdaValidator.with( (name, value) -> validateKeyAlgorithm(crypto, name, (String) value), () -> "Any KeyGenerator algorithm supported by the worker JVM"), ConfigDef.Importance.LOW, INTER_WORKER_KEY_GENERATION_ALGORITHM_DOC) .define(INTER_WORKER_KEY_SIZE_CONFIG, ConfigDef.Type.INT, INTER_WORKER_KEY_SIZE_DEFAULT, ConfigDef.Importance.LOW, INTER_WORKER_KEY_SIZE_DOC) .define(INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG, ConfigDef.Type.STRING, defaultSignatureAlgorithm(crypto), ConfigDef.LambdaValidator.with( (name, value) -> validateSignatureAlgorithm(crypto, name, (String) value), () -> "Any MAC algorithm supported by the worker JVM"), ConfigDef.Importance.LOW, INTER_WORKER_SIGNATURE_ALGORITHM_DOC) .define(INTER_WORKER_VERIFICATION_ALGORITHMS_CONFIG, ConfigDef.Type.LIST, defaultVerificationAlgorithms(crypto), ConfigDef.LambdaValidator.with( (name, value) -> validateVerificationAlgorithms(crypto, name, (List<String>) value), () -> "A list of one or more MAC algorithms, each supported by the worker JVM"), ConfigDef.Importance.LOW, INTER_WORKER_VERIFICATION_ALGORITHMS_DOC) .define(METADATA_RECOVERY_STRATEGY_CONFIG, ConfigDef.Type.STRING, DEFAULT_METADATA_RECOVERY_STRATEGY, ConfigDef.CaseInsensitiveValidString .in(Utils.enumOptions(MetadataRecoveryStrategy.class)), ConfigDef.Importance.LOW, METADATA_RECOVERY_STRATEGY_DOC) .define(METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_CONFIG, ConfigDef.Type.LONG, DEFAULT_METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS, atLeast(0), ConfigDef.Importance.LOW, METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_DOC); } private final ExactlyOnceSourceSupport exactlyOnceSourceSupport; @Override public Integer rebalanceTimeout() { return getInt(DistributedConfig.REBALANCE_TIMEOUT_MS_CONFIG); } @Override public boolean exactlyOnceSourceEnabled() { return exactlyOnceSourceSupport == ExactlyOnceSourceSupport.ENABLED; } /** * @return whether the Connect cluster's leader should use a transactional producer to perform writes to the config * topic, which is useful for ensuring that zombie leaders are fenced out and unable to write to the topic after a * new leader has been elected. */ public boolean transactionalLeaderEnabled() { return exactlyOnceSourceSupport.usesTransactionalLeader; } /** * @return the {@link ProducerConfig#TRANSACTIONAL_ID_CONFIG transactional ID} to use for the worker's producer if * using a transactional producer for writes to internal topics such as the config topic. */ public String transactionalProducerId() { return transactionalProducerId(groupId()); } public static String transactionalProducerId(String groupId) { return "connect-cluster-" + groupId; } @Override public String offsetsTopic() { return getString(OFFSET_STORAGE_TOPIC_CONFIG); } @Override public boolean connectorOffsetsTopicsPermitted() { return true; } @Override public String groupId() { return getString(GROUP_ID_CONFIG); } @Override protected Map<String, Object> postProcessParsedConfig(final Map<String, Object> parsedValues) { CommonClientConfigs.warnDisablingExponentialBackoff(this); return super.postProcessParsedConfig(parsedValues); } public DistributedConfig(Map<String, String> props) { this(Crypto.SYSTEM, props); } // Visible for testing DistributedConfig(Crypto crypto, Map<String, String> props) { super(config(crypto), props); this.crypto = crypto; exactlyOnceSourceSupport = ExactlyOnceSourceSupport.fromProperty(getString(EXACTLY_ONCE_SOURCE_SUPPORT_CONFIG)); validateInterWorkerKeyConfigs(); } public static void main(String[] args) { System.out.println(config(Crypto.SYSTEM).toHtml(4, config -> "connectconfigs_" + config)); } public KeyGenerator getInternalRequestKeyGenerator() { try { KeyGenerator result = crypto.keyGenerator(getString(INTER_WORKER_KEY_GENERATION_ALGORITHM_CONFIG)); Optional.ofNullable(getInt(INTER_WORKER_KEY_SIZE_CONFIG)).ifPresent(result::init); return result; } catch (NoSuchAlgorithmException | InvalidParameterException e) { throw new ConfigException(String.format( "Unable to create key generator with algorithm %s and key size %d: %s", getString(INTER_WORKER_KEY_GENERATION_ALGORITHM_CONFIG), getInt(INTER_WORKER_KEY_SIZE_CONFIG), e.getMessage() )); } } private Map<String, Object> topicSettings(String prefix) { Map<String, Object> result = originalsWithPrefix(prefix); if (CONFIG_STORAGE_PREFIX.equals(prefix) && result.containsKey(PARTITIONS_SUFFIX)) { log.warn("Ignoring '{}{}={}' setting, since config topic partitions is always 1", prefix, PARTITIONS_SUFFIX, result.get("partitions")); } Object removedPolicy = result.remove(TopicConfig.CLEANUP_POLICY_CONFIG); if (removedPolicy != null) { log.warn("Ignoring '{}cleanup.policy={}' setting, since compaction is always used", prefix, removedPolicy); } result.remove(TOPIC_SUFFIX); result.remove(REPLICATION_FACTOR_SUFFIX); result.remove(PARTITIONS_SUFFIX); return result; } public Map<String, Object> configStorageTopicSettings() { return topicSettings(CONFIG_STORAGE_PREFIX); } public Map<String, Object> offsetStorageTopicSettings() { return topicSettings(OFFSET_STORAGE_PREFIX); } public Map<String, Object> statusStorageTopicSettings() { return topicSettings(STATUS_STORAGE_PREFIX); } private void validateInterWorkerKeyConfigs() { getInternalRequestKeyGenerator(); ensureVerificationAlgorithmsIncludeSignatureAlgorithm(); } private void ensureVerificationAlgorithmsIncludeSignatureAlgorithm() { String signatureAlgorithm = getString(INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG); List<String> verificationAlgorithms = getList(INTER_WORKER_VERIFICATION_ALGORITHMS_CONFIG); if (!verificationAlgorithms.contains(signatureAlgorithm)) { throw new ConfigException( INTER_WORKER_SIGNATURE_ALGORITHM_CONFIG, signatureAlgorithm, String.format("Signature algorithm must be present in %s list", INTER_WORKER_VERIFICATION_ALGORITHMS_CONFIG) ); } } private static void validateVerificationAlgorithms(Crypto crypto, String configName, List<String> algorithms) { if (algorithms.isEmpty()) { throw new ConfigException( configName, algorithms, "At least one signature verification algorithm must be provided" ); } for (String algorithm : algorithms) { try { crypto.mac(algorithm); } catch (NoSuchAlgorithmException e) { throw unsupportedAlgorithmException(configName, algorithm, "Mac"); } } } private static void validateSignatureAlgorithm(Crypto crypto, String configName, String algorithm) { try { crypto.mac(algorithm); } catch (NoSuchAlgorithmException e) { throw unsupportedAlgorithmException(configName, algorithm, "Mac"); } } private static void validateKeyAlgorithm(Crypto crypto, String configName, String algorithm) { try { crypto.keyGenerator(algorithm); } catch (NoSuchAlgorithmException e) { throw unsupportedAlgorithmException(configName, algorithm, "KeyGenerator"); } } private static ConfigException unsupportedAlgorithmException(String name, Object value, String type) { return new ConfigException( name, value, "the algorithm is not supported by this JVM; the supported algorithms are: " + supportedAlgorithms(type) ); } // Visible for testing static Set<String> supportedAlgorithms(String type) { Set<String> result = new HashSet<>(); for (Provider provider : Security.getProviders()) { for (Provider.Service service : provider.getServices()) { if (type.equals(service.getType())) { result.add(service.getAlgorithm()); } } } return result; } }
googleapis/google-cloud-java
36,487
java-run/proto-google-cloud-run-v2/src/main/java/com/google/cloud/run/v2/EnvVar.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/run/v2/k8s.min.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.run.v2; /** * * * <pre> * EnvVar represents an environment variable present in a Container. * </pre> * * Protobuf type {@code google.cloud.run.v2.EnvVar} */ public final class EnvVar extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.run.v2.EnvVar) EnvVarOrBuilder { private static final long serialVersionUID = 0L; // Use EnvVar.newBuilder() to construct. private EnvVar(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private EnvVar() { name_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new EnvVar(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.run.v2.K8sMinProto .internal_static_google_cloud_run_v2_EnvVar_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.run.v2.K8sMinProto .internal_static_google_cloud_run_v2_EnvVar_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.run.v2.EnvVar.class, com.google.cloud.run.v2.EnvVar.Builder.class); } private int valuesCase_ = 0; @SuppressWarnings("serial") private java.lang.Object values_; public enum ValuesCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { VALUE(2), VALUE_SOURCE(3), VALUES_NOT_SET(0); private final int value; private ValuesCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ValuesCase valueOf(int value) { return forNumber(value); } public static ValuesCase forNumber(int value) { switch (value) { case 2: return VALUE; case 3: return VALUE_SOURCE; case 0: return VALUES_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ValuesCase getValuesCase() { return ValuesCase.forNumber(valuesCase_); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALUE_FIELD_NUMBER = 2; /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return Whether the value field is set. */ public boolean hasValue() { return valuesCase_ == 2; } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return The value. */ public java.lang.String getValue() { java.lang.Object ref = ""; if (valuesCase_ == 2) { ref = values_; } if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (valuesCase_ == 2) { values_ = s; } return s; } } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return The bytes for value. */ public com.google.protobuf.ByteString getValueBytes() { java.lang.Object ref = ""; if (valuesCase_ == 2) { ref = values_; } if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (valuesCase_ == 2) { values_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALUE_SOURCE_FIELD_NUMBER = 3; /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> * * @return Whether the valueSource field is set. */ @java.lang.Override public boolean hasValueSource() { return valuesCase_ == 3; } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> * * @return The valueSource. */ @java.lang.Override public com.google.cloud.run.v2.EnvVarSource getValueSource() { if (valuesCase_ == 3) { return (com.google.cloud.run.v2.EnvVarSource) values_; } return com.google.cloud.run.v2.EnvVarSource.getDefaultInstance(); } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ @java.lang.Override public com.google.cloud.run.v2.EnvVarSourceOrBuilder getValueSourceOrBuilder() { if (valuesCase_ == 3) { return (com.google.cloud.run.v2.EnvVarSource) values_; } return com.google.cloud.run.v2.EnvVarSource.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (valuesCase_ == 2) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, values_); } if (valuesCase_ == 3) { output.writeMessage(3, (com.google.cloud.run.v2.EnvVarSource) values_); } 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 (valuesCase_ == 2) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, values_); } if (valuesCase_ == 3) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 3, (com.google.cloud.run.v2.EnvVarSource) values_); } 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.run.v2.EnvVar)) { return super.equals(obj); } com.google.cloud.run.v2.EnvVar other = (com.google.cloud.run.v2.EnvVar) obj; if (!getName().equals(other.getName())) return false; if (!getValuesCase().equals(other.getValuesCase())) return false; switch (valuesCase_) { case 2: if (!getValue().equals(other.getValue())) return false; break; case 3: if (!getValueSource().equals(other.getValueSource())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); switch (valuesCase_) { case 2: hash = (37 * hash) + VALUE_FIELD_NUMBER; hash = (53 * hash) + getValue().hashCode(); break; case 3: hash = (37 * hash) + VALUE_SOURCE_FIELD_NUMBER; hash = (53 * hash) + getValueSource().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.run.v2.EnvVar parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.run.v2.EnvVar 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.run.v2.EnvVar parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.run.v2.EnvVar 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.run.v2.EnvVar parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.run.v2.EnvVar parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.run.v2.EnvVar parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.run.v2.EnvVar 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.run.v2.EnvVar parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.run.v2.EnvVar 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.run.v2.EnvVar parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.run.v2.EnvVar 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.run.v2.EnvVar 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> * EnvVar represents an environment variable present in a Container. * </pre> * * Protobuf type {@code google.cloud.run.v2.EnvVar} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.run.v2.EnvVar) com.google.cloud.run.v2.EnvVarOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.run.v2.K8sMinProto .internal_static_google_cloud_run_v2_EnvVar_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.run.v2.K8sMinProto .internal_static_google_cloud_run_v2_EnvVar_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.run.v2.EnvVar.class, com.google.cloud.run.v2.EnvVar.Builder.class); } // Construct using com.google.cloud.run.v2.EnvVar.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; if (valueSourceBuilder_ != null) { valueSourceBuilder_.clear(); } valuesCase_ = 0; values_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.run.v2.K8sMinProto .internal_static_google_cloud_run_v2_EnvVar_descriptor; } @java.lang.Override public com.google.cloud.run.v2.EnvVar getDefaultInstanceForType() { return com.google.cloud.run.v2.EnvVar.getDefaultInstance(); } @java.lang.Override public com.google.cloud.run.v2.EnvVar build() { com.google.cloud.run.v2.EnvVar result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.run.v2.EnvVar buildPartial() { com.google.cloud.run.v2.EnvVar result = new com.google.cloud.run.v2.EnvVar(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.cloud.run.v2.EnvVar result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } } private void buildPartialOneofs(com.google.cloud.run.v2.EnvVar result) { result.valuesCase_ = valuesCase_; result.values_ = this.values_; if (valuesCase_ == 3 && valueSourceBuilder_ != null) { result.values_ = valueSourceBuilder_.build(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.run.v2.EnvVar) { return mergeFrom((com.google.cloud.run.v2.EnvVar) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.run.v2.EnvVar other) { if (other == com.google.cloud.run.v2.EnvVar.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } switch (other.getValuesCase()) { case VALUE: { valuesCase_ = 2; values_ = other.values_; onChanged(); break; } case VALUE_SOURCE: { mergeValueSource(other.getValueSource()); break; } case VALUES_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { java.lang.String s = input.readStringRequireUtf8(); valuesCase_ = 2; values_ = s; break; } // case 18 case 26: { input.readMessage(getValueSourceFieldBuilder().getBuilder(), extensionRegistry); valuesCase_ = 3; 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 valuesCase_ = 0; private java.lang.Object values_; public ValuesCase getValuesCase() { return ValuesCase.forNumber(valuesCase_); } public Builder clearValues() { valuesCase_ = 0; values_ = null; onChanged(); return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The name to set. * @return This builder for chaining. */ public Builder setName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. Name of the environment variable. Must not exceed 32768 * characters. * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return Whether the value field is set. */ @java.lang.Override public boolean hasValue() { return valuesCase_ == 2; } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return The value. */ @java.lang.Override public java.lang.String getValue() { java.lang.Object ref = ""; if (valuesCase_ == 2) { ref = values_; } if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (valuesCase_ == 2) { values_ = s; } return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return The bytes for value. */ @java.lang.Override public com.google.protobuf.ByteString getValueBytes() { java.lang.Object ref = ""; if (valuesCase_ == 2) { ref = values_; } if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); if (valuesCase_ == 2) { values_ = b; } return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @param value The value to set. * @return This builder for chaining. */ public Builder setValue(java.lang.String value) { if (value == null) { throw new NullPointerException(); } valuesCase_ = 2; values_ = value; onChanged(); return this; } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @return This builder for chaining. */ public Builder clearValue() { if (valuesCase_ == 2) { valuesCase_ = 0; values_ = null; onChanged(); } return this; } /** * * * <pre> * Literal value of the environment variable. * Defaults to "", and the maximum length is 32768 bytes. * Variable references are not supported in Cloud Run. * </pre> * * <code>string value = 2;</code> * * @param value The bytes for value to set. * @return This builder for chaining. */ public Builder setValueBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); valuesCase_ = 2; values_ = value; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.run.v2.EnvVarSource, com.google.cloud.run.v2.EnvVarSource.Builder, com.google.cloud.run.v2.EnvVarSourceOrBuilder> valueSourceBuilder_; /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> * * @return Whether the valueSource field is set. */ @java.lang.Override public boolean hasValueSource() { return valuesCase_ == 3; } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> * * @return The valueSource. */ @java.lang.Override public com.google.cloud.run.v2.EnvVarSource getValueSource() { if (valueSourceBuilder_ == null) { if (valuesCase_ == 3) { return (com.google.cloud.run.v2.EnvVarSource) values_; } return com.google.cloud.run.v2.EnvVarSource.getDefaultInstance(); } else { if (valuesCase_ == 3) { return valueSourceBuilder_.getMessage(); } return com.google.cloud.run.v2.EnvVarSource.getDefaultInstance(); } } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ public Builder setValueSource(com.google.cloud.run.v2.EnvVarSource value) { if (valueSourceBuilder_ == null) { if (value == null) { throw new NullPointerException(); } values_ = value; onChanged(); } else { valueSourceBuilder_.setMessage(value); } valuesCase_ = 3; return this; } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ public Builder setValueSource(com.google.cloud.run.v2.EnvVarSource.Builder builderForValue) { if (valueSourceBuilder_ == null) { values_ = builderForValue.build(); onChanged(); } else { valueSourceBuilder_.setMessage(builderForValue.build()); } valuesCase_ = 3; return this; } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ public Builder mergeValueSource(com.google.cloud.run.v2.EnvVarSource value) { if (valueSourceBuilder_ == null) { if (valuesCase_ == 3 && values_ != com.google.cloud.run.v2.EnvVarSource.getDefaultInstance()) { values_ = com.google.cloud.run.v2.EnvVarSource.newBuilder( (com.google.cloud.run.v2.EnvVarSource) values_) .mergeFrom(value) .buildPartial(); } else { values_ = value; } onChanged(); } else { if (valuesCase_ == 3) { valueSourceBuilder_.mergeFrom(value); } else { valueSourceBuilder_.setMessage(value); } } valuesCase_ = 3; return this; } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ public Builder clearValueSource() { if (valueSourceBuilder_ == null) { if (valuesCase_ == 3) { valuesCase_ = 0; values_ = null; onChanged(); } } else { if (valuesCase_ == 3) { valuesCase_ = 0; values_ = null; } valueSourceBuilder_.clear(); } return this; } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ public com.google.cloud.run.v2.EnvVarSource.Builder getValueSourceBuilder() { return getValueSourceFieldBuilder().getBuilder(); } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ @java.lang.Override public com.google.cloud.run.v2.EnvVarSourceOrBuilder getValueSourceOrBuilder() { if ((valuesCase_ == 3) && (valueSourceBuilder_ != null)) { return valueSourceBuilder_.getMessageOrBuilder(); } else { if (valuesCase_ == 3) { return (com.google.cloud.run.v2.EnvVarSource) values_; } return com.google.cloud.run.v2.EnvVarSource.getDefaultInstance(); } } /** * * * <pre> * Source for the environment variable's value. * </pre> * * <code>.google.cloud.run.v2.EnvVarSource value_source = 3;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.run.v2.EnvVarSource, com.google.cloud.run.v2.EnvVarSource.Builder, com.google.cloud.run.v2.EnvVarSourceOrBuilder> getValueSourceFieldBuilder() { if (valueSourceBuilder_ == null) { if (!(valuesCase_ == 3)) { values_ = com.google.cloud.run.v2.EnvVarSource.getDefaultInstance(); } valueSourceBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.run.v2.EnvVarSource, com.google.cloud.run.v2.EnvVarSource.Builder, com.google.cloud.run.v2.EnvVarSourceOrBuilder>( (com.google.cloud.run.v2.EnvVarSource) values_, getParentForChildren(), isClean()); values_ = null; } valuesCase_ = 3; onChanged(); return valueSourceBuilder_; } @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.run.v2.EnvVar) } // @@protoc_insertion_point(class_scope:google.cloud.run.v2.EnvVar) private static final com.google.cloud.run.v2.EnvVar DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.run.v2.EnvVar(); } public static com.google.cloud.run.v2.EnvVar getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<EnvVar> PARSER = new com.google.protobuf.AbstractParser<EnvVar>() { @java.lang.Override public EnvVar 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<EnvVar> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<EnvVar> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.run.v2.EnvVar getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,602
java-chat/proto-google-cloud-chat-v1/src/main/java/com/google/chat/v1/DialogAction.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/chat/v1/message.proto // Protobuf Java Version: 3.25.8 package com.google.chat.v1; /** * * * <pre> * Contains a * [dialog](https://developers.google.com/workspace/chat/dialogs) and request * status code. * </pre> * * Protobuf type {@code google.chat.v1.DialogAction} */ public final class DialogAction extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.chat.v1.DialogAction) DialogActionOrBuilder { private static final long serialVersionUID = 0L; // Use DialogAction.newBuilder() to construct. private DialogAction(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DialogAction() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DialogAction(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chat.v1.MessageProto.internal_static_google_chat_v1_DialogAction_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chat.v1.MessageProto .internal_static_google_chat_v1_DialogAction_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chat.v1.DialogAction.class, com.google.chat.v1.DialogAction.Builder.class); } private int bitField0_; private int actionCase_ = 0; @SuppressWarnings("serial") private java.lang.Object action_; public enum ActionCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { DIALOG(1), ACTION_NOT_SET(0); private final int value; private ActionCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static ActionCase valueOf(int value) { return forNumber(value); } public static ActionCase forNumber(int value) { switch (value) { case 1: return DIALOG; case 0: return ACTION_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public ActionCase getActionCase() { return ActionCase.forNumber(actionCase_); } public static final int DIALOG_FIELD_NUMBER = 1; /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return Whether the dialog field is set. */ @java.lang.Override public boolean hasDialog() { return actionCase_ == 1; } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return The dialog. */ @java.lang.Override public com.google.chat.v1.Dialog getDialog() { if (actionCase_ == 1) { return (com.google.chat.v1.Dialog) action_; } return com.google.chat.v1.Dialog.getDefaultInstance(); } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ @java.lang.Override public com.google.chat.v1.DialogOrBuilder getDialogOrBuilder() { if (actionCase_ == 1) { return (com.google.chat.v1.Dialog) action_; } return com.google.chat.v1.Dialog.getDefaultInstance(); } public static final int ACTION_STATUS_FIELD_NUMBER = 2; private com.google.chat.v1.ActionStatus actionStatus_; /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> * * @return Whether the actionStatus field is set. */ @java.lang.Override public boolean hasActionStatus() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> * * @return The actionStatus. */ @java.lang.Override public com.google.chat.v1.ActionStatus getActionStatus() { return actionStatus_ == null ? com.google.chat.v1.ActionStatus.getDefaultInstance() : actionStatus_; } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ @java.lang.Override public com.google.chat.v1.ActionStatusOrBuilder getActionStatusOrBuilder() { return actionStatus_ == null ? com.google.chat.v1.ActionStatus.getDefaultInstance() : actionStatus_; } 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 (actionCase_ == 1) { output.writeMessage(1, (com.google.chat.v1.Dialog) action_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(2, getActionStatus()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (actionCase_ == 1) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 1, (com.google.chat.v1.Dialog) action_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getActionStatus()); } 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.chat.v1.DialogAction)) { return super.equals(obj); } com.google.chat.v1.DialogAction other = (com.google.chat.v1.DialogAction) obj; if (hasActionStatus() != other.hasActionStatus()) return false; if (hasActionStatus()) { if (!getActionStatus().equals(other.getActionStatus())) return false; } if (!getActionCase().equals(other.getActionCase())) return false; switch (actionCase_) { case 1: if (!getDialog().equals(other.getDialog())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasActionStatus()) { hash = (37 * hash) + ACTION_STATUS_FIELD_NUMBER; hash = (53 * hash) + getActionStatus().hashCode(); } switch (actionCase_) { case 1: hash = (37 * hash) + DIALOG_FIELD_NUMBER; hash = (53 * hash) + getDialog().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.chat.v1.DialogAction parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.DialogAction parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chat.v1.DialogAction parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.DialogAction 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.chat.v1.DialogAction parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.chat.v1.DialogAction parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.chat.v1.DialogAction parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.chat.v1.DialogAction 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.chat.v1.DialogAction parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.chat.v1.DialogAction 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.chat.v1.DialogAction parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.chat.v1.DialogAction 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.chat.v1.DialogAction 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> * Contains a * [dialog](https://developers.google.com/workspace/chat/dialogs) and request * status code. * </pre> * * Protobuf type {@code google.chat.v1.DialogAction} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.chat.v1.DialogAction) com.google.chat.v1.DialogActionOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.chat.v1.MessageProto.internal_static_google_chat_v1_DialogAction_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.chat.v1.MessageProto .internal_static_google_chat_v1_DialogAction_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.chat.v1.DialogAction.class, com.google.chat.v1.DialogAction.Builder.class); } // Construct using com.google.chat.v1.DialogAction.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getActionStatusFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dialogBuilder_ != null) { dialogBuilder_.clear(); } actionStatus_ = null; if (actionStatusBuilder_ != null) { actionStatusBuilder_.dispose(); actionStatusBuilder_ = null; } actionCase_ = 0; action_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.chat.v1.MessageProto.internal_static_google_chat_v1_DialogAction_descriptor; } @java.lang.Override public com.google.chat.v1.DialogAction getDefaultInstanceForType() { return com.google.chat.v1.DialogAction.getDefaultInstance(); } @java.lang.Override public com.google.chat.v1.DialogAction build() { com.google.chat.v1.DialogAction result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.chat.v1.DialogAction buildPartial() { com.google.chat.v1.DialogAction result = new com.google.chat.v1.DialogAction(this); if (bitField0_ != 0) { buildPartial0(result); } buildPartialOneofs(result); onBuilt(); return result; } private void buildPartial0(com.google.chat.v1.DialogAction result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000002) != 0)) { result.actionStatus_ = actionStatusBuilder_ == null ? actionStatus_ : actionStatusBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } private void buildPartialOneofs(com.google.chat.v1.DialogAction result) { result.actionCase_ = actionCase_; result.action_ = this.action_; if (actionCase_ == 1 && dialogBuilder_ != null) { result.action_ = dialogBuilder_.build(); } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.chat.v1.DialogAction) { return mergeFrom((com.google.chat.v1.DialogAction) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.chat.v1.DialogAction other) { if (other == com.google.chat.v1.DialogAction.getDefaultInstance()) return this; if (other.hasActionStatus()) { mergeActionStatus(other.getActionStatus()); } switch (other.getActionCase()) { case DIALOG: { mergeDialog(other.getDialog()); break; } case ACTION_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getDialogFieldBuilder().getBuilder(), extensionRegistry); actionCase_ = 1; break; } // case 10 case 18: { input.readMessage(getActionStatusFieldBuilder().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 actionCase_ = 0; private java.lang.Object action_; public ActionCase getActionCase() { return ActionCase.forNumber(actionCase_); } public Builder clearAction() { actionCase_ = 0; action_ = null; onChanged(); return this; } private int bitField0_; private com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.Dialog, com.google.chat.v1.Dialog.Builder, com.google.chat.v1.DialogOrBuilder> dialogBuilder_; /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return Whether the dialog field is set. */ @java.lang.Override public boolean hasDialog() { return actionCase_ == 1; } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> * * @return The dialog. */ @java.lang.Override public com.google.chat.v1.Dialog getDialog() { if (dialogBuilder_ == null) { if (actionCase_ == 1) { return (com.google.chat.v1.Dialog) action_; } return com.google.chat.v1.Dialog.getDefaultInstance(); } else { if (actionCase_ == 1) { return dialogBuilder_.getMessage(); } return com.google.chat.v1.Dialog.getDefaultInstance(); } } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ public Builder setDialog(com.google.chat.v1.Dialog value) { if (dialogBuilder_ == null) { if (value == null) { throw new NullPointerException(); } action_ = value; onChanged(); } else { dialogBuilder_.setMessage(value); } actionCase_ = 1; return this; } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ public Builder setDialog(com.google.chat.v1.Dialog.Builder builderForValue) { if (dialogBuilder_ == null) { action_ = builderForValue.build(); onChanged(); } else { dialogBuilder_.setMessage(builderForValue.build()); } actionCase_ = 1; return this; } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ public Builder mergeDialog(com.google.chat.v1.Dialog value) { if (dialogBuilder_ == null) { if (actionCase_ == 1 && action_ != com.google.chat.v1.Dialog.getDefaultInstance()) { action_ = com.google.chat.v1.Dialog.newBuilder((com.google.chat.v1.Dialog) action_) .mergeFrom(value) .buildPartial(); } else { action_ = value; } onChanged(); } else { if (actionCase_ == 1) { dialogBuilder_.mergeFrom(value); } else { dialogBuilder_.setMessage(value); } } actionCase_ = 1; return this; } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ public Builder clearDialog() { if (dialogBuilder_ == null) { if (actionCase_ == 1) { actionCase_ = 0; action_ = null; onChanged(); } } else { if (actionCase_ == 1) { actionCase_ = 0; action_ = null; } dialogBuilder_.clear(); } return this; } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ public com.google.chat.v1.Dialog.Builder getDialogBuilder() { return getDialogFieldBuilder().getBuilder(); } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ @java.lang.Override public com.google.chat.v1.DialogOrBuilder getDialogOrBuilder() { if ((actionCase_ == 1) && (dialogBuilder_ != null)) { return dialogBuilder_.getMessageOrBuilder(); } else { if (actionCase_ == 1) { return (com.google.chat.v1.Dialog) action_; } return com.google.chat.v1.Dialog.getDefaultInstance(); } } /** * * * <pre> * Input only. * [Dialog](https://developers.google.com/workspace/chat/dialogs) for the * request. * </pre> * * <code>.google.chat.v1.Dialog dialog = 1 [(.google.api.field_behavior) = INPUT_ONLY];</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.Dialog, com.google.chat.v1.Dialog.Builder, com.google.chat.v1.DialogOrBuilder> getDialogFieldBuilder() { if (dialogBuilder_ == null) { if (!(actionCase_ == 1)) { action_ = com.google.chat.v1.Dialog.getDefaultInstance(); } dialogBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.Dialog, com.google.chat.v1.Dialog.Builder, com.google.chat.v1.DialogOrBuilder>( (com.google.chat.v1.Dialog) action_, getParentForChildren(), isClean()); action_ = null; } actionCase_ = 1; onChanged(); return dialogBuilder_; } private com.google.chat.v1.ActionStatus actionStatus_; private com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.ActionStatus, com.google.chat.v1.ActionStatus.Builder, com.google.chat.v1.ActionStatusOrBuilder> actionStatusBuilder_; /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> * * @return Whether the actionStatus field is set. */ public boolean hasActionStatus() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> * * @return The actionStatus. */ public com.google.chat.v1.ActionStatus getActionStatus() { if (actionStatusBuilder_ == null) { return actionStatus_ == null ? com.google.chat.v1.ActionStatus.getDefaultInstance() : actionStatus_; } else { return actionStatusBuilder_.getMessage(); } } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ public Builder setActionStatus(com.google.chat.v1.ActionStatus value) { if (actionStatusBuilder_ == null) { if (value == null) { throw new NullPointerException(); } actionStatus_ = value; } else { actionStatusBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ public Builder setActionStatus(com.google.chat.v1.ActionStatus.Builder builderForValue) { if (actionStatusBuilder_ == null) { actionStatus_ = builderForValue.build(); } else { actionStatusBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ public Builder mergeActionStatus(com.google.chat.v1.ActionStatus value) { if (actionStatusBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && actionStatus_ != null && actionStatus_ != com.google.chat.v1.ActionStatus.getDefaultInstance()) { getActionStatusBuilder().mergeFrom(value); } else { actionStatus_ = value; } } else { actionStatusBuilder_.mergeFrom(value); } if (actionStatus_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ public Builder clearActionStatus() { bitField0_ = (bitField0_ & ~0x00000002); actionStatus_ = null; if (actionStatusBuilder_ != null) { actionStatusBuilder_.dispose(); actionStatusBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ public com.google.chat.v1.ActionStatus.Builder getActionStatusBuilder() { bitField0_ |= 0x00000002; onChanged(); return getActionStatusFieldBuilder().getBuilder(); } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ public com.google.chat.v1.ActionStatusOrBuilder getActionStatusOrBuilder() { if (actionStatusBuilder_ != null) { return actionStatusBuilder_.getMessageOrBuilder(); } else { return actionStatus_ == null ? com.google.chat.v1.ActionStatus.getDefaultInstance() : actionStatus_; } } /** * * * <pre> * Input only. Status for a request to either invoke or submit a * [dialog](https://developers.google.com/workspace/chat/dialogs). Displays * a status and message to users, if necessary. * For example, in case of an error or success. * </pre> * * <code> * .google.chat.v1.ActionStatus action_status = 2 [(.google.api.field_behavior) = INPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.ActionStatus, com.google.chat.v1.ActionStatus.Builder, com.google.chat.v1.ActionStatusOrBuilder> getActionStatusFieldBuilder() { if (actionStatusBuilder_ == null) { actionStatusBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.chat.v1.ActionStatus, com.google.chat.v1.ActionStatus.Builder, com.google.chat.v1.ActionStatusOrBuilder>( getActionStatus(), getParentForChildren(), isClean()); actionStatus_ = null; } return actionStatusBuilder_; } @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.chat.v1.DialogAction) } // @@protoc_insertion_point(class_scope:google.chat.v1.DialogAction) private static final com.google.chat.v1.DialogAction DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.chat.v1.DialogAction(); } public static com.google.chat.v1.DialogAction getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DialogAction> PARSER = new com.google.protobuf.AbstractParser<DialogAction>() { @java.lang.Override public DialogAction 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<DialogAction> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DialogAction> getParserForType() { return PARSER; } @java.lang.Override public com.google.chat.v1.DialogAction getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,588
java-netapp/proto-google-cloud-netapp-v1/src/main/java/com/google/cloud/netapp/v1/CreateKmsConfigRequest.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/kms.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.netapp.v1; /** * * * <pre> * CreateKmsConfigRequest creates a KMS Config. * </pre> * * Protobuf type {@code google.cloud.netapp.v1.CreateKmsConfigRequest} */ public final class CreateKmsConfigRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.netapp.v1.CreateKmsConfigRequest) CreateKmsConfigRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateKmsConfigRequest.newBuilder() to construct. private CreateKmsConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateKmsConfigRequest() { parent_ = ""; kmsConfigId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateKmsConfigRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.KmsProto .internal_static_google_cloud_netapp_v1_CreateKmsConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.KmsProto .internal_static_google_cloud_netapp_v1_CreateKmsConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.CreateKmsConfigRequest.class, com.google.cloud.netapp.v1.CreateKmsConfigRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Value for parent. * </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. Value for parent. * </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 KMS_CONFIG_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object kmsConfigId_ = ""; /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The kmsConfigId. */ @java.lang.Override public java.lang.String getKmsConfigId() { java.lang.Object ref = kmsConfigId_; 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(); kmsConfigId_ = s; return s; } } /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for kmsConfigId. */ @java.lang.Override public com.google.protobuf.ByteString getKmsConfigIdBytes() { java.lang.Object ref = kmsConfigId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); kmsConfigId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int KMS_CONFIG_FIELD_NUMBER = 3; private com.google.cloud.netapp.v1.KmsConfig kmsConfig_; /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the kmsConfig field is set. */ @java.lang.Override public boolean hasKmsConfig() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The kmsConfig. */ @java.lang.Override public com.google.cloud.netapp.v1.KmsConfig getKmsConfig() { return kmsConfig_ == null ? com.google.cloud.netapp.v1.KmsConfig.getDefaultInstance() : kmsConfig_; } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.netapp.v1.KmsConfigOrBuilder getKmsConfigOrBuilder() { return kmsConfig_ == null ? com.google.cloud.netapp.v1.KmsConfig.getDefaultInstance() : kmsConfig_; } 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(kmsConfigId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, kmsConfigId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getKmsConfig()); } 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(kmsConfigId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, kmsConfigId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getKmsConfig()); } 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.CreateKmsConfigRequest)) { return super.equals(obj); } com.google.cloud.netapp.v1.CreateKmsConfigRequest other = (com.google.cloud.netapp.v1.CreateKmsConfigRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getKmsConfigId().equals(other.getKmsConfigId())) return false; if (hasKmsConfig() != other.hasKmsConfig()) return false; if (hasKmsConfig()) { if (!getKmsConfig().equals(other.getKmsConfig())) 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) + KMS_CONFIG_ID_FIELD_NUMBER; hash = (53 * hash) + getKmsConfigId().hashCode(); if (hasKmsConfig()) { hash = (37 * hash) + KMS_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getKmsConfig().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest 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.CreateKmsConfigRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest 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.CreateKmsConfigRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest 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.CreateKmsConfigRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest 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.CreateKmsConfigRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest 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.CreateKmsConfigRequest 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.CreateKmsConfigRequest 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.CreateKmsConfigRequest 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> * CreateKmsConfigRequest creates a KMS Config. * </pre> * * Protobuf type {@code google.cloud.netapp.v1.CreateKmsConfigRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.netapp.v1.CreateKmsConfigRequest) com.google.cloud.netapp.v1.CreateKmsConfigRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.netapp.v1.KmsProto .internal_static_google_cloud_netapp_v1_CreateKmsConfigRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.netapp.v1.KmsProto .internal_static_google_cloud_netapp_v1_CreateKmsConfigRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.netapp.v1.CreateKmsConfigRequest.class, com.google.cloud.netapp.v1.CreateKmsConfigRequest.Builder.class); } // Construct using com.google.cloud.netapp.v1.CreateKmsConfigRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getKmsConfigFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; kmsConfigId_ = ""; kmsConfig_ = null; if (kmsConfigBuilder_ != null) { kmsConfigBuilder_.dispose(); kmsConfigBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.netapp.v1.KmsProto .internal_static_google_cloud_netapp_v1_CreateKmsConfigRequest_descriptor; } @java.lang.Override public com.google.cloud.netapp.v1.CreateKmsConfigRequest getDefaultInstanceForType() { return com.google.cloud.netapp.v1.CreateKmsConfigRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.netapp.v1.CreateKmsConfigRequest build() { com.google.cloud.netapp.v1.CreateKmsConfigRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.netapp.v1.CreateKmsConfigRequest buildPartial() { com.google.cloud.netapp.v1.CreateKmsConfigRequest result = new com.google.cloud.netapp.v1.CreateKmsConfigRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.netapp.v1.CreateKmsConfigRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.kmsConfigId_ = kmsConfigId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.kmsConfig_ = kmsConfigBuilder_ == null ? kmsConfig_ : kmsConfigBuilder_.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.netapp.v1.CreateKmsConfigRequest) { return mergeFrom((com.google.cloud.netapp.v1.CreateKmsConfigRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.netapp.v1.CreateKmsConfigRequest other) { if (other == com.google.cloud.netapp.v1.CreateKmsConfigRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getKmsConfigId().isEmpty()) { kmsConfigId_ = other.kmsConfigId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasKmsConfig()) { mergeKmsConfig(other.getKmsConfig()); } 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: { kmsConfigId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getKmsConfigFieldBuilder().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. Value for parent. * </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. Value for parent. * </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. Value for parent. * </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. Value for parent. * </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. Value for parent. * </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 kmsConfigId_ = ""; /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The kmsConfigId. */ public java.lang.String getKmsConfigId() { java.lang.Object ref = kmsConfigId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); kmsConfigId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for kmsConfigId. */ public com.google.protobuf.ByteString getKmsConfigIdBytes() { java.lang.Object ref = kmsConfigId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); kmsConfigId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The kmsConfigId to set. * @return This builder for chaining. */ public Builder setKmsConfigId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } kmsConfigId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearKmsConfigId() { kmsConfigId_ = getDefaultInstance().getKmsConfigId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Id of the requesting KmsConfig. Must be unique within the parent * resource. Must contain only letters, numbers and hyphen, with the first * character a letter, the last a letter or a * number, and a 63 character maximum. * </pre> * * <code>string kms_config_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for kmsConfigId to set. * @return This builder for chaining. */ public Builder setKmsConfigIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); kmsConfigId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.netapp.v1.KmsConfig kmsConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.KmsConfig, com.google.cloud.netapp.v1.KmsConfig.Builder, com.google.cloud.netapp.v1.KmsConfigOrBuilder> kmsConfigBuilder_; /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the kmsConfig field is set. */ public boolean hasKmsConfig() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The kmsConfig. */ public com.google.cloud.netapp.v1.KmsConfig getKmsConfig() { if (kmsConfigBuilder_ == null) { return kmsConfig_ == null ? com.google.cloud.netapp.v1.KmsConfig.getDefaultInstance() : kmsConfig_; } else { return kmsConfigBuilder_.getMessage(); } } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setKmsConfig(com.google.cloud.netapp.v1.KmsConfig value) { if (kmsConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } kmsConfig_ = value; } else { kmsConfigBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setKmsConfig(com.google.cloud.netapp.v1.KmsConfig.Builder builderForValue) { if (kmsConfigBuilder_ == null) { kmsConfig_ = builderForValue.build(); } else { kmsConfigBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeKmsConfig(com.google.cloud.netapp.v1.KmsConfig value) { if (kmsConfigBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && kmsConfig_ != null && kmsConfig_ != com.google.cloud.netapp.v1.KmsConfig.getDefaultInstance()) { getKmsConfigBuilder().mergeFrom(value); } else { kmsConfig_ = value; } } else { kmsConfigBuilder_.mergeFrom(value); } if (kmsConfig_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearKmsConfig() { bitField0_ = (bitField0_ & ~0x00000004); kmsConfig_ = null; if (kmsConfigBuilder_ != null) { kmsConfigBuilder_.dispose(); kmsConfigBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.netapp.v1.KmsConfig.Builder getKmsConfigBuilder() { bitField0_ |= 0x00000004; onChanged(); return getKmsConfigFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.netapp.v1.KmsConfigOrBuilder getKmsConfigOrBuilder() { if (kmsConfigBuilder_ != null) { return kmsConfigBuilder_.getMessageOrBuilder(); } else { return kmsConfig_ == null ? com.google.cloud.netapp.v1.KmsConfig.getDefaultInstance() : kmsConfig_; } } /** * * * <pre> * Required. The required parameters to create a new KmsConfig. * </pre> * * <code> * .google.cloud.netapp.v1.KmsConfig kms_config = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.KmsConfig, com.google.cloud.netapp.v1.KmsConfig.Builder, com.google.cloud.netapp.v1.KmsConfigOrBuilder> getKmsConfigFieldBuilder() { if (kmsConfigBuilder_ == null) { kmsConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.netapp.v1.KmsConfig, com.google.cloud.netapp.v1.KmsConfig.Builder, com.google.cloud.netapp.v1.KmsConfigOrBuilder>( getKmsConfig(), getParentForChildren(), isClean()); kmsConfig_ = null; } return kmsConfigBuilder_; } @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.CreateKmsConfigRequest) } // @@protoc_insertion_point(class_scope:google.cloud.netapp.v1.CreateKmsConfigRequest) private static final com.google.cloud.netapp.v1.CreateKmsConfigRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.netapp.v1.CreateKmsConfigRequest(); } public static com.google.cloud.netapp.v1.CreateKmsConfigRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateKmsConfigRequest> PARSER = new com.google.protobuf.AbstractParser<CreateKmsConfigRequest>() { @java.lang.Override public CreateKmsConfigRequest 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<CreateKmsConfigRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateKmsConfigRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.netapp.v1.CreateKmsConfigRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,607
java-contact-center-insights/proto-google-cloud-contact-center-insights-v1/src/main/java/com/google/cloud/contactcenterinsights/v1/UpdateQaScorecardRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/contactcenterinsights/v1/contact_center_insights.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.contactcenterinsights.v1; /** * * * <pre> * The request for updating a QaScorecard. * </pre> * * Protobuf type {@code google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest} */ public final class UpdateQaScorecardRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest) UpdateQaScorecardRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateQaScorecardRequest.newBuilder() to construct. private UpdateQaScorecardRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateQaScorecardRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateQaScorecardRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto .internal_static_google_cloud_contactcenterinsights_v1_UpdateQaScorecardRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto .internal_static_google_cloud_contactcenterinsights_v1_UpdateQaScorecardRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest.class, com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest.Builder.class); } private int bitField0_; public static final int QA_SCORECARD_FIELD_NUMBER = 1; private com.google.cloud.contactcenterinsights.v1.QaScorecard qaScorecard_; /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the qaScorecard field is set. */ @java.lang.Override public boolean hasQaScorecard() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The qaScorecard. */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.QaScorecard getQaScorecard() { return qaScorecard_ == null ? com.google.cloud.contactcenterinsights.v1.QaScorecard.getDefaultInstance() : qaScorecard_; } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.contactcenterinsights.v1.QaScorecardOrBuilder getQaScorecardOrBuilder() { return qaScorecard_ == null ? com.google.cloud.contactcenterinsights.v1.QaScorecard.getDefaultInstance() : qaScorecard_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Required. The list of fields to be updated. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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, getQaScorecard()); } 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, getQaScorecard()); } 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.contactcenterinsights.v1.UpdateQaScorecardRequest)) { return super.equals(obj); } com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest other = (com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest) obj; if (hasQaScorecard() != other.hasQaScorecard()) return false; if (hasQaScorecard()) { if (!getQaScorecard().equals(other.getQaScorecard())) 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 (hasQaScorecard()) { hash = (37 * hash) + QA_SCORECARD_FIELD_NUMBER; hash = (53 * hash) + getQaScorecard().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.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest 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 for updating a QaScorecard. * </pre> * * Protobuf type {@code google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest) com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto .internal_static_google_cloud_contactcenterinsights_v1_UpdateQaScorecardRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto .internal_static_google_cloud_contactcenterinsights_v1_UpdateQaScorecardRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest.class, com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest.Builder.class); } // Construct using // com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getQaScorecardFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; qaScorecard_ = null; if (qaScorecardBuilder_ != null) { qaScorecardBuilder_.dispose(); qaScorecardBuilder_ = 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.contactcenterinsights.v1.ContactCenterInsightsProto .internal_static_google_cloud_contactcenterinsights_v1_UpdateQaScorecardRequest_descriptor; } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest getDefaultInstanceForType() { return com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest build() { com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest buildPartial() { com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest result = new com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.qaScorecard_ = qaScorecardBuilder_ == null ? qaScorecard_ : qaScorecardBuilder_.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.contactcenterinsights.v1.UpdateQaScorecardRequest) { return mergeFrom( (com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest other) { if (other == com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest .getDefaultInstance()) return this; if (other.hasQaScorecard()) { mergeQaScorecard(other.getQaScorecard()); } 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(getQaScorecardFieldBuilder().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.contactcenterinsights.v1.QaScorecard qaScorecard_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.QaScorecard, com.google.cloud.contactcenterinsights.v1.QaScorecard.Builder, com.google.cloud.contactcenterinsights.v1.QaScorecardOrBuilder> qaScorecardBuilder_; /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the qaScorecard field is set. */ public boolean hasQaScorecard() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The qaScorecard. */ public com.google.cloud.contactcenterinsights.v1.QaScorecard getQaScorecard() { if (qaScorecardBuilder_ == null) { return qaScorecard_ == null ? com.google.cloud.contactcenterinsights.v1.QaScorecard.getDefaultInstance() : qaScorecard_; } else { return qaScorecardBuilder_.getMessage(); } } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setQaScorecard(com.google.cloud.contactcenterinsights.v1.QaScorecard value) { if (qaScorecardBuilder_ == null) { if (value == null) { throw new NullPointerException(); } qaScorecard_ = value; } else { qaScorecardBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setQaScorecard( com.google.cloud.contactcenterinsights.v1.QaScorecard.Builder builderForValue) { if (qaScorecardBuilder_ == null) { qaScorecard_ = builderForValue.build(); } else { qaScorecardBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeQaScorecard(com.google.cloud.contactcenterinsights.v1.QaScorecard value) { if (qaScorecardBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && qaScorecard_ != null && qaScorecard_ != com.google.cloud.contactcenterinsights.v1.QaScorecard.getDefaultInstance()) { getQaScorecardBuilder().mergeFrom(value); } else { qaScorecard_ = value; } } else { qaScorecardBuilder_.mergeFrom(value); } if (qaScorecard_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearQaScorecard() { bitField0_ = (bitField0_ & ~0x00000001); qaScorecard_ = null; if (qaScorecardBuilder_ != null) { qaScorecardBuilder_.dispose(); qaScorecardBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.contactcenterinsights.v1.QaScorecard.Builder getQaScorecardBuilder() { bitField0_ |= 0x00000001; onChanged(); return getQaScorecardFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.contactcenterinsights.v1.QaScorecardOrBuilder getQaScorecardOrBuilder() { if (qaScorecardBuilder_ != null) { return qaScorecardBuilder_.getMessageOrBuilder(); } else { return qaScorecard_ == null ? com.google.cloud.contactcenterinsights.v1.QaScorecard.getDefaultInstance() : qaScorecard_; } } /** * * * <pre> * Required. The QaScorecard to update. * </pre> * * <code> * .google.cloud.contactcenterinsights.v1.QaScorecard qa_scorecard = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.QaScorecard, com.google.cloud.contactcenterinsights.v1.QaScorecard.Builder, com.google.cloud.contactcenterinsights.v1.QaScorecardOrBuilder> getQaScorecardFieldBuilder() { if (qaScorecardBuilder_ == null) { qaScorecardBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.contactcenterinsights.v1.QaScorecard, com.google.cloud.contactcenterinsights.v1.QaScorecard.Builder, com.google.cloud.contactcenterinsights.v1.QaScorecardOrBuilder>( getQaScorecard(), getParentForChildren(), isClean()); qaScorecard_ = null; } return qaScorecardBuilder_; } 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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </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. All possible fields can be * updated by passing `*`, or a subset of the following updateable fields can * be provided: * * * `description` * * `display_name` * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest) } // @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest) private static final com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest(); } public static com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateQaScorecardRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateQaScorecardRequest>() { @java.lang.Override public UpdateQaScorecardRequest 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<UpdateQaScorecardRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateQaScorecardRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.contactcenterinsights.v1.UpdateQaScorecardRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,636
java-discoveryengine/proto-google-cloud-discoveryengine-v1/src/main/java/com/google/cloud/discoveryengine/v1/UpdateConversationRequest.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/conversational_search_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1; /** * * * <pre> * Request for UpdateConversation method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.UpdateConversationRequest} */ public final class UpdateConversationRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1.UpdateConversationRequest) UpdateConversationRequestOrBuilder { private static final long serialVersionUID = 0L; // Use UpdateConversationRequest.newBuilder() to construct. private UpdateConversationRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private UpdateConversationRequest() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new UpdateConversationRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_UpdateConversationRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_UpdateConversationRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.UpdateConversationRequest.class, com.google.cloud.discoveryengine.v1.UpdateConversationRequest.Builder.class); } private int bitField0_; public static final int CONVERSATION_FIELD_NUMBER = 1; private com.google.cloud.discoveryengine.v1.Conversation conversation_; /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the conversation field is set. */ @java.lang.Override public boolean hasConversation() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The conversation. */ @java.lang.Override public com.google.cloud.discoveryengine.v1.Conversation getConversation() { return conversation_ == null ? com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance() : conversation_; } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.discoveryengine.v1.ConversationOrBuilder getConversationOrBuilder() { return conversation_ == null ? com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance() : conversation_; } public static final int UPDATE_MASK_FIELD_NUMBER = 2; private com.google.protobuf.FieldMask updateMask_; /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ @java.lang.Override public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ @java.lang.Override public com.google.protobuf.FieldMask getUpdateMask() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ @java.lang.Override public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(1, getConversation()); } 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, getConversation()); } 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.v1.UpdateConversationRequest)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1.UpdateConversationRequest other = (com.google.cloud.discoveryengine.v1.UpdateConversationRequest) obj; if (hasConversation() != other.hasConversation()) return false; if (hasConversation()) { if (!getConversation().equals(other.getConversation())) 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 (hasConversation()) { hash = (37 * hash) + CONVERSATION_FIELD_NUMBER; hash = (53 * hash) + getConversation().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.v1.UpdateConversationRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.UpdateConversationRequest 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.UpdateConversationRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.UpdateConversationRequest 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.UpdateConversationRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1.UpdateConversationRequest 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.UpdateConversationRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.UpdateConversationRequest 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.UpdateConversationRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1.UpdateConversationRequest 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.UpdateConversationRequest 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.UpdateConversationRequest 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.UpdateConversationRequest 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 UpdateConversation method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1.UpdateConversationRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1.UpdateConversationRequest) com.google.cloud.discoveryengine.v1.UpdateConversationRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_UpdateConversationRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_UpdateConversationRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1.UpdateConversationRequest.class, com.google.cloud.discoveryengine.v1.UpdateConversationRequest.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1.UpdateConversationRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getConversationFieldBuilder(); getUpdateMaskFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; conversation_ = null; if (conversationBuilder_ != null) { conversationBuilder_.dispose(); conversationBuilder_ = 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.v1.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1_UpdateConversationRequest_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1.UpdateConversationRequest getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1.UpdateConversationRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1.UpdateConversationRequest build() { com.google.cloud.discoveryengine.v1.UpdateConversationRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1.UpdateConversationRequest buildPartial() { com.google.cloud.discoveryengine.v1.UpdateConversationRequest result = new com.google.cloud.discoveryengine.v1.UpdateConversationRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.discoveryengine.v1.UpdateConversationRequest result) { int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { result.conversation_ = conversationBuilder_ == null ? conversation_ : conversationBuilder_.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.v1.UpdateConversationRequest) { return mergeFrom((com.google.cloud.discoveryengine.v1.UpdateConversationRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1.UpdateConversationRequest other) { if (other == com.google.cloud.discoveryengine.v1.UpdateConversationRequest.getDefaultInstance()) return this; if (other.hasConversation()) { mergeConversation(other.getConversation()); } 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(getConversationFieldBuilder().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.v1.Conversation conversation_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.discoveryengine.v1.Conversation, com.google.cloud.discoveryengine.v1.Conversation.Builder, com.google.cloud.discoveryengine.v1.ConversationOrBuilder> conversationBuilder_; /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the conversation field is set. */ public boolean hasConversation() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The conversation. */ public com.google.cloud.discoveryengine.v1.Conversation getConversation() { if (conversationBuilder_ == null) { return conversation_ == null ? com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance() : conversation_; } else { return conversationBuilder_.getMessage(); } } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConversation(com.google.cloud.discoveryengine.v1.Conversation value) { if (conversationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } conversation_ = value; } else { conversationBuilder_.setMessage(value); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setConversation( com.google.cloud.discoveryengine.v1.Conversation.Builder builderForValue) { if (conversationBuilder_ == null) { conversation_ = builderForValue.build(); } else { conversationBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeConversation(com.google.cloud.discoveryengine.v1.Conversation value) { if (conversationBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0) && conversation_ != null && conversation_ != com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance()) { getConversationBuilder().mergeFrom(value); } else { conversation_ = value; } } else { conversationBuilder_.mergeFrom(value); } if (conversation_ != null) { bitField0_ |= 0x00000001; onChanged(); } return this; } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearConversation() { bitField0_ = (bitField0_ & ~0x00000001); conversation_ = null; if (conversationBuilder_ != null) { conversationBuilder_.dispose(); conversationBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.discoveryengine.v1.Conversation.Builder getConversationBuilder() { bitField0_ |= 0x00000001; onChanged(); return getConversationFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.discoveryengine.v1.ConversationOrBuilder getConversationOrBuilder() { if (conversationBuilder_ != null) { return conversationBuilder_.getMessageOrBuilder(); } else { return conversation_ == null ? com.google.cloud.discoveryengine.v1.Conversation.getDefaultInstance() : conversation_; } } /** * * * <pre> * Required. The Conversation to update. * </pre> * * <code> * .google.cloud.discoveryengine.v1.Conversation conversation = 1 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.discoveryengine.v1.Conversation, com.google.cloud.discoveryengine.v1.Conversation.Builder, com.google.cloud.discoveryengine.v1.ConversationOrBuilder> getConversationFieldBuilder() { if (conversationBuilder_ == null) { conversationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.discoveryengine.v1.Conversation, com.google.cloud.discoveryengine.v1.Conversation.Builder, com.google.cloud.discoveryengine.v1.ConversationOrBuilder>( getConversation(), getParentForChildren(), isClean()); conversation_ = null; } return conversationBuilder_; } 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 * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return Whether the updateMask field is set. */ public boolean hasUpdateMask() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> * * @return The updateMask. */ public com.google.protobuf.FieldMask getUpdateMask() { if (updateMaskBuilder_ == null) { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } else { return updateMaskBuilder_.getMessage(); } } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (value == null) { throw new NullPointerException(); } updateMask_ = value; } else { updateMaskBuilder_.setMessage(value); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) { if (updateMaskBuilder_ == null) { updateMask_ = builderForValue.build(); } else { updateMaskBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) { if (updateMaskBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0) && updateMask_ != null && updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) { getUpdateMaskBuilder().mergeFrom(value); } else { updateMask_ = value; } } else { updateMaskBuilder_.mergeFrom(value); } if (updateMask_ != null) { bitField0_ |= 0x00000002; onChanged(); } return this; } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public Builder clearUpdateMask() { bitField0_ = (bitField0_ & ~0x00000002); updateMask_ = null; if (updateMaskBuilder_ != null) { updateMaskBuilder_.dispose(); updateMaskBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() { bitField0_ |= 0x00000002; onChanged(); return getUpdateMaskFieldBuilder().getBuilder(); } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() { if (updateMaskBuilder_ != null) { return updateMaskBuilder_.getMessageOrBuilder(); } else { return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_; } } /** * * * <pre> * Indicates which fields in the provided * [Conversation][google.cloud.discoveryengine.v1.Conversation] to update. The * following are NOT supported: * * * [Conversation.name][google.cloud.discoveryengine.v1.Conversation.name] * * If not set or empty, all supported fields are updated. * </pre> * * <code>.google.protobuf.FieldMask update_mask = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> getUpdateMaskFieldBuilder() { if (updateMaskBuilder_ == null) { updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>( getUpdateMask(), getParentForChildren(), isClean()); updateMask_ = null; } return updateMaskBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1.UpdateConversationRequest) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1.UpdateConversationRequest) private static final com.google.cloud.discoveryengine.v1.UpdateConversationRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1.UpdateConversationRequest(); } public static com.google.cloud.discoveryengine.v1.UpdateConversationRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<UpdateConversationRequest> PARSER = new com.google.protobuf.AbstractParser<UpdateConversationRequest>() { @java.lang.Override public UpdateConversationRequest 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<UpdateConversationRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<UpdateConversationRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1.UpdateConversationRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
google/sagetv
36,587
java/sage/DShowMediaPlayer.java
/* * Copyright 2015 The SageTV Authors. 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 sage; public class DShowMediaPlayer implements DVDMediaPlayer { protected static String PREFS_ROOT = BasicVideoFrame.VIDEOFRAME_KEY + '/'; protected static final String VIDEO_DECODER_FILTER = "video_decoder_filter"; protected static final String AUDIO_DECODER_FILTER = "audio_decoder_filter"; protected static final String AUDIO_RENDER_FILTER = "audio_render_filter"; protected static final String VIDEO_RENDER_FILTER = "video_render_filter"; protected static final String ADDITIONAL_VIDEO_FILTERS = "additional_video_filters"; protected static final String ADDITIONAL_AUDIO_FILTERS = "additional_audio_filters"; protected static final String USE_EVR = "use_evr"; protected static final String USE_VMR = "use_vmr"; protected static final String USE_OVERLAY = "use_overlay"; public static final boolean OVERLAY_IS_DEFAULT = true; protected static final String EVR_GUID = "{FA10746C-9B63-4B6C-BC49-FC300EA5F256}"; protected static final String VMR9_GUID = "{51B4ABF3-748F-4E3B-A276-C828330E926A}"; protected static final String OVERLAY_GUID = "{CD8743A1-3736-11D0-9E69-00C04FD7C15B}"; //"{A0025E90-E45B-11D1-ABE9-00A0C905F375}"; // OverlayMixer2 private static boolean EVR_SUPPORTED = false; public static boolean isEVRSupported() { return EVR_SUPPORTED; } public static final java.util.Comparator filterNameCompare = new java.util.Comparator() { public int compare(Object o1, Object o2) { return mystrcmp((String) o1, (String) o2); } int mystrcmp(String s1, String s2) { int i1=0, i2=0; do { if (i1 == s1.length() && i2 == s2.length()) return 0; if (i1 == s1.length()) return -1; if (i2 == s2.length()) return 1; char c1 = Character.toLowerCase(s1.charAt(i1)); char c2 = Character.toLowerCase(s2.charAt(i2)); i1++; i2++; // TERRIBLE HACK: There's a problem with the copyright symbol in the sonic cinemaster decoder's // name that I tried to deal with awhile back. And I added a wildcard to fix it. But it totally // screws up the sorting algorithm. I've changed it to only be the @ sign here so it shouldn't cause any harm anymore if ((c1 == '@' || c2 == '@') && (i1 > 5 && i2 > 5))//(!Character.isLetterOrDigit(c1) || !Character.isLetterOrDigit(c2)) continue; if (c1 != c2) return (int) (c1 - c2); }while (true); } }; protected static String[] videoFilterNames = Pooler.EMPTY_STRING_ARRAY; protected static String[] audioFilterNames = Pooler.EMPTY_STRING_ARRAY; static { if (Sage.WINDOWS_OS) { sage.Native.loadLibrary("DShowPlayer"); java.util.ArrayList videoFilters = new java.util.ArrayList(); java.util.ArrayList audioFilters = new java.util.ArrayList(); audioFilters.add("LAV Audio Decoder"); videoFilters.add("LAV Video Decoder"); audioFilters.add("Cyberlink Audio Decoder"); videoFilters.add("Cyberlink Video/SP Decoder"); audioFilters.add("CyberLink Audio Decoder (PDVD7)"); videoFilters.add("CyberLink Video/SP Decoder (PDVD7)"); audioFilters.add("CyberLink Audio Decoder (PDVD8)"); videoFilters.add("CyberLink Video/SP Decoder (PDVD8)"); audioFilters.add("CyberLink Audio Decoder (PDVD9)"); videoFilters.add("CyberLink Video/SP Decoder (PDVD9)"); audioFilters.add("CyberLink Audio Decoder (HD264)"); audioFilters.add("CyberLink Audio Decoder (ATI)"); audioFilters.add("CyberLink Audio Decoder(ATI)"); videoFilters.add("CyberLink Video/SP Decoder (ATI)"); videoFilters.add("CyberLink H.264/AVC Decoder(ATI)"); audioFilters.add("CyberLink Audio Decoder for Dell"); videoFilters.add("CyberLink Video/SP Decoder for Dell"); videoFilters.add("CyberLink Video/SP Decoder DELL 5.3"); String eleFilterName = Sage.readStringValue(Sage.HKEY_LOCAL_MACHINE, "SOFTWARE\\Classes\\CLSID\\{BC4EB321-771F-4e9f-AF67-37C631ECA106}", ""); if (eleFilterName != null) videoFilters.add(eleFilterName); eleFilterName = Sage.readStringValue(Sage.HKEY_LOCAL_MACHINE, "SOFTWARE\\Classes\\CLSID\\{F50B3F13-19C4-11CF-AA9A-02608C9BABA2}", ""); if (eleFilterName != null) videoFilters.add(eleFilterName); audioFilters.add("InterVideo Audio Decoder"); videoFilters.add("InterVideo Video Decoder"); audioFilters.add("InterVideo NonCSS Audio Decoder for Hauppauge"); videoFilters.add("InterVideo NonCSS Video Decoder for Hauppauge"); audioFilters.add("Moonlight Odio Dekoda"); audioFilters.add("MPEG Audio Decoder"); audioFilters.add("AC3Filter"); audioFilters.add("RAVISENT Cinemaster DS Audio Decoder"); videoFilters.add("RAVISENT Cinemaster DS Video Decoder"); videoFilters.add("Sigma Designs MPEG-2 hardware decoder"); audioFilters.add("DVD Express Audio Decoder"); videoFilters.add("DVD Express Video Decoder"); videoFilters.add("NVIDIA Video Decoder"); audioFilters.add("NVIDIA Audio Decoder"); videoFilters.add("ffdshow MPEG-4 Video Decoder"); audioFilters.add("ffdshow Audio Decoder"); videoFilters.add("NVIDIA Video Post Processor"); videoFilters.add("MainConcept MPEG Video Decoder"); if (!videoFilters.contains("MainConcept MPEG-2 Video Decoder")) videoFilters.add("MainConcept MPEG-2 Video Decoder"); // this shows up from the Elecard filter registry value sometimes audioFilters.add("MainConcept MPEG Audio Decoder"); audioFilters.add("ATI MPEG Audio Decoder"); videoFilters.add("ATI MPEG Video Decoder"); videoFilters.add("ArcSoft Video Decoder"); audioFilters.add("ArcSoft Audio Decoder HD"); videoFilters.add("Microsoft MPEG-2 Video Decoder"); audioFilters.add("Microsoft MPEG-1/DD Audio Decoder"); videoFilters.add("Microsoft DTV-DVD Video Decoder"); audioFilters.add("Microsoft DTV-DVD Audio Decoder"); String extraFilters = Sage.get(PREFS_ROOT + ADDITIONAL_AUDIO_FILTERS, ""); java.util.StringTokenizer toker = new java.util.StringTokenizer(extraFilters, ";"); while (toker.hasMoreTokens()) { // In case they're using the old format that also has pin names java.util.StringTokenizer toke2 = new java.util.StringTokenizer(toker.nextToken(), ","); audioFilters.add(toke2.nextToken()); } extraFilters = Sage.get(PREFS_ROOT + ADDITIONAL_VIDEO_FILTERS, ""); toker = new java.util.StringTokenizer(extraFilters, ";"); while (toker.hasMoreTokens()) { // In case they're using the old format that also has pin names java.util.StringTokenizer toke2 = new java.util.StringTokenizer(toker.nextToken(), ","); videoFilters.add(toke2.nextToken()); } String[] allFilters = DShowCaptureDevice.getDevicesInCategory0(DShowCaptureManager.FILTERS_CATEGORY_GUID); java.util.Arrays.sort(allFilters, filterNameCompare); if (Sage.DBG) System.out.println("DShowFilters=" + java.util.Arrays.asList(allFilters)); java.util.Iterator walker = audioFilters.iterator(); while (walker.hasNext()) { if (java.util.Arrays.binarySearch(allFilters, walker.next(), filterNameCompare) < 0) walker.remove(); } walker = videoFilters.iterator(); while (walker.hasNext()) { String curr = walker.next().toString(); if (java.util.Arrays.binarySearch(allFilters, curr, filterNameCompare) < 0) { walker.remove(); } } // Check these independently because they don't work right with the sorting for (int i = 0; i < allFilters.length; i++) { if (filterNameCompare.compare(allFilters[i], "Sonic Cinemaster@ DS Audio Decoder") == 0) audioFilters.add(allFilters[i]); if (filterNameCompare.compare(allFilters[i], "Sonic Cinemaster@ MCE Audio Decoder") == 0) audioFilters.add(allFilters[i]); if (filterNameCompare.compare(allFilters[i], "Sonic Cinemaster@ DS Video Decoder") == 0) videoFilters.add(allFilters[i]); if (filterNameCompare.compare(allFilters[i], "Sonic Cinemaster@ MCE Video Decoder") == 0) videoFilters.add(allFilters[i]); } // These should always be there because the names changed between V6.2 and V6.3 w/ the new DXVA decoders videoFilters.add("SageTV MPEG Video Decoder"); audioFilters.add("SageTV MPEG Audio Decoder"); videoFilterNames = (String[]) videoFilters.toArray(new String[0]); java.util.Arrays.sort(videoFilterNames); audioFilterNames = (String[]) audioFilters.toArray(new String[0]); java.util.Arrays.sort(audioFilterNames); EVR_SUPPORTED = java.util.Arrays.binarySearch(allFilters, "Enhanced Video Renderer", filterNameCompare) >= 0; if (Sage.DBG) System.out.println("EVR support detected=" + EVR_SUPPORTED); if (Sage.get(PREFS_ROOT + VIDEO_RENDER_FILTER, null) == null) { if (Sage.VISTA_OS) Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "EVR"); else if (Sage.getBoolean(PREFS_ROOT + USE_VMR, !OVERLAY_IS_DEFAULT)) Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "VMR9"); else if (Sage.getBoolean(PREFS_ROOT + USE_OVERLAY, OVERLAY_IS_DEFAULT)) Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "Overlay"); else Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "Default"); } } } public static boolean getUseOverlay() { return "Overlay".equals(Sage.get(PREFS_ROOT + VIDEO_RENDER_FILTER, null)); } public static void setUseOverlay(){ Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "Overlay"); } public static boolean getUseVmr() { return "VMR9".equals(Sage.get(PREFS_ROOT + VIDEO_RENDER_FILTER, null)); } public static void setUseVmr(){ Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "VMR9"); } public static boolean getUseEvr() { return "EVR".equals(Sage.get(PREFS_ROOT + VIDEO_RENDER_FILTER, null)); } public static void setUseEvr(){ Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "EVR"); } public static void setUseDefaultVideoRenderer() { Sage.put(PREFS_ROOT + VIDEO_RENDER_FILTER, "Default"); } public static String getAudioRenderFilter() { return Sage.rez(Sage.get(PREFS_ROOT + AUDIO_RENDER_FILTER, "Default")); } public static void setAudioRenderFilter(String x) { Sage.put(PREFS_ROOT + AUDIO_RENDER_FILTER, x); } public static String[] getAudioDecoderFilters() { return audioFilterNames; } public static String[] getVideoDecoderFilters() { return videoFilterNames; } public DShowMediaPlayer() { prefs = PREFS_ROOT; currState = NO_STATE; } public boolean canFastLoad(byte majorTypeHint, byte minorTypeHint, String encodingHint, java.io.File file) { return false; } public void fastLoad(byte majorTypeHint, byte minorTypeHint, String encodingHint, java.io.File file, String hostname, boolean timeshifted, long bufferSize, boolean waitUntilDone) throws PlaybackException { throw new PlaybackException(); } public boolean frameStep(int amount) { // Frame stepping will pause it if playing if (currState == PLAY_STATE || currState == PAUSE_STATE) { synchronized (this) { if (currState == PLAY_STATE) { if (pause0(pHandle)) currState = PAUSE_STATE; else return false; } return frameStep0(pHandle, amount); } } else return false; } public void free() { if (pHandle != 0) { // NOTE: This is required or it can hang the graph on stop. This was occuring when using // DivX files for playback in testing. We must do this to be safe because we can't // recover from hangs in this situation. // 12/08/04 - to keep sync on this, we put this back in the sync block here, but disabled // sync on the asyncStop call (which could deadlock us if this call was made from a thread // that has the lock already) synchronized (this) { if (currState == PAUSE_STATE || currState == PLAY_STATE) Sage.stop(this); teardownGraph0(pHandle); currState = NO_STATE; pHandle = 0; } VideoFrame.getVideoFrameForPlayer(this).getUIMgr().putFloat("videoframe/last_dshow_volume", lastVolume); } } public long getDurationMillis() { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { synchronized (this) { if (currTimeshifted) return 0; else return getDurationMillis0(pHandle); } } else return 0; } public java.io.File getFile() { return currFile; } public long getMediaTimeMillis() { if (currState == PLAY_STATE || currState == PAUSE_STATE) { synchronized (this) { if (currState == PLAY_STATE || currState == PAUSE_STATE) { return getMediaTimeMillis0(pHandle); } } } return 0; } public int getPlaybackCaps() { return FRAME_STEP_FORWARD_CAP | PAUSE_CAP | SEEK_CAP; } public float getPlaybackRate() { if (currState == PLAY_STATE || currState == PAUSE_STATE) { synchronized (this) { return getPlaybackRate0(pHandle); } } else return 1.0f; } public int getState() { return eos ? EOS_STATE : currState; } public float getVolume() { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { return lastVolume; // synchronized (this) // { // return getGraphVolume0(pHandle); // } } return 0; } public synchronized void inactiveFile() { inactiveFile0(pHandle); currTimeshifted = false; } protected void setFilters() throws PlaybackException { MediaFile mf = VideoFrame.getMediaFileForPlayer(this); nullVideoDim = false; if (getUseEvr() || getUseVmr()) { if (DirectX9SageRenderer.getD3DObjectPtr() != 0 && DirectX9SageRenderer.getD3DDevicePtr() != 0 && (getUseVmr() || DirectX9SageRenderer.getD3DDeviceMgr() != 0)) { java.util.Map vmrOptions = new java.util.HashMap(); vmrOptions.put("d3d_device_ptr", new Long(DirectX9SageRenderer.getD3DDevicePtr())); vmrOptions.put("d3d_object_ptr", new Long(DirectX9SageRenderer.getD3DObjectPtr())); vmrOptions.put("d3d_device_mgr", new Long(DirectX9SageRenderer.getD3DDeviceMgr())); // We never deal with CC for non MPEG2 playback; and MPEG2 playback is always handled by the DShowTVPlayer vmrOptions.put("enable_cc", new Boolean(false)); setVideoRendererFilter0(pHandle, getUseEvr() ? EVR_GUID : VMR9_GUID, vmrOptions); nullVideoDim = true; transparency = TRANSLUCENT; } else { setVideoRendererFilter0(pHandle, OVERLAY_GUID, null); transparency = BITMASK; } } else if (getUseOverlay()) { setVideoRendererFilter0(pHandle, OVERLAY_GUID, null); transparency = BITMASK; } else transparency = OPAQUE; String audDec = Sage.get(prefs + AUDIO_RENDER_FILTER, "Default"); if (audDec.length() > 0 && !"Default".equals(audDec)) setAudioRendererFilter0(pHandle, audDec, null); // If we're dealing with a WM Source and MS encoded audio or video then don't put // the filters in because it's better to let MS put the Decoder DMO objects in itself String contForm = mf.getContainerFormat(); String vidDec = ""; String vidType = mf != null ? mf.getPrimaryVideoFormat() : ""; if (!sage.media.format.MediaFormat.ASF.equals(contForm) || (!sage.media.format.MediaFormat.WMV7.equals(vidType) && !sage.media.format.MediaFormat.WMV8.equals(vidType) && !sage.media.format.MediaFormat.WMV9.equals(vidType) && !sage.media.format.MediaFormat.VC1.equals(vidType))) { if (sage.media.format.MediaFormat.H264.equals(vidType)) { setupH264DecoderFilter(); } else { // Check for a format specific video decoder if (sage.media.format.MediaFormat.MPEG2_VIDEO.equals(vidType)) vidDec = Sage.get(prefs + VIDEO_DECODER_FILTER, "SageTV MPEG Video Decoder"); else if (vidType.length() > 0) vidDec = Sage.get(prefs + vidType.toLowerCase() + "_" + VIDEO_DECODER_FILTER, ""); // Default to the WindowsMedia VC1 decoder if another one isn't specified if (vidDec.length() == 0 && sage.media.format.MediaFormat.VC1.equals(vidType)) vidDec = "WMVideo Decoder DMO"; if (vidDec.length() > 0 && !"Default".equals(vidDec) && !Sage.rez("Default").equals(vidDec)) setVideoDecoderFilter0(pHandle, vidDec, null); } } audDec = ""; String audType = ""; if (mf != null) { audType = mf.getPrimaryAudioFormat(); sage.media.format.ContainerFormat cf = mf.getFileFormat(); if (cf != null) { sage.media.format.AudioFormat[] afs = cf.getAudioFormats(false); if (afs != null && afs.length > languageIndex) audType = afs[languageIndex].getFormatName(); } } if (!sage.media.format.MediaFormat.ASF.equals(contForm) || (!sage.media.format.MediaFormat.WMA7.equals(audType) && !sage.media.format.MediaFormat.WMA8.equals(audType) && !sage.media.format.MediaFormat.WMA9LOSSLESS.equals(audType) && !sage.media.format.MediaFormat.WMA_PRO.equals(audType))) { // Check for a format specific audio decoder if (sage.media.format.MediaFormat.AC3.equals(audType) || sage.media.format.MediaFormat.MP2.equals(audType)) audDec = Sage.get(prefs + AUDIO_DECODER_FILTER, "SageTV MPEG Audio Decoder"); else if (audType.length() > 0) audDec = Sage.get(prefs + audType.toLowerCase() + "_" + AUDIO_DECODER_FILTER, ""); if (audDec.length() > 0 && !"Default".equals(audDec) && !Sage.rez("Default").equals(audDec)) setAudioDecoderFilter0(pHandle, audDec, null); else if (sage.media.format.MediaFormat.DTS.equalsIgnoreCase(audType) || "DCA".equalsIgnoreCase(audType)) setAudioDecoderFilter0(pHandle, "AC3Filter", null); } // Ugly hack for not being able to start at the beginning of H264 FLV files correctly (update to ffmpeg will likely fix it after V7.0) if (!currTimeshifted && sage.media.format.MediaFormat.FLASH_VIDEO.equals(mf.getContainerFormat()) && sage.media.format.MediaFormat.H264.equals(mf.getPrimaryVideoFormat())) minSeekTime = 5000; } protected void setupH264DecoderFilter() throws PlaybackException { String currH264Filter = null; if ((currH264Filter = Sage.get("videoframe/h264_video_decoder_filter", null)) == null) { // Try to find an H.264 decoder filter to use String[] allFilters = DShowCaptureDevice.getDevicesInCategory0(DShowCaptureManager.FILTERS_CATEGORY_GUID); java.util.Arrays.sort(allFilters, filterNameCompare); if (java.util.Arrays.binarySearch(allFilters, "ArcSoft Video Decoder", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "ArcSoft Video Decoder"); else if (java.util.Arrays.binarySearch(allFilters, "CyberLink H.264/AVC Decoder (PDVD8)", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "CyberLink H.264/AVC Decoder (PDVD8)"); else if (java.util.Arrays.binarySearch(allFilters, "CyberLink H.264/AVC Decoder (PDVD7)", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "CyberLink H.264/AVC Decoder (PDVD7)"); else if (java.util.Arrays.binarySearch(allFilters, "CyberLink H.264/AVC Decoder (HD264)", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "CyberLink H.264/AVC Decoder (HD264)"); else if (java.util.Arrays.binarySearch(allFilters, "CyberLink H.264/AVC Decoder(ATI)", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "CyberLink H.264/AVC Decoder(ATI)"); else if (java.util.Arrays.binarySearch(allFilters, "CoreAVC Video Decoder", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "CoreAVC Video Decoder"); else if (java.util.Arrays.binarySearch(allFilters, "CyberLink H.264/AVC Decoder (PDVD7.x)", filterNameCompare) >= 0) Sage.put("videoframe/h264_video_decoder_filter", currH264Filter = "CyberLink H.264/AVC Decoder (PDVD7.x)"); } if (currH264Filter != null) setVideoDecoderFilter0(pHandle, currH264Filter, null); } public synchronized void load(byte majorTypeHint, byte minorTypeHint, String encodingHint, java.io.File file, String hostname, boolean timeshifted, long bufferSize) throws PlaybackException { eos = false; pHandle = createGraph0(); UIManager uiMgr = VideoFrame.getVideoFrameForPlayer(this).getUIMgr(); lastVolume = (uiMgr.getBoolean("media_player_uses_system_volume", Sage.WINDOWS_OS && !Sage.VISTA_OS)) ? 1.0f : uiMgr.getFloat("videoframe/last_dshow_volume", 1.0f); currHintMajorType = majorTypeHint; currHintMinorType = minorTypeHint; currHintEncoding = encodingHint; currTimeshifted = timeshifted; // Set the default language index before we do the filters so we get the right audio codec selected setDefaultLangIndex(); setFilters(); // NOTE: Enabling timeshifting can only cause problems because we can't do this correctly // for anything that doesn't use the TV media player // UPDATE: I think if we use the stv:// URL for the file path then we should be able to deal with // the issues associated with using timeshifted playback since some other demuxes support it properly it turns out // UPDATE2: Nope. This'll fail on SageTVClient since it doesn't have a MediaServer running (and we can't run one since it might interfere w/ the local server) setTimeshifting0(pHandle, timeshifted, bufferSize); if (hostname != null && hostname.indexOf("mms://") != -1) { setupGraph0(pHandle, hostname, null, true, true); disableSeekAndRate = true; } else { setupGraph0(pHandle, file != null ? file.getPath() : null, hostname, true, true); disableSeekAndRate = false; } if (transparency != TRANSLUCENT && (majorTypeHint == MediaFile.MEDIATYPE_VIDEO || majorTypeHint == MediaFile.MEDIATYPE_DVD || majorTypeHint == MediaFile.MEDIATYPE_BLURAY)) // not vmr & video is present, so we need to render to the HWND setVideoHWND0(pHandle, VideoFrame.getVideoFrameForPlayer(this).getVideoHandle()); colorKey = null; currCCState = -1; videoDimensions = null; getVideoDimensions(); currFile = file; currState = LOADED_STATE; getColorKey(); setNotificationWindow0(pHandle, Sage.mainHwnd); } protected sage.media.format.ContainerFormat getCurrFormat() { VideoFrame vf = VideoFrame.getVideoFrameForPlayer(this); if (vf != null) { MediaFile mf = vf.getCurrFile(); if (mf != null) return mf.getFileFormat(); } return null; } protected void setDefaultLangIndex() { // Make sure we have the right default language index selected sage.media.format.ContainerFormat cf = getCurrFormat(); if (cf != null && cf.getNumAudioStreams() > 1) { boolean bestHDAudio = false; boolean bestAC3DTS = false; int bestChans = 0; sage.media.format.AudioFormat[] afs = cf.getAudioFormats(false); for (int i = 0; i < afs.length; i++) { boolean currHDAudio = sage.media.format.MediaFormat.DOLBY_HD.equals(afs[i].getFormatName()) || sage.media.format.MediaFormat.DTS_HD.equals(afs[i].getFormatName()) || sage.media.format.MediaFormat.DTS_MA.equals(afs[i].getFormatName()); int currChans = afs[i].getChannels(); if ((!bestHDAudio && currHDAudio) || (bestHDAudio && currHDAudio && (currChans > bestChans))) { languageIndex = i; bestHDAudio = true; bestChans = currChans; } else if (!bestHDAudio) { boolean currAC3DTS = sage.media.format.MediaFormat.AC3.equals(afs[i].getFormatName()) || sage.media.format.MediaFormat.DTS.equals(afs[i].getFormatName()) || "DCA".equals(afs[i].getFormatName()) || sage.media.format.MediaFormat.EAC3.equals(afs[i].getFormatName()); if ((!bestAC3DTS && currAC3DTS) || ((!bestAC3DTS || currAC3DTS) && (currChans > bestChans))) { languageIndex = i; bestAC3DTS = currAC3DTS; bestChans = currChans; } } } if (Sage.DBG) System.out.println("Detected default audio stream index to be: " + (languageIndex + 1)); } } public boolean pause() { if (currState == LOADED_STATE || currState == PLAY_STATE) { synchronized (this) { if (pause0(pHandle)) currState = PAUSE_STATE; } } return currState == PAUSE_STATE; } public boolean play() { if (currState == LOADED_STATE || currState == PAUSE_STATE) { synchronized (this) { if (play0(pHandle)) currState = PLAY_STATE; } } return currState == PLAY_STATE; } public long seek(long seekTimeMillis) throws PlaybackException { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { synchronized (this) { if (!disableSeekAndRate) { eos = false; seek0(pHandle, Math.max(minSeekTime, seekTimeMillis)); } return getMediaTimeMillis(); } } else return 0; } public void setMute(boolean x) { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { synchronized (this) { setGraphVolume0(pHandle, x ? 0 : lastVolume); } } } public boolean getMute() { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { synchronized (this) { return getGraphVolume0(pHandle) == 0; } } else return false; } public float setPlaybackRate(float newRate) { if (!disableSeekAndRate && (currState == PLAY_STATE || currState == PAUSE_STATE)) { synchronized (this) { setPlaybackRate0(pHandle, newRate); return getPlaybackRate0(pHandle); } } else return 1.0f; } public float setVolume(float f) { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { synchronized (this) { return setGraphVolume0(pHandle, lastVolume = f); } } return 0; } public void stop() { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { Sage.stop(this); } } // This is NOT synchronized so we don't deadlock void asyncStop() { stop0(pHandle); currState = STOPPED_STATE; } public java.awt.Color getColorKey() { if (transparency == BITMASK) { if (colorKey == null && currState != NO_STATE) { synchronized (this) { colorKey = getColorKey0(pHandle); } } return colorKey; } return null; } public int getTransparency() { return transparency; } public java.awt.Dimension getVideoDimensions() { if (nullVideoDim || currState == NO_STATE) return null; // makes VMR9 faster if (videoDimensions != null) return videoDimensions; synchronized (this) { videoDimensions = getVideoDimensions0(pHandle); if (Sage.DBG) System.out.println("Got Native Video Dimensions " + videoDimensions); return videoDimensions; } } public void setVideoRectangles(java.awt.Rectangle videoSrcRect, java.awt.Rectangle videoDestRect, boolean hideCursor) { // Don't do the native call for VMR9 because it doesn't do anything!! if (currState != NO_STATE && transparency != TRANSLUCENT && !nullVideoDim) { synchronized (this) { resizeVideo0(pHandle, videoSrcRect, videoDestRect, hideCursor); } } } public boolean setClosedCaptioningState(int ccState) { if (currState == NO_STATE || ccState < 0 || ccState > CC_ENABLED_CAPTION2) return false; else { synchronized (this) { if (setCCState0(pHandle, ccState)) { currCCState = ccState; return true; } else return false; } } } public int getClosedCaptioningState() { if (currState == NO_STATE) return CC_DISABLED; int rv = currCCState; if (rv < 0) { synchronized (this) { rv = currCCState = getCCState0(pHandle); } } return rv; } public synchronized void processEvents() throws PlaybackException { if (Sage.DBG) System.out.println("DShowMediaPlayer is consuming the events..."); if (pHandle != 0) { int res = processEvents0(pHandle); if (res == 1 || (res == 2 && VideoFrame.getVideoFrameForPlayer(this).isLiveControl())) eos = true; else if (res == 0x53) // render device changed, redo the video size { videoDimensions = null; } } } public boolean playControlEx(int playCode, long param1, long param2) throws PlaybackException { processEvents(); if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == LOADED_STATE) { if (playCode == VideoFrame.DVD_CONTROL_AUDIO_CHANGE) { int newLanguageIndex = param1 >= 0 ? (int)param1 : 0; if (newLanguageIndex != languageIndex) { languageIndex = newLanguageIndex; synchronized (this) { int oldState = currState; Sage.stop(this); processEvents(); boolean rv = demuxPlaybackControl0(pHandle, playCode, param1, param2); currState = oldState; if (currState == PAUSE_STATE) pause0(pHandle); else play0(pHandle); } } } } return false; } public boolean areDVDButtonsVisible() { return false; } public int getDVDAngle() { return 0; } public String[] getDVDAvailableLanguages() { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == STOPPED_STATE) // it can be stopped during the language switch { sage.media.format.ContainerFormat cf = getCurrFormat(); if (cf != null && cf.getNumAudioStreams() > 1) { return cf.getAudioStreamSelectionDescriptors(false); } } return new String[0]; } public String[] getDVDAvailableSubpictures() { return new String[0]; } public int getDVDChapter() { return 0; } public int getDVDTotalChapters() { return 0; } public int getDVDDomain() { return 0; } public String getDVDLanguage() { if (currState == PLAY_STATE || currState == PAUSE_STATE || currState == STOPPED_STATE) // it can be stopped during the language switch { sage.media.format.ContainerFormat cf = getCurrFormat(); if (cf != null && cf.getNumAudioStreams() > 1) { String[] audioStreams = cf.getAudioStreamSelectionDescriptors(false); return audioStreams[Math.min(audioStreams.length - 1, Math.max(0, languageIndex))]; } } return ""; } public String getDVDSubpicture() { return ""; } public int getDVDTitle() { return 0; } public int getDVDTotalAngles() { return 0; } public int getDVDTotalTitles() { return 0; } public float getCurrentAspectRatio() { return 0; } protected native boolean frameStep0(long ptr, int amount); protected native void teardownGraph0(long ptr); protected native long getDurationMillis0(long ptr); protected native long getMediaTimeMillis0(long ptr); protected native float getGraphVolume0(long ptr); protected native boolean pause0(long ptr); protected native boolean play0(long ptr); protected native void seek0(long ptr, long time) throws PlaybackException; protected native void stop0(long ptr); protected native void setPlaybackRate0(long ptr, float rate); protected native float getPlaybackRate0(long ptr); protected native float setGraphVolume0(long ptr, float volume); // createGraph0 will create the peer native object and create the initial filter graph protected native long createGraph0() throws PlaybackException; // setupGraph0 adds all of the filters to the graph and connects it up appropriately protected native void setupGraph0(long ptr, String filePath, String remoteHost, boolean renderVideo, boolean renderAudio) throws PlaybackException; // the setXXXFilter0 methods are used to specify what filters to use for different parts of the playback graph // the optionsMap is used to set different configurations specific to a certain filter. This gets resolved // at the native level (presently DXVAMode, DeinterlacingMode, DScaler properties, and // DX9 object refs for VMR9 are supported). // To specify the format for a pin connection, you should use the optionsMap of the // filter which has the input pin for that connection. protected native void setVideoDecoderFilter0(long ptr, String filterName, java.util.Map optionsMap) throws PlaybackException; protected native void setVideoPostProcessingFilter0(long ptr, String filterName, java.util.Map optionsMap) throws PlaybackException; protected native void setVideoRendererFilter0(long ptr, String filterName, java.util.Map optionsMap) throws PlaybackException; protected native void setAudioDecoderFilter0(long ptr, String filterName, java.util.Map optionsMap) throws PlaybackException; protected native void setAudioPostProcessingFilter0(long ptr, String filterName, java.util.Map optionsMap) throws PlaybackException; protected native void setAudioRendererFilter0(long ptr, String filterName, java.util.Map optionsMap) throws PlaybackException; protected native void setNotificationWindow0(long ptr, long hwndID); protected native void setVideoHWND0(long ptr, long hwnd); // use 0 to indicate non-circular file protected native void setTimeshifting0(long ptr, boolean isTimeshifting, long fileSize) throws PlaybackException; protected native java.awt.Color getColorKey0(long ptr); protected native java.awt.Dimension getVideoDimensions0(long ptr); protected native void resizeVideo0(long ptr, java.awt.Rectangle videoSrcRect, java.awt.Rectangle videoDestRect, boolean hideCursor); // Enables/disables specified closed captioning service protected native boolean setCCState0(long ptr, int ccState); protected native int getCCState0(long ptr); protected native int processEvents0(long ptr) throws PlaybackException; protected native boolean demuxPlaybackControl0(long ptr, int playCode, long param1, long param2); protected native void inactiveFile0(long ptr); protected int currState; protected long pHandle; protected java.io.File currFile; protected byte currHintMajorType; protected byte currHintMinorType; protected String currHintEncoding; protected String prefs; protected int transparency; protected java.awt.Color colorKey; protected java.awt.Dimension videoDimensions; protected int currCCState; protected boolean eos; protected boolean nullVideoDim; protected int languageIndex; protected float lastVolume; protected boolean currTimeshifted; protected boolean disableSeekAndRate; protected long minSeekTime; }
googleapis/google-cloud-java
36,599
java-datastream/proto-google-cloud-datastream-v1/src/main/java/com/google/cloud/datastream/v1/ListStreamObjectsResponse.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/datastream/v1/datastream.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.datastream.v1; /** * * * <pre> * Response containing the objects for a stream. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.ListStreamObjectsResponse} */ public final class ListStreamObjectsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datastream.v1.ListStreamObjectsResponse) ListStreamObjectsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListStreamObjectsResponse.newBuilder() to construct. private ListStreamObjectsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListStreamObjectsResponse() { streamObjects_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListStreamObjectsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamProto .internal_static_google_cloud_datastream_v1_ListStreamObjectsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamProto .internal_static_google_cloud_datastream_v1_ListStreamObjectsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.ListStreamObjectsResponse.class, com.google.cloud.datastream.v1.ListStreamObjectsResponse.Builder.class); } public static final int STREAM_OBJECTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.datastream.v1.StreamObject> streamObjects_; /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.datastream.v1.StreamObject> getStreamObjectsList() { return streamObjects_; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.datastream.v1.StreamObjectOrBuilder> getStreamObjectsOrBuilderList() { return streamObjects_; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ @java.lang.Override public int getStreamObjectsCount() { return streamObjects_.size(); } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ @java.lang.Override public com.google.cloud.datastream.v1.StreamObject getStreamObjects(int index) { return streamObjects_.get(index); } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ @java.lang.Override public com.google.cloud.datastream.v1.StreamObjectOrBuilder getStreamObjectsOrBuilder(int index) { return streamObjects_.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. * </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. * </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 < streamObjects_.size(); i++) { output.writeMessage(1, streamObjects_.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 < streamObjects_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, streamObjects_.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.datastream.v1.ListStreamObjectsResponse)) { return super.equals(obj); } com.google.cloud.datastream.v1.ListStreamObjectsResponse other = (com.google.cloud.datastream.v1.ListStreamObjectsResponse) obj; if (!getStreamObjectsList().equals(other.getStreamObjectsList())) 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 (getStreamObjectsCount() > 0) { hash = (37 * hash) + STREAM_OBJECTS_FIELD_NUMBER; hash = (53 * hash) + getStreamObjectsList().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.datastream.v1.ListStreamObjectsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.datastream.v1.ListStreamObjectsResponse 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 containing the objects for a stream. * </pre> * * Protobuf type {@code google.cloud.datastream.v1.ListStreamObjectsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1.ListStreamObjectsResponse) com.google.cloud.datastream.v1.ListStreamObjectsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datastream.v1.DatastreamProto .internal_static_google_cloud_datastream_v1_ListStreamObjectsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datastream.v1.DatastreamProto .internal_static_google_cloud_datastream_v1_ListStreamObjectsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datastream.v1.ListStreamObjectsResponse.class, com.google.cloud.datastream.v1.ListStreamObjectsResponse.Builder.class); } // Construct using com.google.cloud.datastream.v1.ListStreamObjectsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (streamObjectsBuilder_ == null) { streamObjects_ = java.util.Collections.emptyList(); } else { streamObjects_ = null; streamObjectsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.datastream.v1.DatastreamProto .internal_static_google_cloud_datastream_v1_ListStreamObjectsResponse_descriptor; } @java.lang.Override public com.google.cloud.datastream.v1.ListStreamObjectsResponse getDefaultInstanceForType() { return com.google.cloud.datastream.v1.ListStreamObjectsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datastream.v1.ListStreamObjectsResponse build() { com.google.cloud.datastream.v1.ListStreamObjectsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datastream.v1.ListStreamObjectsResponse buildPartial() { com.google.cloud.datastream.v1.ListStreamObjectsResponse result = new com.google.cloud.datastream.v1.ListStreamObjectsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.datastream.v1.ListStreamObjectsResponse result) { if (streamObjectsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { streamObjects_ = java.util.Collections.unmodifiableList(streamObjects_); bitField0_ = (bitField0_ & ~0x00000001); } result.streamObjects_ = streamObjects_; } else { result.streamObjects_ = streamObjectsBuilder_.build(); } } private void buildPartial0(com.google.cloud.datastream.v1.ListStreamObjectsResponse 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.datastream.v1.ListStreamObjectsResponse) { return mergeFrom((com.google.cloud.datastream.v1.ListStreamObjectsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datastream.v1.ListStreamObjectsResponse other) { if (other == com.google.cloud.datastream.v1.ListStreamObjectsResponse.getDefaultInstance()) return this; if (streamObjectsBuilder_ == null) { if (!other.streamObjects_.isEmpty()) { if (streamObjects_.isEmpty()) { streamObjects_ = other.streamObjects_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureStreamObjectsIsMutable(); streamObjects_.addAll(other.streamObjects_); } onChanged(); } } else { if (!other.streamObjects_.isEmpty()) { if (streamObjectsBuilder_.isEmpty()) { streamObjectsBuilder_.dispose(); streamObjectsBuilder_ = null; streamObjects_ = other.streamObjects_; bitField0_ = (bitField0_ & ~0x00000001); streamObjectsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getStreamObjectsFieldBuilder() : null; } else { streamObjectsBuilder_.addAllMessages(other.streamObjects_); } } } 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.datastream.v1.StreamObject m = input.readMessage( com.google.cloud.datastream.v1.StreamObject.parser(), extensionRegistry); if (streamObjectsBuilder_ == null) { ensureStreamObjectsIsMutable(); streamObjects_.add(m); } else { streamObjectsBuilder_.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.datastream.v1.StreamObject> streamObjects_ = java.util.Collections.emptyList(); private void ensureStreamObjectsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { streamObjects_ = new java.util.ArrayList<com.google.cloud.datastream.v1.StreamObject>(streamObjects_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datastream.v1.StreamObject, com.google.cloud.datastream.v1.StreamObject.Builder, com.google.cloud.datastream.v1.StreamObjectOrBuilder> streamObjectsBuilder_; /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public java.util.List<com.google.cloud.datastream.v1.StreamObject> getStreamObjectsList() { if (streamObjectsBuilder_ == null) { return java.util.Collections.unmodifiableList(streamObjects_); } else { return streamObjectsBuilder_.getMessageList(); } } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public int getStreamObjectsCount() { if (streamObjectsBuilder_ == null) { return streamObjects_.size(); } else { return streamObjectsBuilder_.getCount(); } } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public com.google.cloud.datastream.v1.StreamObject getStreamObjects(int index) { if (streamObjectsBuilder_ == null) { return streamObjects_.get(index); } else { return streamObjectsBuilder_.getMessage(index); } } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder setStreamObjects(int index, com.google.cloud.datastream.v1.StreamObject value) { if (streamObjectsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureStreamObjectsIsMutable(); streamObjects_.set(index, value); onChanged(); } else { streamObjectsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder setStreamObjects( int index, com.google.cloud.datastream.v1.StreamObject.Builder builderForValue) { if (streamObjectsBuilder_ == null) { ensureStreamObjectsIsMutable(); streamObjects_.set(index, builderForValue.build()); onChanged(); } else { streamObjectsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder addStreamObjects(com.google.cloud.datastream.v1.StreamObject value) { if (streamObjectsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureStreamObjectsIsMutable(); streamObjects_.add(value); onChanged(); } else { streamObjectsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder addStreamObjects(int index, com.google.cloud.datastream.v1.StreamObject value) { if (streamObjectsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureStreamObjectsIsMutable(); streamObjects_.add(index, value); onChanged(); } else { streamObjectsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder addStreamObjects( com.google.cloud.datastream.v1.StreamObject.Builder builderForValue) { if (streamObjectsBuilder_ == null) { ensureStreamObjectsIsMutable(); streamObjects_.add(builderForValue.build()); onChanged(); } else { streamObjectsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder addStreamObjects( int index, com.google.cloud.datastream.v1.StreamObject.Builder builderForValue) { if (streamObjectsBuilder_ == null) { ensureStreamObjectsIsMutable(); streamObjects_.add(index, builderForValue.build()); onChanged(); } else { streamObjectsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder addAllStreamObjects( java.lang.Iterable<? extends com.google.cloud.datastream.v1.StreamObject> values) { if (streamObjectsBuilder_ == null) { ensureStreamObjectsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, streamObjects_); onChanged(); } else { streamObjectsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder clearStreamObjects() { if (streamObjectsBuilder_ == null) { streamObjects_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { streamObjectsBuilder_.clear(); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public Builder removeStreamObjects(int index) { if (streamObjectsBuilder_ == null) { ensureStreamObjectsIsMutable(); streamObjects_.remove(index); onChanged(); } else { streamObjectsBuilder_.remove(index); } return this; } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public com.google.cloud.datastream.v1.StreamObject.Builder getStreamObjectsBuilder(int index) { return getStreamObjectsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public com.google.cloud.datastream.v1.StreamObjectOrBuilder getStreamObjectsOrBuilder( int index) { if (streamObjectsBuilder_ == null) { return streamObjects_.get(index); } else { return streamObjectsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public java.util.List<? extends com.google.cloud.datastream.v1.StreamObjectOrBuilder> getStreamObjectsOrBuilderList() { if (streamObjectsBuilder_ != null) { return streamObjectsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(streamObjects_); } } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public com.google.cloud.datastream.v1.StreamObject.Builder addStreamObjectsBuilder() { return getStreamObjectsFieldBuilder() .addBuilder(com.google.cloud.datastream.v1.StreamObject.getDefaultInstance()); } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public com.google.cloud.datastream.v1.StreamObject.Builder addStreamObjectsBuilder(int index) { return getStreamObjectsFieldBuilder() .addBuilder(index, com.google.cloud.datastream.v1.StreamObject.getDefaultInstance()); } /** * * * <pre> * List of stream objects. * </pre> * * <code>repeated .google.cloud.datastream.v1.StreamObject stream_objects = 1;</code> */ public java.util.List<com.google.cloud.datastream.v1.StreamObject.Builder> getStreamObjectsBuilderList() { return getStreamObjectsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datastream.v1.StreamObject, com.google.cloud.datastream.v1.StreamObject.Builder, com.google.cloud.datastream.v1.StreamObjectOrBuilder> getStreamObjectsFieldBuilder() { if (streamObjectsBuilder_ == null) { streamObjectsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.datastream.v1.StreamObject, com.google.cloud.datastream.v1.StreamObject.Builder, com.google.cloud.datastream.v1.StreamObjectOrBuilder>( streamObjects_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); streamObjects_ = null; } return streamObjectsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token, which can be sent as `page_token` to retrieve the next 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.datastream.v1.ListStreamObjectsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.datastream.v1.ListStreamObjectsResponse) private static final com.google.cloud.datastream.v1.ListStreamObjectsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datastream.v1.ListStreamObjectsResponse(); } public static com.google.cloud.datastream.v1.ListStreamObjectsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListStreamObjectsResponse> PARSER = new com.google.protobuf.AbstractParser<ListStreamObjectsResponse>() { @java.lang.Override public ListStreamObjectsResponse 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<ListStreamObjectsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListStreamObjectsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datastream.v1.ListStreamObjectsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
36,783
jaxp/src/com/sun/org/apache/xerces/internal/dom/ParentNode.java
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * Copyright 1999-2002,2004,2005 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 com.sun.org.apache.xerces.internal.dom; import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.UserDataHandler; /** * ParentNode inherits from ChildNode and adds the capability of having child * nodes. Not every node in the DOM can have children, so only nodes that can * should inherit from this class and pay the price for it. * <P> * ParentNode, just like NodeImpl, also implements NodeList, so it can * return itself in response to the getChildNodes() query. This eliminiates * the need for a separate ChildNodeList object. Note that this is an * IMPLEMENTATION DETAIL; applications should _never_ assume that * this identity exists. On the other hand, subclasses may need to override * this, in case of conflicting names. This is the case for the classes * HTMLSelectElementImpl and HTMLFormElementImpl of the HTML DOM. * <P> * While we have a direct reference to the first child, the last child is * stored as the previous sibling of the first child. First child nodes are * marked as being so, and getNextSibling hides this fact. * <P>Note: Not all parent nodes actually need to also be a child. At some * point we used to have ParentNode inheriting from NodeImpl and another class * called ChildAndParentNode that inherited from ChildNode. But due to the lack * of multiple inheritance a lot of code had to be duplicated which led to a * maintenance nightmare. At the same time only a few nodes (Document, * DocumentFragment, Entity, and Attribute) cannot be a child so the gain in * memory wasn't really worth it. The only type for which this would be the * case is Attribute, but we deal with there in another special way, so this is * not applicable. * <p> * This class doesn't directly support mutation events, however, it notifies * the document when mutations are performed so that the document class do so. * * <p><b>WARNING</b>: Some of the code here is partially duplicated in * AttrImpl, be careful to keep these two classes in sync! * * @xerces.internal * * @author Arnaud Le Hors, IBM * @author Joe Kesselman, IBM * @author Andy Clark, IBM * @version $Id: ParentNode.java,v 1.6 2009/07/21 20:30:28 joehw Exp $ */ public abstract class ParentNode extends ChildNode { /** Serialization version. */ static final long serialVersionUID = 2815829867152120872L; /** Owner document. */ protected CoreDocumentImpl ownerDocument; /** First child. */ protected ChildNode firstChild = null; // transients /** NodeList cache */ protected transient NodeListCache fNodeListCache = null; // // Constructors // /** * No public constructor; only subclasses of ParentNode should be * instantiated, and those normally via a Document's factory methods */ protected ParentNode(CoreDocumentImpl ownerDocument) { super(ownerDocument); this.ownerDocument = ownerDocument; } /** Constructor for serialization. */ public ParentNode() {} // // NodeList methods // /** * Returns a duplicate of a given node. You can consider this a * generic "copy constructor" for nodes. The newly returned object should * be completely independent of the source object's subtree, so changes * in one after the clone has been made will not affect the other. * <p> * Example: Cloning a Text node will copy both the node and the text it * contains. * <p> * Example: Cloning something that has children -- Element or Attr, for * example -- will _not_ clone those children unless a "deep clone" * has been requested. A shallow clone of an Attr node will yield an * empty Attr of the same name. * <p> * NOTE: Clones will always be read/write, even if the node being cloned * is read-only, to permit applications using only the DOM API to obtain * editable copies of locked portions of the tree. */ public Node cloneNode(boolean deep) { if (needsSyncChildren()) { synchronizeChildren(); } ParentNode newnode = (ParentNode) super.cloneNode(deep); // set owner document newnode.ownerDocument = ownerDocument; // Need to break the association w/ original kids newnode.firstChild = null; // invalidate cache for children NodeList newnode.fNodeListCache = null; // Then, if deep, clone the kids too. if (deep) { for (ChildNode child = firstChild; child != null; child = child.nextSibling) { newnode.appendChild(child.cloneNode(true)); } } return newnode; } // cloneNode(boolean):Node /** * Find the Document that this Node belongs to (the document in * whose context the Node was created). The Node may or may not * currently be part of that Document's actual contents. */ public Document getOwnerDocument() { return ownerDocument; } /** * same as above but returns internal type and this one is not overridden * by CoreDocumentImpl to return null */ CoreDocumentImpl ownerDocument() { return ownerDocument; } /** * NON-DOM * set the ownerDocument of this node and its children */ void setOwnerDocument(CoreDocumentImpl doc) { if (needsSyncChildren()) { synchronizeChildren(); } for (ChildNode child = firstChild; child != null; child = child.nextSibling) { child.setOwnerDocument(doc); } /* setting the owner document of self, after it's children makes the data of children available to the new document. */ super.setOwnerDocument(doc); ownerDocument = doc; } /** * Test whether this node has any children. Convenience shorthand * for (Node.getFirstChild()!=null) */ public boolean hasChildNodes() { if (needsSyncChildren()) { synchronizeChildren(); } return firstChild != null; } /** * Obtain a NodeList enumerating all children of this node. If there * are none, an (initially) empty NodeList is returned. * <p> * NodeLists are "live"; as children are added/removed the NodeList * will immediately reflect those changes. Also, the NodeList refers * to the actual nodes, so changes to those nodes made via the DOM tree * will be reflected in the NodeList and vice versa. * <p> * In this implementation, Nodes implement the NodeList interface and * provide their own getChildNodes() support. Other DOMs may solve this * differently. */ public NodeList getChildNodes() { if (needsSyncChildren()) { synchronizeChildren(); } return this; } // getChildNodes():NodeList /** The first child of this Node, or null if none. */ public Node getFirstChild() { if (needsSyncChildren()) { synchronizeChildren(); } return firstChild; } // getFirstChild():Node /** The last child of this Node, or null if none. */ public Node getLastChild() { if (needsSyncChildren()) { synchronizeChildren(); } return lastChild(); } // getLastChild():Node final ChildNode lastChild() { // last child is stored as the previous sibling of first child return firstChild != null ? firstChild.previousSibling : null; } final void lastChild(ChildNode node) { // store lastChild as previous sibling of first child if (firstChild != null) { firstChild.previousSibling = node; } } /** * Move one or more node(s) to our list of children. Note that this * implicitly removes them from their previous parent. * * @param newChild The Node to be moved to our subtree. As a * convenience feature, inserting a DocumentNode will instead insert * all its children. * * @param refChild Current child which newChild should be placed * immediately before. If refChild is null, the insertion occurs * after all existing Nodes, like appendChild(). * * @return newChild, in its new state (relocated, or emptied in the case of * DocumentNode.) * * @throws DOMException(HIERARCHY_REQUEST_ERR) if newChild is of a * type that shouldn't be a child of this node, or if newChild is an * ancestor of this node. * * @throws DOMException(WRONG_DOCUMENT_ERR) if newChild has a * different owner document than we do. * * @throws DOMException(NOT_FOUND_ERR) if refChild is not a child of * this node. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is * read-only. */ public Node insertBefore(Node newChild, Node refChild) throws DOMException { // Tail-call; optimizer should be able to do good things with. return internalInsertBefore(newChild, refChild, false); } // insertBefore(Node,Node):Node /** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able * to control which mutation events are spawned. This version of the * insertBefore operation allows us to do so. It is not intended * for use by application programs. */ Node internalInsertBefore(Node newChild, Node refChild, boolean replace) throws DOMException { boolean errorChecking = ownerDocument.errorChecking; if (newChild.getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. if (errorChecking) { for (Node kid = newChild.getFirstChild(); // Prescan kid != null; kid = kid.getNextSibling()) { if (!ownerDocument.isKidOK(this, kid)) { throw new DOMException( DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null)); } } } while (newChild.hasChildNodes()) { insertBefore(newChild.getFirstChild(), refChild); } return newChild; } if (newChild == refChild) { // stupid case that must be handled as a no-op triggering events... refChild = refChild.getNextSibling(); removeChild(newChild); insertBefore(newChild, refChild); return newChild; } if (needsSyncChildren()) { synchronizeChildren(); } if (errorChecking) { if (isReadOnly()) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } if (newChild.getOwnerDocument() != ownerDocument && newChild != ownerDocument) { throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "WRONG_DOCUMENT_ERR", null)); } if (!ownerDocument.isKidOK(this, newChild)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null)); } // refChild must be a child of this node (or null) if (refChild != null && refChild.getParentNode() != this) { throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null)); } // Prevent cycles in the tree // newChild cannot be ancestor of this Node, // and actually cannot be this if (ownerDocument.ancestorChecking) { boolean treeSafe = true; for (NodeImpl a = this; treeSafe && a != null; a = a.parentNode()) { treeSafe = newChild != a; } if(!treeSafe) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "HIERARCHY_REQUEST_ERR", null)); } } } // notify document ownerDocument.insertingNode(this, replace); // Convert to internal type, to avoid repeated casting ChildNode newInternal = (ChildNode)newChild; Node oldparent = newInternal.parentNode(); if (oldparent != null) { oldparent.removeChild(newInternal); } // Convert to internal type, to avoid repeated casting ChildNode refInternal = (ChildNode)refChild; // Attach up newInternal.ownerNode = this; newInternal.isOwned(true); // Attach before and after // Note: firstChild.previousSibling == lastChild!! if (firstChild == null) { // this our first and only child firstChild = newInternal; newInternal.isFirstChild(true); newInternal.previousSibling = newInternal; } else { if (refInternal == null) { // this is an append ChildNode lastChild = firstChild.previousSibling; lastChild.nextSibling = newInternal; newInternal.previousSibling = lastChild; firstChild.previousSibling = newInternal; } else { // this is an insert if (refChild == firstChild) { // at the head of the list firstChild.isFirstChild(false); newInternal.nextSibling = firstChild; newInternal.previousSibling = firstChild.previousSibling; firstChild.previousSibling = newInternal; firstChild = newInternal; newInternal.isFirstChild(true); } else { // somewhere in the middle ChildNode prev = refInternal.previousSibling; newInternal.nextSibling = refInternal; prev.nextSibling = newInternal; refInternal.previousSibling = newInternal; newInternal.previousSibling = prev; } } } changed(); // update cached length if we have any if (fNodeListCache != null) { if (fNodeListCache.fLength != -1) { fNodeListCache.fLength++; } if (fNodeListCache.fChildIndex != -1) { // if we happen to insert just before the cached node, update // the cache to the new node to match the cached index if (fNodeListCache.fChild == refInternal) { fNodeListCache.fChild = newInternal; } else { // otherwise just invalidate the cache fNodeListCache.fChildIndex = -1; } } } // notify document ownerDocument.insertedNode(this, newInternal, replace); checkNormalizationAfterInsert(newInternal); return newChild; } // internalInsertBefore(Node,Node,boolean):Node /** * Remove a child from this Node. The removed child's subtree * remains intact so it may be re-inserted elsewhere. * * @return oldChild, in its new state (removed). * * @throws DOMException(NOT_FOUND_ERR) if oldChild is not a child of * this node. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is * read-only. */ public Node removeChild(Node oldChild) throws DOMException { // Tail-call, should be optimizable return internalRemoveChild(oldChild, false); } // removeChild(Node) :Node /** NON-DOM INTERNAL: Within DOM actions,we sometimes need to be able * to control which mutation events are spawned. This version of the * removeChild operation allows us to do so. It is not intended * for use by application programs. */ Node internalRemoveChild(Node oldChild, boolean replace) throws DOMException { CoreDocumentImpl ownerDocument = ownerDocument(); if (ownerDocument.errorChecking) { if (isReadOnly()) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } if (oldChild != null && oldChild.getParentNode() != this) { throw new DOMException(DOMException.NOT_FOUND_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NOT_FOUND_ERR", null)); } } ChildNode oldInternal = (ChildNode) oldChild; // notify document ownerDocument.removingNode(this, oldInternal, replace); // update cached length if we have any if (fNodeListCache != null) { if (fNodeListCache.fLength != -1) { fNodeListCache.fLength--; } if (fNodeListCache.fChildIndex != -1) { // if the removed node is the cached node // move the cache to its (soon former) previous sibling if (fNodeListCache.fChild == oldInternal) { fNodeListCache.fChildIndex--; fNodeListCache.fChild = oldInternal.previousSibling(); } else { // otherwise just invalidate the cache fNodeListCache.fChildIndex = -1; } } } // Patch linked list around oldChild // Note: lastChild == firstChild.previousSibling if (oldInternal == firstChild) { // removing first child oldInternal.isFirstChild(false); firstChild = oldInternal.nextSibling; if (firstChild != null) { firstChild.isFirstChild(true); firstChild.previousSibling = oldInternal.previousSibling; } } else { ChildNode prev = oldInternal.previousSibling; ChildNode next = oldInternal.nextSibling; prev.nextSibling = next; if (next == null) { // removing last child firstChild.previousSibling = prev; } else { // removing some other child in the middle next.previousSibling = prev; } } // Save previous sibling for normalization checking. ChildNode oldPreviousSibling = oldInternal.previousSibling(); // Remove oldInternal's references to tree oldInternal.ownerNode = ownerDocument; oldInternal.isOwned(false); oldInternal.nextSibling = null; oldInternal.previousSibling = null; changed(); // notify document ownerDocument.removedNode(this, replace); checkNormalizationAfterRemove(oldPreviousSibling); return oldInternal; } // internalRemoveChild(Node,boolean):Node /** * Make newChild occupy the location that oldChild used to * have. Note that newChild will first be removed from its previous * parent, if any. Equivalent to inserting newChild before oldChild, * then removing oldChild. * * @return oldChild, in its new state (removed). * * @throws DOMException(HIERARCHY_REQUEST_ERR) if newChild is of a * type that shouldn't be a child of this node, or if newChild is * one of our ancestors. * * @throws DOMException(WRONG_DOCUMENT_ERR) if newChild has a * different owner document than we do. * * @throws DOMException(NOT_FOUND_ERR) if oldChild is not a child of * this node. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if this node is * read-only. */ public Node replaceChild(Node newChild, Node oldChild) throws DOMException { // If Mutation Events are being generated, this operation might // throw aggregate events twice when modifying an Attr -- once // on insertion and once on removal. DOM Level 2 does not specify // this as either desirable or undesirable, but hints that // aggregations should be issued only once per user request. // notify document ownerDocument.replacingNode(this); internalInsertBefore(newChild, oldChild, true); if (newChild != oldChild) { internalRemoveChild(oldChild, true); } // notify document ownerDocument.replacedNode(this); return oldChild; } /* * Get Node text content * @since DOM Level 3 */ public String getTextContent() throws DOMException { Node child = getFirstChild(); if (child != null) { Node next = child.getNextSibling(); if (next == null) { return hasTextContent(child) ? ((NodeImpl) child).getTextContent() : ""; } if (fBufferStr == null){ fBufferStr = new StringBuffer(); } else { fBufferStr.setLength(0); } getTextContent(fBufferStr); return fBufferStr.toString(); } return ""; } // internal method taking a StringBuffer in parameter void getTextContent(StringBuffer buf) throws DOMException { Node child = getFirstChild(); while (child != null) { if (hasTextContent(child)) { ((NodeImpl) child).getTextContent(buf); } child = child.getNextSibling(); } } // internal method returning whether to take the given node's text content final boolean hasTextContent(Node child) { return child.getNodeType() != Node.COMMENT_NODE && child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE && (child.getNodeType() != Node.TEXT_NODE || ((TextImpl) child).isIgnorableWhitespace() == false); } /* * Set Node text content * @since DOM Level 3 */ public void setTextContent(String textContent) throws DOMException { // get rid of any existing children Node child; while ((child = getFirstChild()) != null) { removeChild(child); } // create a Text node to hold the given content if (textContent != null && textContent.length() != 0){ appendChild(ownerDocument().createTextNode(textContent)); } } // // NodeList methods // /** * Count the immediate children of this node. Use to implement * NodeList.getLength(). * @return int */ private int nodeListGetLength() { if (fNodeListCache == null) { // get rid of trivial cases if (firstChild == null) { return 0; } if (firstChild == lastChild()) { return 1; } // otherwise request a cache object fNodeListCache = ownerDocument.getNodeListCache(this); } if (fNodeListCache.fLength == -1) { // is the cached length invalid ? int l; ChildNode n; // start from the cached node if we have one if (fNodeListCache.fChildIndex != -1 && fNodeListCache.fChild != null) { l = fNodeListCache.fChildIndex; n = fNodeListCache.fChild; } else { n = firstChild; l = 0; } while (n != null) { l++; n = n.nextSibling; } fNodeListCache.fLength = l; } return fNodeListCache.fLength; } // nodeListGetLength():int /** * NodeList method: Count the immediate children of this node * @return int */ public int getLength() { return nodeListGetLength(); } /** * Return the Nth immediate child of this node, or null if the index is * out of bounds. Use to implement NodeList.item(). * @param index int */ private Node nodeListItem(int index) { if (fNodeListCache == null) { // get rid of trivial case if (firstChild == lastChild()) { return index == 0 ? firstChild : null; } // otherwise request a cache object fNodeListCache = ownerDocument.getNodeListCache(this); } int i = fNodeListCache.fChildIndex; ChildNode n = fNodeListCache.fChild; boolean firstAccess = true; // short way if (i != -1 && n != null) { firstAccess = false; if (i < index) { while (i < index && n != null) { i++; n = n.nextSibling; } } else if (i > index) { while (i > index && n != null) { i--; n = n.previousSibling(); } } } else { // long way if (index < 0) { return null; } n = firstChild; for (i = 0; i < index && n != null; i++) { n = n.nextSibling; } } // release cache if reaching last child or first child if (!firstAccess && (n == firstChild || n == lastChild())) { fNodeListCache.fChildIndex = -1; fNodeListCache.fChild = null; ownerDocument.freeNodeListCache(fNodeListCache); // we can keep using the cache until it is actually reused // fNodeListCache will be nulled by the pool (document) if that // happens. // fNodeListCache = null; } else { // otherwise update it fNodeListCache.fChildIndex = i; fNodeListCache.fChild = n; } return n; } // nodeListItem(int):Node /** * NodeList method: Return the Nth immediate child of this node, or * null if the index is out of bounds. * @return org.w3c.dom.Node * @param index int */ public Node item(int index) { return nodeListItem(index); } // item(int):Node /** * Create a NodeList to access children that is use by subclass elements * that have methods named getLength() or item(int). ChildAndParentNode * optimizes getChildNodes() by implementing NodeList itself. However if * a subclass Element implements methods with the same name as the NodeList * methods, they will override the actually methods in this class. * <p> * To use this method, the subclass should implement getChildNodes() and * have it call this method. The resulting NodeList instance maybe * shared and cached in a transient field, but the cached value must be * cleared if the node is cloned. */ protected final NodeList getChildNodesUnoptimized() { if (needsSyncChildren()) { synchronizeChildren(); } return new NodeList() { /** * @see NodeList.getLength() */ public int getLength() { return nodeListGetLength(); } // getLength():int /** * @see NodeList.item(int) */ public Node item(int index) { return nodeListItem(index); } // item(int):Node }; } // getChildNodesUnoptimized():NodeList // // DOM2: methods, getters, setters // /** * Override default behavior to call normalize() on this Node's * children. It is up to implementors or Node to override normalize() * to take action. */ public void normalize() { // No need to normalize if already normalized. if (isNormalized()) { return; } if (needsSyncChildren()) { synchronizeChildren(); } ChildNode kid; for (kid = firstChild; kid != null; kid = kid.nextSibling) { kid.normalize(); } isNormalized(true); } /** * DOM Level 3 WD- Experimental. * Override inherited behavior from NodeImpl to support deep equal. */ public boolean isEqualNode(Node arg) { if (!super.isEqualNode(arg)) { return false; } // there are many ways to do this test, and there isn't any way // better than another. Performance may vary greatly depending on // the implementations involved. This one should work fine for us. Node child1 = getFirstChild(); Node child2 = arg.getFirstChild(); while (child1 != null && child2 != null) { if (!((NodeImpl) child1).isEqualNode(child2)) { return false; } child1 = child1.getNextSibling(); child2 = child2.getNextSibling(); } if (child1 != child2) { return false; } return true; } // // Public methods // /** * Override default behavior so that if deep is true, children are also * toggled. * @see Node * <P> * Note: this will not change the state of an EntityReference or its * children, which are always read-only. */ public void setReadOnly(boolean readOnly, boolean deep) { super.setReadOnly(readOnly, deep); if (deep) { if (needsSyncChildren()) { synchronizeChildren(); } // Recursively set kids for (ChildNode mykid = firstChild; mykid != null; mykid = mykid.nextSibling) { if (mykid.getNodeType() != Node.ENTITY_REFERENCE_NODE) { mykid.setReadOnly(readOnly,true); } } } } // setReadOnly(boolean,boolean) // // Protected methods // /** * Override this method in subclass to hook in efficient * internal data structure. */ protected void synchronizeChildren() { // By default just change the flag to avoid calling this method again needsSyncChildren(false); } /** * Checks the normalized state of this node after inserting a child. * If the inserted child causes this node to be unnormalized, then this * node is flagged accordingly. * The conditions for changing the normalized state are: * <ul> * <li>The inserted child is a text node and one of its adjacent siblings * is also a text node. * <li>The inserted child is is itself unnormalized. * </ul> * * @param insertedChild the child node that was inserted into this node * * @throws NullPointerException if the inserted child is <code>null</code> */ void checkNormalizationAfterInsert(ChildNode insertedChild) { // See if insertion caused this node to be unnormalized. if (insertedChild.getNodeType() == Node.TEXT_NODE) { ChildNode prev = insertedChild.previousSibling(); ChildNode next = insertedChild.nextSibling; // If an adjacent sibling of the new child is a text node, // flag this node as unnormalized. if ((prev != null && prev.getNodeType() == Node.TEXT_NODE) || (next != null && next.getNodeType() == Node.TEXT_NODE)) { isNormalized(false); } } else { // If the new child is not normalized, // then this node is inherently not normalized. if (!insertedChild.isNormalized()) { isNormalized(false); } } } // checkNormalizationAfterInsert(ChildNode) /** * Checks the normalized of this node after removing a child. * If the removed child causes this node to be unnormalized, then this * node is flagged accordingly. * The conditions for changing the normalized state are: * <ul> * <li>The removed child had two adjacent siblings that were text nodes. * </ul> * * @param previousSibling the previous sibling of the removed child, or * <code>null</code> */ void checkNormalizationAfterRemove(ChildNode previousSibling) { // See if removal caused this node to be unnormalized. // If the adjacent siblings of the removed child were both text nodes, // flag this node as unnormalized. if (previousSibling != null && previousSibling.getNodeType() == Node.TEXT_NODE) { ChildNode next = previousSibling.nextSibling; if (next != null && next.getNodeType() == Node.TEXT_NODE) { isNormalized(false); } } } // checkNormalizationAfterRemove(Node) // // Serialization methods // /** Serialize object. */ private void writeObject(ObjectOutputStream out) throws IOException { // synchronize chilren if (needsSyncChildren()) { synchronizeChildren(); } // write object out.defaultWriteObject(); } // writeObject(ObjectOutputStream) /** Deserialize object. */ private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { // perform default deseralization ois.defaultReadObject(); // hardset synchildren - so we don't try to sync - it does not make any // sense to try to synchildren when we just deserialize object. needsSyncChildren(false); } // readObject(ObjectInputStream) /* * a class to store some user data along with its handler */ class UserDataRecord implements Serializable { /** Serialization version. */ private static final long serialVersionUID = 3258126977134310455L; Object fData; UserDataHandler fHandler; UserDataRecord(Object data, UserDataHandler handler) { fData = data; fHandler = handler; } } } // class ParentNode
apache/druid
36,607
extensions-core/kubernetes-overlord-extensions/src/test/java/org/apache/druid/k8s/overlord/KubernetesPeonLifecycleTest.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.druid.k8s.overlord; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Optional; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodBuilder; import io.fabric8.kubernetes.api.model.batch.v1.Job; import io.fabric8.kubernetes.api.model.batch.v1.JobBuilder; import io.fabric8.kubernetes.client.dsl.LogWatch; import org.apache.commons.io.IOUtils; import org.apache.druid.indexer.TaskLocation; import org.apache.druid.indexer.TaskStatus; import org.apache.druid.indexing.common.TestUtils; import org.apache.druid.indexing.common.task.Task; import org.apache.druid.k8s.overlord.common.JobResponse; import org.apache.druid.k8s.overlord.common.K8sTaskId; import org.apache.druid.k8s.overlord.common.K8sTestUtils; import org.apache.druid.k8s.overlord.common.KubernetesPeonClient; import org.apache.druid.k8s.overlord.common.PeonPhase; import org.apache.druid.tasklogs.TaskLogs; import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.EasyMockSupport; import org.easymock.Mock; import org.joda.time.Period; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @RunWith(EasyMockRunner.class) public class KubernetesPeonLifecycleTest extends EasyMockSupport { private static final String ID = "id"; private static final TaskStatus SUCCESS = TaskStatus.success(ID); private static final Period LOG_SAVE_TIMEOUT = new Period("PT300S"); private static final Period SHORT_LOG_SAVE_TIMEOUT = new Period("PT1S"); @Mock KubernetesPeonClient kubernetesClient; @Mock TaskLogs taskLogs; @Mock LogWatch logWatch; @Mock KubernetesPeonLifecycle.TaskStateListener stateListener; private ObjectMapper mapper; private Task task; private K8sTaskId k8sTaskId; @Before public void setup() { mapper = new TestUtils().getTestObjectMapper(); task = K8sTestUtils.createTask(ID, 0); k8sTaskId = new K8sTaskId(null, task); EasyMock.expect(logWatch.getOutput()).andReturn(IOUtils.toInputStream("", StandardCharsets.UTF_8)).anyTimes(); } @Test public void test_run() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ) { @Override protected synchronized TaskStatus join(long timeout) { return TaskStatus.success(ID); } }; Job job = new JobBuilder().withNewMetadata().withName(ID).endMetadata().build(); EasyMock.expect(kubernetesClient.launchPeonJobAndWaitForStart( EasyMock.eq(job), EasyMock.eq(task), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(null); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); stateListener.stateChanged(KubernetesPeonLifecycle.State.PENDING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); replayAll(); TaskStatus taskStatus = peonLifecycle.run(job, 0L, 0L, false); verifyAll(); Assert.assertTrue(taskStatus.isSuccess()); Assert.assertEquals(ID, taskStatus.getId()); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_run_useTaskManager() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ) { @Override protected synchronized TaskStatus join(long timeout) { return TaskStatus.success(ID); } }; Job job = new JobBuilder().withNewMetadata().withName(ID).endMetadata().build(); EasyMock.expect(kubernetesClient.launchPeonJobAndWaitForStart( EasyMock.eq(job), EasyMock.eq(task), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(null); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); stateListener.stateChanged(KubernetesPeonLifecycle.State.PENDING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); taskLogs.pushTaskPayload(EasyMock.anyString(), EasyMock.anyObject()); replayAll(); TaskStatus taskStatus = peonLifecycle.run(job, 0L, 0L, true); verifyAll(); Assert.assertTrue(taskStatus.isSuccess()); Assert.assertEquals(ID, taskStatus.getId()); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_run_whenCalledMultipleTimes_raisesIllegalStateException() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ) { @Override protected synchronized TaskStatus join(long timeout) { return TaskStatus.success(ID); } }; Job job = new JobBuilder().withNewMetadata().withName(ID).endMetadata().build(); EasyMock.expect(kubernetesClient.launchPeonJobAndWaitForStart( EasyMock.eq(job), EasyMock.eq(task), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(null); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); stateListener.stateChanged(KubernetesPeonLifecycle.State.PENDING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); replayAll(); peonLifecycle.run(job, 0L, 0L, false); Assert.assertThrows( "Task [id] failed to run: invalid peon lifecycle state transition [STOPPED]->[PENDING]", IllegalStateException.class, () -> peonLifecycle.run(job, 0L, 0L, false) ); verifyAll(); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_run_whenExceptionRaised_setsRunnerTaskStateToNone() { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ) { @Override protected synchronized TaskStatus join(long timeout) { throw new IllegalStateException(); } }; Job job = new JobBuilder().withNewMetadata().withName(ID).endMetadata().build(); EasyMock.expect(kubernetesClient.launchPeonJobAndWaitForStart( EasyMock.eq(job), EasyMock.eq(task), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(null); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); stateListener.stateChanged(KubernetesPeonLifecycle.State.PENDING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); replayAll(); Assert.assertThrows( Exception.class, () -> peonLifecycle.run(job, 0L, 0L, false) ); verifyAll(); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_run_whenExceptionRaised_setsStartStatusFutureToFalse() throws ExecutionException, InterruptedException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ) { @Override protected synchronized TaskStatus join(long timeout) { throw new IllegalStateException(); } }; Job job = new JobBuilder().withNewMetadata().withName(ID).endMetadata().build(); EasyMock.expect(kubernetesClient.launchPeonJobAndWaitForStart( EasyMock.eq(job), EasyMock.eq(task), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(null); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); stateListener.stateChanged(KubernetesPeonLifecycle.State.PENDING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); replayAll(); Assert.assertThrows( Exception.class, () -> peonLifecycle.run(job, 0L, 0L, false) ); verifyAll(); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); Assert.assertTrue(peonLifecycle.getTaskStartedSuccessfullyFuture().isDone()); Assert.assertFalse(peonLifecycle.getTaskStartedSuccessfullyFuture().get()); } @Test public void test_join_withoutJob_returnsFailedTaskStatus() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(new JobResponse(null, PeonPhase.FAILED)); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.absent()); EasyMock.expect(taskLogs.streamTaskStatus(ID)).andReturn(Optional.absent()); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); replayAll(); TaskStatus taskStatus = peonLifecycle.join(0L); verifyAll(); Assert.assertTrue(taskStatus.isFailure()); Assert.assertEquals(ID, taskStatus.getId()); Assert.assertEquals("Peon did not report status successfully.", taskStatus.getErrorMsg()); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_join() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); Assert.assertFalse(peonLifecycle.getTaskStartedSuccessfullyFuture().isDone()); Job job = new JobBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withSucceeded(1) .withStartTime("2022-09-19T23:31:50Z") .withCompletionTime("2022-09-19T23:32:48Z") .endStatus() .build(); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(new JobResponse(job, PeonPhase.SUCCEEDED)); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.of(logWatch)); EasyMock.expect(taskLogs.streamTaskStatus(ID)).andReturn(Optional.of( IOUtils.toInputStream(mapper.writeValueAsString(SUCCESS), StandardCharsets.UTF_8) )); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); logWatch.close(); EasyMock.expectLastCall(); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); replayAll(); TaskStatus taskStatus = peonLifecycle.join(0L); verifyAll(); Assert.assertTrue(peonLifecycle.getTaskStartedSuccessfullyFuture().isDone()); Assert.assertEquals(SUCCESS.withDuration(58000), taskStatus); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_join_whenCalledMultipleTimes_raisesIllegalStateException() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); Job job = new JobBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withSucceeded(1) .endStatus() .build(); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(new JobResponse(job, PeonPhase.SUCCEEDED)); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.of(logWatch)); EasyMock.expect(taskLogs.streamTaskStatus(ID)).andReturn( Optional.of(IOUtils.toInputStream(mapper.writeValueAsString(SUCCESS), StandardCharsets.UTF_8)) ); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); logWatch.close(); EasyMock.expectLastCall(); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); logWatch.close(); EasyMock.expectLastCall(); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); replayAll(); TaskStatus taskStatus = peonLifecycle.join(0L); Assert.assertThrows( "Task [id] failed to join: invalid peon lifecycle state transition [STOPPED]->[PENDING]", IllegalStateException.class, () -> peonLifecycle.join(0L) ); verifyAll(); Assert.assertEquals(SUCCESS, taskStatus); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_join_withoutTaskStatus_returnsFailedTaskStatus() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); Job job = new JobBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withSucceeded(1) .endStatus() .build(); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(new JobResponse(job, PeonPhase.SUCCEEDED)); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.absent()); EasyMock.expect(taskLogs.streamTaskStatus(ID)).andReturn(Optional.absent()); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); replayAll(); TaskStatus taskStatus = peonLifecycle.join(0L); verifyAll(); Assert.assertTrue(taskStatus.isFailure()); Assert.assertEquals(ID, taskStatus.getId()); Assert.assertEquals("Peon did not report status successfully.", taskStatus.getErrorMsg()); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_join_whenIOExceptionThrownWhileStreamingTaskStatus_returnsFailedTaskStatus() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); Job job = new JobBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withSucceeded(1) .endStatus() .build(); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(new JobResponse(job, PeonPhase.SUCCEEDED)); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.of(logWatch)); EasyMock.expect(taskLogs.streamTaskStatus(ID)).andThrow(new IOException()); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); logWatch.close(); EasyMock.expectLastCall(); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); replayAll(); TaskStatus taskStatus = peonLifecycle.join(0L); verifyAll(); Assert.assertTrue(taskStatus.isFailure()); Assert.assertEquals(ID, taskStatus.getId()); Assert.assertEquals("error loading status: null", taskStatus.getErrorMsg()); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_join_whenIOExceptionThrownWhileStreamingTaskLogs_isIgnored() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); Job job = new JobBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withSucceeded(1) .endStatus() .build(); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andReturn(new JobResponse(job, PeonPhase.SUCCEEDED)); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.of(logWatch)); EasyMock.expect(taskLogs.streamTaskStatus(ID)).andReturn( Optional.of(IOUtils.toInputStream(mapper.writeValueAsString(SUCCESS), StandardCharsets.UTF_8)) ); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall().andThrow(new IOException()); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); logWatch.close(); EasyMock.expectLastCall(); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); replayAll(); TaskStatus taskStatus = peonLifecycle.join(0L); verifyAll(); Assert.assertEquals(SUCCESS, taskStatus); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_join_whenRuntimeExceptionThrownWhileWaitingForKubernetesJob_throwsException() throws IOException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); EasyMock.expect(kubernetesClient.waitForPeonJobCompletion( EasyMock.eq(k8sTaskId), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS) )).andThrow(new RuntimeException()); // We should still try to push logs EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.of(logWatch)); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); stateListener.stateChanged(KubernetesPeonLifecycle.State.RUNNING, ID); EasyMock.expectLastCall().once(); stateListener.stateChanged(KubernetesPeonLifecycle.State.STOPPED, ID); EasyMock.expectLastCall().once(); logWatch.close(); EasyMock.expectLastCall(); Assert.assertEquals(KubernetesPeonLifecycle.State.NOT_STARTED, peonLifecycle.getState()); replayAll(); Assert.assertThrows(RuntimeException.class, () -> peonLifecycle.join(0L)); verifyAll(); Assert.assertEquals(KubernetesPeonLifecycle.State.STOPPED, peonLifecycle.getState()); } @Test public void test_shutdown_withNotStartedTaskState() { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); peonLifecycle.shutdown(); } @Test public void test_shutdown_withPendingTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.PENDING); EasyMock.expect(kubernetesClient.deletePeonJob(k8sTaskId)).andReturn(true); replayAll(); peonLifecycle.shutdown(); verifyAll(); } @Test public void test_shutdown_withRunningTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); EasyMock.expect(kubernetesClient.deletePeonJob(k8sTaskId)).andReturn(true); replayAll(); peonLifecycle.shutdown(); verifyAll(); } @Test public void test_shutdown_withStoppedTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.STOPPED); peonLifecycle.shutdown(); } @Test public void test_streamLogs_withNotStartedTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.NOT_STARTED); peonLifecycle.streamLogs(); } @Test public void test_streamLogs_withPendingTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.PENDING); peonLifecycle.streamLogs(); } @Test public void test_streamLogs_withRunningTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); EasyMock.expect(kubernetesClient.getPeonLogs(k8sTaskId)).andReturn( Optional.of(IOUtils.toInputStream("", StandardCharsets.UTF_8)) ); replayAll(); peonLifecycle.streamLogs(); verifyAll(); } @Test public void test_streamLogs_withStoppedTaskState() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.STOPPED); peonLifecycle.streamLogs(); } @Test public void test_getTaskLocation_withNotStartedTaskState_returnsUnknown() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.NOT_STARTED); Assert.assertEquals(TaskLocation.unknown(), peonLifecycle.getTaskLocation()); } @Test public void test_getTaskLocation_withPendingTaskState_returnsUnknown() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.PENDING); Assert.assertEquals(TaskLocation.unknown(), peonLifecycle.getTaskLocation()); } @Test public void test_getTaskLocation_withRunningTaskState_withoutPeonPod_returnsUnknown() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); EasyMock.expect(kubernetesClient.getPeonPod(k8sTaskId.getK8sJobName())).andReturn(Optional.absent()); replayAll(); Assert.assertEquals(TaskLocation.unknown(), peonLifecycle.getTaskLocation()); verifyAll(); } @Test public void test_getTaskLocation_withRunningTaskState_withPeonPodWithoutStatus_returnsUnknown() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); Pod pod = new PodBuilder() .withNewMetadata() .withName(ID) .endMetadata() .build(); EasyMock.expect(kubernetesClient.getPeonPod(k8sTaskId.getK8sJobName())).andReturn(Optional.of(pod)); replayAll(); Assert.assertEquals(TaskLocation.unknown(), peonLifecycle.getTaskLocation()); verifyAll(); } @Test public void test_getTaskLocation_withRunningTaskState_withPeonPodWithStatus_returnsLocation() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); Pod pod = new PodBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withPodIP("ip") .endStatus() .build(); EasyMock.expect(kubernetesClient.getPeonPod(k8sTaskId.getK8sJobName())).andReturn(Optional.of(pod)); replayAll(); TaskLocation location = peonLifecycle.getTaskLocation(); Assert.assertEquals("ip", location.getHost()); Assert.assertEquals(8100, location.getPort()); Assert.assertEquals(-1, location.getTlsPort()); Assert.assertEquals(ID, location.getK8sPodName()); verifyAll(); } @Test public void test_getTaskLocation_saveTaskLocation() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); Pod pod = new PodBuilder() .withNewMetadata() .withName(ID) .endMetadata() .withNewStatus() .withPodIP("ip") .endStatus() .build(); EasyMock.expect(kubernetesClient.getPeonPod(k8sTaskId.getK8sJobName())).andReturn(Optional.of(pod)).once(); replayAll(); TaskLocation location = peonLifecycle.getTaskLocation(); peonLifecycle.getTaskLocation(); Assert.assertEquals("ip", location.getHost()); Assert.assertEquals(8100, location.getPort()); Assert.assertEquals(-1, location.getTlsPort()); Assert.assertEquals(ID, location.getK8sPodName()); verifyAll(); } @Test public void test_getTaskLocation_withRunningTaskState_withPeonPodWithStatusWithTLSAnnotation_returnsLocation() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.RUNNING); Pod pod = new PodBuilder() .withNewMetadata() .withName(ID) .addToAnnotations("tls.enabled", "true") .endMetadata() .withNewStatus() .withPodIP("ip") .endStatus() .build(); EasyMock.expect(kubernetesClient.getPeonPod(k8sTaskId.getK8sJobName())).andReturn(Optional.of(pod)); replayAll(); TaskLocation location = peonLifecycle.getTaskLocation(); Assert.assertEquals("ip", location.getHost()); Assert.assertEquals(-1, location.getPort()); Assert.assertEquals(8091, location.getTlsPort()); Assert.assertEquals(ID, location.getK8sPodName()); verifyAll(); } @Test public void test_getTaskLocation_withStoppedTaskState_returnsUnknown() throws NoSuchFieldException, IllegalAccessException { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); setPeonLifecycleState(peonLifecycle, KubernetesPeonLifecycle.State.STOPPED); EasyMock.expect(kubernetesClient.getPeonPod(k8sTaskId.getK8sJobName())).andReturn(Optional.absent()).once(); replayAll(); Assert.assertEquals(TaskLocation.unknown(), peonLifecycle.getTaskLocation()); verifyAll(); } @Test public void test_startWatchingLogs_logWatchInitialize_timeout() { KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, SHORT_LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)) .andAnswer(() -> { Thread.sleep(5000); // Exceeds 1 second timeout return Optional.of(logWatch); }); replayAll(); long startTime = System.currentTimeMillis(); peonLifecycle.startWatchingLogs(); long duration = System.currentTimeMillis() - startTime; // Anything less than 5 seconds means the Executor timeed out correctly, because the mock sleeps for 5 seconds Assert.assertTrue("Test should complete quickly due to timeout", duration < 2500); verifyAll(); } @Test public void test_saveLogs_streamLogs_timeout() throws IOException { EasyMock.reset(logWatch); InputStream slowInputStream = new InputStream() { @Override public int read() throws IOException { try { Thread.sleep(5000); } catch (InterruptedException e) { throw new IOException(e); } return -1; } }; KubernetesPeonLifecycle peonLifecycle = new KubernetesPeonLifecycle( task, k8sTaskId, kubernetesClient, taskLogs, mapper, stateListener, SHORT_LOG_SAVE_TIMEOUT.toStandardDuration().getMillis() ); EasyMock.expect(kubernetesClient.getPeonLogWatcher(k8sTaskId)).andReturn(Optional.of(logWatch)).once(); EasyMock.expect(logWatch.getOutput()).andReturn(slowInputStream); logWatch.close(); EasyMock.expectLastCall(); taskLogs.pushTaskLog(EasyMock.eq(ID), EasyMock.anyObject(File.class)); EasyMock.expectLastCall(); replayAll(); long startTime = System.currentTimeMillis(); peonLifecycle.saveLogs(); long duration = System.currentTimeMillis() - startTime; // Anything less than 5 seconds means the Executor timeed out correctly, because the mock sleeps for 5 seconds Assert.assertTrue("Test should complete quickly due to timeout", duration < 2500); verifyAll(); } private void setPeonLifecycleState(KubernetesPeonLifecycle peonLifecycle, KubernetesPeonLifecycle.State state) throws NoSuchFieldException, IllegalAccessException { Field stateField = peonLifecycle.getClass().getDeclaredField("state"); stateField.setAccessible(true); stateField.set(peonLifecycle, new AtomicReference<>(state)); } }
apache/hudi
36,591
hudi-cli/src/main/java/org/apache/hudi/cli/commands/CompactionCommand.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.hudi.cli.commands; import org.apache.hudi.avro.model.HoodieCompactionOperation; import org.apache.hudi.avro.model.HoodieCompactionPlan; import org.apache.hudi.cli.HoodieCLI; import org.apache.hudi.cli.HoodiePrintHelper; import org.apache.hudi.cli.HoodieTableHeaderFields; import org.apache.hudi.cli.TableHeader; import org.apache.hudi.cli.commands.SparkMain.SparkCommand; import org.apache.hudi.cli.utils.InputStreamConsumer; import org.apache.hudi.cli.utils.SparkUtil; import org.apache.hudi.client.CompactionAdminClient.RenameOpResult; import org.apache.hudi.client.CompactionAdminClient.ValidationOpResult; import org.apache.hudi.common.model.HoodieTableType; import org.apache.hudi.common.table.HoodieTableMetaClient; import org.apache.hudi.common.table.timeline.HoodieActiveTimeline; import org.apache.hudi.common.table.timeline.HoodieArchivedTimeline; import org.apache.hudi.common.table.timeline.HoodieInstant; import org.apache.hudi.common.table.timeline.HoodieTimeline; import org.apache.hudi.common.table.timeline.InstantGenerator; import org.apache.hudi.common.util.Option; import org.apache.hudi.common.util.StringUtils; import org.apache.hudi.common.util.collection.Pair; import org.apache.hudi.exception.HoodieException; import org.apache.hudi.exception.HoodieIOException; import org.apache.hudi.storage.HoodieStorage; import org.apache.hudi.storage.StoragePath; import org.apache.hudi.table.action.compact.OperationResult; import org.apache.hudi.utilities.UtilHelpers; import org.apache.spark.launcher.SparkLauncher; import org.apache.spark.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import org.springframework.shell.standard.ShellOption; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.hudi.cli.utils.CommitUtil.getTimeDaysAgo; import static org.apache.hudi.util.JavaScalaConverters.convertJavaPropertiesToScalaMap; /** * CLI command to display compaction related options. */ @ShellComponent public class CompactionCommand { private static final Logger LOG = LoggerFactory.getLogger(CompactionCommand.class); private static final String TMP_DIR = "/tmp/"; public static final String COMPACTION_SCH_SUCCESSFUL = "Attempted to schedule compaction for "; public static final String COMPACTION_EXE_SUCCESSFUL = "Compaction successfully completed for "; public static final String COMPACTION_SCH_EXE_SUCCESSFUL = "Schedule and execute compaction successfully completed"; private HoodieTableMetaClient checkAndGetMetaClient() { HoodieTableMetaClient client = HoodieCLI.getTableMetaClient(); if (client.getTableType() != HoodieTableType.MERGE_ON_READ) { throw new HoodieException("Compactions can only be run for table type : MERGE_ON_READ"); } return client; } @ShellMethod(key = "compactions show all", value = "Shows all compactions that are in active timeline") public String compactionsAll( @ShellOption(value = {"--includeExtraMetadata"}, help = "Include extra metadata", defaultValue = "false") final boolean includeExtraMetadata, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") final Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") final String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") final boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") final boolean headerOnly) { HoodieTableMetaClient client = checkAndGetMetaClient(); HoodieActiveTimeline activeTimeline = client.getActiveTimeline(); return printAllCompactions(activeTimeline, compactionPlanReader(this::readCompactionPlanForActiveTimeline, activeTimeline), includeExtraMetadata, sortByField, descending, limit, headerOnly); } @ShellMethod(key = "compaction show", value = "Shows compaction details for a specific compaction instant") public String compactionShow( @ShellOption(value = "--instant", help = "Base path for the target hoodie table") final String compactionInstantTime, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") final Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") final String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") final boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") final boolean headerOnly, @ShellOption(value = {"--partition"}, help = "Partition value", defaultValue = ShellOption.NULL) final String partition) throws Exception { HoodieTableMetaClient client = checkAndGetMetaClient(); HoodieActiveTimeline activeTimeline = client.getActiveTimeline(); InstantGenerator instantGenerator = client.getInstantGenerator(); HoodieCompactionPlan compactionPlan = activeTimeline.readCompactionPlan(instantGenerator.getCompactionRequestedInstant(compactionInstantTime)); return printCompaction(compactionPlan, sortByField, descending, limit, headerOnly, partition); } @ShellMethod(key = "compactions showarchived", value = "Shows compaction details for specified time window") public String compactionsShowArchived( @ShellOption(value = {"--includeExtraMetadata"}, help = "Include extra metadata", defaultValue = "false") final boolean includeExtraMetadata, @ShellOption(value = {"--startTs"}, defaultValue = ShellOption.NULL, help = "start time for compactions, default: now - 10 days") String startTs, @ShellOption(value = {"--endTs"}, defaultValue = ShellOption.NULL, help = "end time for compactions, default: now - 1 day") String endTs, @ShellOption(value = {"--limit"}, help = "Limit compactions", defaultValue = "-1") final Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") final String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") final boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") final boolean headerOnly) { if (StringUtils.isNullOrEmpty(startTs)) { startTs = getTimeDaysAgo(10); } if (StringUtils.isNullOrEmpty(endTs)) { endTs = getTimeDaysAgo(1); } HoodieTableMetaClient client = checkAndGetMetaClient(); HoodieArchivedTimeline archivedTimeline = client.getArchivedTimeline(); archivedTimeline.loadCompactionDetailsInMemory(startTs, endTs); try { return printAllCompactions(archivedTimeline, compactionPlanReader(this::readCompactionPlanForArchivedTimeline, archivedTimeline), includeExtraMetadata, sortByField, descending, limit, headerOnly); } finally { archivedTimeline.clearInstantDetailsFromMemory(startTs, endTs); } } @ShellMethod(key = "compaction showarchived", value = "Shows compaction details for a specific compaction instant") public String compactionShowArchived( @ShellOption(value = "--instant", help = "instant time") final String compactionInstantTime, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") final Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") final String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") final boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") final boolean headerOnly, @ShellOption(value = {"--partition"}, help = "Partition value", defaultValue = ShellOption.NULL) final String partition) throws Exception { HoodieTableMetaClient client = checkAndGetMetaClient(); HoodieArchivedTimeline archivedTimeline = client.getArchivedTimeline(); HoodieInstant instant = client.createNewInstant(HoodieInstant.State.COMPLETED, HoodieTimeline.COMPACTION_ACTION, compactionInstantTime); try { archivedTimeline.loadCompactionDetailsInMemory(compactionInstantTime); HoodieCompactionPlan compactionPlan = archivedTimeline.readCompactionPlan(instant); return printCompaction(compactionPlan, sortByField, descending, limit, headerOnly, partition); } finally { archivedTimeline.clearInstantDetailsFromMemory(compactionInstantTime); } } @ShellMethod(key = "compaction schedule", value = "Schedule Compaction") public String scheduleCompact( @ShellOption(value = "--sparkMemory", defaultValue = "1G", help = "Spark executor memory") final String sparkMemory, @ShellOption(value = "--propsFilePath", help = "path to properties file on localfs or dfs with configurations for hoodie client for compacting", defaultValue = "") final String propsFilePath, @ShellOption(value = "--hoodieConfigs", help = "Any configuration that can be set in the properties file can be passed here in the form of an array", defaultValue = "") final String[] configs, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master) throws Exception { HoodieTableMetaClient client = checkAndGetMetaClient(); boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); String sparkPropertiesPath = Utils.getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); String tableName = client.getTableConfig().getTableName(); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_SCHEDULE, master, sparkMemory, HoodieCLI.basePath, tableName, propsFilePath); UtilHelpers.validateAndAddProperties(configs, sparkLauncher); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to run compaction for " + tableName; } return COMPACTION_SCH_SUCCESSFUL + tableName; } @ShellMethod(key = "compaction run", value = "Run Compaction for given instant time") public String compact( @ShellOption(value = {"--parallelism"}, defaultValue = "3", help = "Parallelism for hoodie compaction") final String parallelism, @ShellOption(value = "--schemaFilePath", help = "Path for Avro schema file", defaultValue = "") final String schemaFilePath, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master, @ShellOption(value = "--sparkMemory", defaultValue = "4G", help = "Spark executor memory") final String sparkMemory, @ShellOption(value = "--retry", defaultValue = "1", help = "Number of retries") final String retry, @ShellOption(value = "--compactionInstant", help = "Instant of compaction.request", defaultValue = ShellOption.NULL) String compactionInstantTime, @ShellOption(value = "--propsFilePath", help = "path to properties file on localfs or dfs with configurations for hoodie client for compacting", defaultValue = "") final String propsFilePath, @ShellOption(value = "--hoodieConfigs", help = "Any configuration that can be set in the properties file can be passed here in the form of an array", defaultValue = "") final String[] configs) throws Exception { HoodieTableMetaClient client = checkAndGetMetaClient(); boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); if (null == compactionInstantTime) { // pick outstanding one with lowest timestamp Option<String> firstPendingInstant = client.reloadActiveTimeline().filterCompletedAndCompactionInstants() .filter(instant -> instant.getAction().equals(HoodieTimeline.COMPACTION_ACTION)).firstInstant() .map(HoodieInstant::requestedTime); if (!firstPendingInstant.isPresent()) { return "NO PENDING COMPACTION TO RUN"; } compactionInstantTime = firstPendingInstant.get(); } String sparkPropertiesPath = Utils.getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_RUN, master, sparkMemory, HoodieCLI.basePath, client.getTableConfig().getTableName(), compactionInstantTime, parallelism, schemaFilePath, retry, propsFilePath); UtilHelpers.validateAndAddProperties(configs, sparkLauncher); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to run compaction for " + compactionInstantTime; } return COMPACTION_EXE_SUCCESSFUL + compactionInstantTime; } @ShellMethod(key = "compaction scheduleAndExecute", value = "Schedule compaction plan and execute this plan") public String compact( @ShellOption(value = {"--parallelism"}, defaultValue = "3", help = "Parallelism for hoodie compaction") final String parallelism, @ShellOption(value = "--schemaFilePath", help = "Path for Avro schema file", defaultValue = ShellOption.NULL) final String schemaFilePath, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master, @ShellOption(value = "--sparkMemory", defaultValue = "4G", help = "Spark executor memory") final String sparkMemory, @ShellOption(value = "--retry", defaultValue = "1", help = "Number of retries") final String retry, @ShellOption(value = "--propsFilePath", help = "path to properties file on localfs or dfs with configurations for hoodie client for compacting", defaultValue = "") final String propsFilePath, @ShellOption(value = "--hoodieConfigs", help = "Any configuration that can be set in the properties file can be passed here in the form of an array", defaultValue = "") final String[] configs) throws Exception { HoodieTableMetaClient client = checkAndGetMetaClient(); boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); String sparkPropertiesPath = Utils.getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_SCHEDULE_AND_EXECUTE, master, sparkMemory, HoodieCLI.basePath, client.getTableConfig().getTableName(), parallelism, schemaFilePath, retry, propsFilePath); UtilHelpers.validateAndAddProperties(configs, sparkLauncher); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to schedule and execute compaction "; } return COMPACTION_SCH_EXE_SUCCESSFUL; } /** * Prints all compaction details. */ private static String printAllCompactions(HoodieTimeline timeline, Function<HoodieInstant, HoodieCompactionPlan> compactionPlanReader, boolean includeExtraMetadata, String sortByField, boolean descending, int limit, boolean headerOnly) { Stream<HoodieInstant> instantsStream = timeline.getWriteTimeline().getReverseOrderedInstants(); List<Pair<HoodieInstant, HoodieCompactionPlan>> compactionPlans = instantsStream .map(instant -> Pair.of(instant, compactionPlanReader.apply(instant))) .filter(pair -> pair.getRight() != null) .collect(Collectors.toList()); Set<String> committedInstants = timeline.getCommitAndReplaceTimeline().filterCompletedInstants() .getInstantsAsStream().map(HoodieInstant::requestedTime).collect(Collectors.toSet()); List<Comparable[]> rows = new ArrayList<>(); for (Pair<HoodieInstant, HoodieCompactionPlan> compactionPlan : compactionPlans) { HoodieCompactionPlan plan = compactionPlan.getRight(); HoodieInstant instant = compactionPlan.getLeft(); final HoodieInstant.State state; if (committedInstants.contains(instant.requestedTime())) { state = HoodieInstant.State.COMPLETED; } else { state = instant.getState(); } if (includeExtraMetadata) { rows.add(new Comparable[] {instant.requestedTime(), state.toString(), plan.getOperations() == null ? 0 : plan.getOperations().size(), plan.getExtraMetadata().toString()}); } else { rows.add(new Comparable[] {instant.requestedTime(), state.toString(), plan.getOperations() == null ? 0 : plan.getOperations().size()}); } } Map<String, Function<Object, String>> fieldNameToConverterMap = new HashMap<>(); TableHeader header = new TableHeader() .addTableHeaderField(HoodieTableHeaderFields.HEADER_COMPACTION_INSTANT_TIME) .addTableHeaderField(HoodieTableHeaderFields.HEADER_STATE) .addTableHeaderField(HoodieTableHeaderFields.HEADER_TOTAL_FILES_TO_BE_COMPACTED); if (includeExtraMetadata) { header = header.addTableHeaderField(HoodieTableHeaderFields.HEADER_EXTRA_METADATA); } return HoodiePrintHelper.print(header, fieldNameToConverterMap, sortByField, descending, limit, headerOnly, rows); } /** * Compaction reading is different for different timelines. Create partial function to override special logic. * We can make these read methods part of HoodieDefaultTimeline and override where necessary. But the * BiFunction below has 'hacky' exception blocks, so restricting it to CLI. */ private <T extends HoodieTimeline, U extends HoodieInstant, V extends HoodieCompactionPlan> Function<HoodieInstant, HoodieCompactionPlan> compactionPlanReader( BiFunction<T, HoodieInstant, HoodieCompactionPlan> f, T timeline) { return (y) -> f.apply(timeline, y); } private HoodieCompactionPlan readCompactionPlanForArchivedTimeline(HoodieArchivedTimeline archivedTimeline, HoodieInstant instant) { try { return archivedTimeline.readCompactionPlan(instant); } catch (Exception e) { throw new HoodieException(e.getMessage(), e); } } /** * TBD Can we make this part of HoodieActiveTimeline or a utility class. */ private HoodieCompactionPlan readCompactionPlanForActiveTimeline(HoodieActiveTimeline activeTimeline, HoodieInstant instant) { InstantGenerator instantGenerator = HoodieCLI.getTableMetaClient().getInstantGenerator(); try { if (!HoodieTimeline.COMPACTION_ACTION.equals(instant.getAction())) { try { // This could be a completed compaction. Assume a compaction request file is present but skip if fails return activeTimeline.readCompactionPlan( instantGenerator.getCompactionRequestedInstant(instant.requestedTime())); } catch (HoodieIOException ioe) { // SKIP return null; } } else { return activeTimeline.readCompactionPlan( instantGenerator.getCompactionRequestedInstant(instant.requestedTime())); } } catch (IOException e) { throw new HoodieIOException(e.getMessage(), e); } } protected static String printCompaction(HoodieCompactionPlan compactionPlan, String sortByField, boolean descending, int limit, boolean headerOnly, final String partition) { List<Comparable[]> rows = new ArrayList<>(); if ((null != compactionPlan) && (null != compactionPlan.getOperations())) { for (HoodieCompactionOperation op : compactionPlan.getOperations()) { if (StringUtils.isNullOrEmpty(partition) || partition.equals(op.getPartitionPath())) { rows.add(new Comparable[] {op.getPartitionPath(), op.getFileId(), op.getBaseInstantTime(), op.getDataFilePath(), op.getDeltaFilePaths().size(), op.getMetrics() == null ? "" : op.getMetrics().toString()}); } } } Map<String, Function<Object, String>> fieldNameToConverterMap = new HashMap<>(); TableHeader header = new TableHeader() .addTableHeaderField(HoodieTableHeaderFields.HEADER_PARTITION_PATH) .addTableHeaderField(HoodieTableHeaderFields.HEADER_FILE_ID) .addTableHeaderField(HoodieTableHeaderFields.HEADER_BASE_INSTANT) .addTableHeaderField(HoodieTableHeaderFields.HEADER_DATA_FILE_PATH) .addTableHeaderField(HoodieTableHeaderFields.HEADER_TOTAL_DELTA_FILES) .addTableHeaderField(HoodieTableHeaderFields.HEADER_METRICS); return HoodiePrintHelper.print(header, fieldNameToConverterMap, sortByField, descending, limit, headerOnly, rows); } private static String getTmpSerializerFile() { return TMP_DIR + UUID.randomUUID() + ".ser"; } private <T> T deSerializeOperationResult(StoragePath inputPath, HoodieStorage storage) throws Exception { InputStream inputStream = storage.open(inputPath); ObjectInputStream in = new ObjectInputStream(inputStream); try { T result = (T) in.readObject(); LOG.info("Result : " + result); return result; } finally { in.close(); inputStream.close(); } } @ShellMethod(key = "compaction validate", value = "Validate Compaction") public String validateCompaction( @ShellOption(value = "--instant", help = "Compaction Instant") String compactionInstant, @ShellOption(value = {"--parallelism"}, defaultValue = "3", help = "Parallelism") String parallelism, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master, @ShellOption(value = "--sparkMemory", defaultValue = "2G", help = "executor memory") String sparkMemory, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") boolean headerOnly) throws Exception { boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); String outputPathStr = getTmpSerializerFile(); StoragePath outputPath = new StoragePath(outputPathStr); String output; try { String sparkPropertiesPath = Utils .getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_VALIDATE, master, sparkMemory, HoodieCLI.basePath, compactionInstant, outputPathStr, parallelism); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to validate compaction for " + compactionInstant; } List<ValidationOpResult> res = deSerializeOperationResult(outputPath, HoodieCLI.storage); boolean valid = res.stream().map(OperationResult::isSuccess).reduce(Boolean::logicalAnd).orElse(true); String message = "\n\n\t COMPACTION PLAN " + (valid ? "VALID" : "INVALID") + "\n\n"; List<Comparable[]> rows = new ArrayList<>(); res.forEach(r -> { Comparable[] row = new Comparable[] {r.getOperation().getFileId(), r.getOperation().getBaseInstantTime(), r.getOperation().getDataFileName().isPresent() ? r.getOperation().getDataFileName().get() : "", r.getOperation().getDeltaFileNames().size(), r.isSuccess(), r.getException().isPresent() ? r.getException().get().getMessage() : ""}; rows.add(row); }); Map<String, Function<Object, String>> fieldNameToConverterMap = new HashMap<>(); TableHeader header = new TableHeader() .addTableHeaderField(HoodieTableHeaderFields.HEADER_FILE_ID) .addTableHeaderField(HoodieTableHeaderFields.HEADER_BASE_INSTANT_TIME) .addTableHeaderField(HoodieTableHeaderFields.HEADER_BASE_DATA_FILE) .addTableHeaderField(HoodieTableHeaderFields.HEADER_NUM_DELTA_FILES) .addTableHeaderField(HoodieTableHeaderFields.HEADER_VALID) .addTableHeaderField(HoodieTableHeaderFields.HEADER_ERROR); output = message + HoodiePrintHelper.print(header, fieldNameToConverterMap, sortByField, descending, limit, headerOnly, rows); } finally { // Delete tmp file used to serialize result if (HoodieCLI.storage.exists(outputPath)) { HoodieCLI.storage.deleteFile(outputPath); } } return output; } @ShellMethod(key = "compaction unschedule", value = "Unschedule Compaction") public String unscheduleCompaction( @ShellOption(value = "--instant", help = "Compaction Instant") String compactionInstant, @ShellOption(value = {"--parallelism"}, defaultValue = "3", help = "Parallelism") String parallelism, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master, @ShellOption(value = "--sparkMemory", defaultValue = "2G", help = "executor memory") String sparkMemory, @ShellOption(value = {"--skipValidation"}, help = "skip validation", defaultValue = "false") boolean skipV, @ShellOption(value = {"--dryRun"}, help = "Dry Run Mode", defaultValue = "false") boolean dryRun, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") boolean headerOnly) throws Exception { boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); String outputPathStr = getTmpSerializerFile(); StoragePath outputPath = new StoragePath(outputPathStr); String output; try { String sparkPropertiesPath = Utils .getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_UNSCHEDULE_PLAN, master, sparkMemory, HoodieCLI.basePath, compactionInstant, outputPathStr, parallelism, Boolean.valueOf(skipV).toString(), Boolean.valueOf(dryRun).toString()); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to unschedule compaction for " + compactionInstant; } List<RenameOpResult> res = deSerializeOperationResult(outputPath, HoodieCLI.storage); output = getRenamesToBePrinted(res, limit, sortByField, descending, headerOnly, "unschedule pending compaction"); } finally { // Delete tmp file used to serialize result if (HoodieCLI.storage.exists(outputPath)) { HoodieCLI.storage.deleteFile(outputPath); } } return output; } @ShellMethod(key = "compaction unscheduleFileId", value = "UnSchedule Compaction for a fileId") public String unscheduleCompactFile( @ShellOption(value = "--fileId", help = "File Id") final String fileId, @ShellOption(value = "--partitionPath", defaultValue = "", help = "partition path") final String partitionPath, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master, @ShellOption(value = "--sparkMemory", defaultValue = "2G", help = "executor memory") String sparkMemory, @ShellOption(value = {"--skipValidation"}, help = "skip validation", defaultValue = "false") boolean skipV, @ShellOption(value = {"--dryRun"}, help = "Dry Run Mode", defaultValue = "false") boolean dryRun, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") boolean descending, @ShellOption(value = {"--headeronly"}, help = "Header Only", defaultValue = "false") boolean headerOnly) throws Exception { boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); String outputPathStr = getTmpSerializerFile(); StoragePath outputPath = new StoragePath(outputPathStr); String output; try { String sparkPropertiesPath = Utils .getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_UNSCHEDULE_FILE, master, sparkMemory, HoodieCLI.basePath, fileId, partitionPath, outputPathStr, "1", Boolean.valueOf(skipV).toString(), Boolean.valueOf(dryRun).toString()); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to unschedule compaction for file " + fileId; } List<RenameOpResult> res = deSerializeOperationResult(outputPath, HoodieCLI.storage); output = getRenamesToBePrinted(res, limit, sortByField, descending, headerOnly, "unschedule file from pending compaction"); } finally { // Delete tmp file used to serialize result if (HoodieCLI.storage.exists(outputPath)) { HoodieCLI.storage.deleteFile(outputPath); } } return output; } @ShellMethod(key = "compaction repair", value = "Renames the files to make them consistent with the timeline as " + "dictated by Hoodie metadata. Use when compaction unschedule fails partially.") public String repairCompaction( @ShellOption(value = "--instant", help = "Compaction Instant") String compactionInstant, @ShellOption(value = {"--parallelism"}, defaultValue = "3", help = "Parallelism") String parallelism, @ShellOption(value = "--sparkMaster", defaultValue = "local", help = "Spark Master") String master, @ShellOption(value = "--sparkMemory", defaultValue = "2G", help = "executor memory") String sparkMemory, @ShellOption(value = {"--dryRun"}, help = "Dry Run Mode", defaultValue = "false") boolean dryRun, @ShellOption(value = {"--limit"}, help = "Limit commits", defaultValue = "-1") Integer limit, @ShellOption(value = {"--sortBy"}, help = "Sorting Field", defaultValue = "") String sortByField, @ShellOption(value = {"--desc"}, help = "Ordering", defaultValue = "false") boolean descending, @ShellOption(value = {"--headeronly"}, help = "Print Header Only", defaultValue = "false") boolean headerOnly) throws Exception { boolean initialized = HoodieCLI.initConf(); HoodieCLI.initFS(initialized); String outputPathStr = getTmpSerializerFile(); StoragePath outputPath = new StoragePath(outputPathStr); String output; try { String sparkPropertiesPath = Utils .getDefaultPropertiesFile(convertJavaPropertiesToScalaMap(System.getProperties())); SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath); SparkMain.addAppArgs(sparkLauncher, SparkCommand.COMPACT_REPAIR, master, sparkMemory, HoodieCLI.basePath, compactionInstant, outputPathStr, parallelism, Boolean.valueOf(dryRun).toString()); Process process = sparkLauncher.launch(); InputStreamConsumer.captureOutput(process); int exitCode = process.waitFor(); if (exitCode != 0) { return "Failed to unschedule compaction for " + compactionInstant; } List<RenameOpResult> res = deSerializeOperationResult(outputPath, HoodieCLI.storage); output = getRenamesToBePrinted(res, limit, sortByField, descending, headerOnly, "repair compaction"); } finally { // Delete tmp file used to serialize result if (HoodieCLI.storage.exists(outputPath)) { HoodieCLI.storage.deleteFile(outputPath); } } return output; } private String getRenamesToBePrinted(List<RenameOpResult> res, Integer limit, String sortByField, boolean descending, boolean headerOnly, String operation) { Option<Boolean> result = Option.fromJavaOptional(res.stream().map(r -> r.isExecuted() && r.isSuccess()).reduce(Boolean::logicalAnd)); if (result.isPresent()) { System.out.println("There were some file renames that needed to be done to " + operation); if (result.get()) { System.out.println("All renames successfully completed to " + operation + " done !!"); } else { System.out.println("Some renames failed. table could be in inconsistent-state. Try running compaction repair"); } List<Comparable[]> rows = new ArrayList<>(); res.forEach(r -> { Comparable[] row = new Comparable[] {r.getOperation().fileId, r.getOperation().srcPath, r.getOperation().destPath, r.isExecuted(), r.isSuccess(), r.getException().isPresent() ? r.getException().get().getMessage() : ""}; rows.add(row); }); Map<String, Function<Object, String>> fieldNameToConverterMap = new HashMap<>(); TableHeader header = new TableHeader() .addTableHeaderField(HoodieTableHeaderFields.HEADER_FILE_ID) .addTableHeaderField(HoodieTableHeaderFields.HEADER_SOURCE_FILE_PATH) .addTableHeaderField(HoodieTableHeaderFields.HEADER_DESTINATION_FILE_PATH) .addTableHeaderField(HoodieTableHeaderFields.HEADER_RENAME_EXECUTED) .addTableHeaderField(HoodieTableHeaderFields.HEADER_RENAME_SUCCEEDED) .addTableHeaderField(HoodieTableHeaderFields.HEADER_ERROR); return HoodiePrintHelper.print(header, fieldNameToConverterMap, sortByField, descending, limit, headerOnly, rows); } else { return "No File renames needed to " + operation + ". Operation successful."; } } }
hibernate/hibernate-orm
33,443
hibernate-core/src/test/java/org/hibernate/orm/test/immutable/entitywithmutablecollection/AbstractEntityWithManyToManyTest.java
/* * SPDX-License-Identifier: Apache-2.0 * Copyright Red Hat Inc. and Hibernate Authors */ package org.hibernate.orm.test.immutable.entitywithmutablecollection; import java.util.Iterator; import org.hibernate.LockMode; import org.hibernate.StaleObjectStateException; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.metamodel.MappingMetamodel; import org.hibernate.testing.orm.junit.SessionFactory; import org.hibernate.testing.orm.junit.SessionFactoryScope; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import jakarta.persistence.PersistenceException; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Root; import static org.hibernate.testing.orm.junit.ExtraAssertions.assertTyping; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * @author Gail Badner */ @SessionFactory(generateStatistics = true) public abstract class AbstractEntityWithManyToManyTest { private boolean isPlanContractsInverse; private boolean isPlanContractsBidirectional; private boolean isPlanVersioned; private boolean isContractVersioned; @BeforeEach protected void prepareTest(SessionFactoryScope scope) throws Exception { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); MappingMetamodel domainModel = sessionFactory.getRuntimeMetamodels().getMappingMetamodel(); isPlanContractsInverse = domainModel.getCollectionDescriptor( Plan.class.getName() + ".contracts" ) .isInverse(); try { domainModel.getCollectionDescriptor( Contract.class.getName() + ".plans" ); isPlanContractsBidirectional = true; } catch (IllegalArgumentException ex) { isPlanContractsBidirectional = false; } isPlanVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Plan.class.getName()).isVersioned(); isContractVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Contract.class.getName()).isVersioned(); sessionFactory.getStatistics().clear(); } @Test public void testUpdateProperty(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = new Plan( "plan" ); p.addContract( new Contract( null, "gail", "phone" ) ); s.persist( p ); } ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = getPlan( s ); p.setDescription( "new plan" ); assertEquals( 1, p.getContracts().size() ); Contract c = (Contract) p.getContracts().iterator().next(); c.setCustomerName( "yogi" ); } ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = getPlan( s ); assertEquals( 1, p.getContracts().size() ); Contract c = (Contract) p.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertEquals( 1, c.getPlans().size() ); assertSame( p, c.getPlans().iterator().next() ); } s.remove( p ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testCreateWithNonEmptyManyToManyCollectionOfNew(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = new Plan( "plan" ); p.addContract( new Contract( null, "gail", "phone" ) ); s.persist( p ); } ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = getPlan( s ); assertEquals( 1, p.getContracts().size() ); Contract c = (Contract) p.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertEquals( 1, c.getPlans().size() ); assertSame( p, c.getPlans().iterator().next() ); } s.remove( p ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testCreateWithNonEmptyManyToManyCollectionOfExisting(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Contract c = new Contract( null, "gail", "phone" ); scope.inTransaction( s -> s.persist( c ) ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { assertThrows(IllegalArgumentException.class, () -> s.lock( c, LockMode.NONE ), "Given entity is not associated with the persistence context" ); Plan p = new Plan( "plan" ); p.addContract( s.get(Contract.class, c.getId()) ); s.persist( p ); } ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 1, p1.getContracts().size() ); Contract c1 = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertEquals( 1, c1.getPlans().size() ); assertSame( p1, c1.getPlans().iterator().next() ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testAddNewManyToManyElementToPersistentEntity(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); scope.inTransaction( s -> { s.persist( p ); } ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = s.get( Plan.class, p.getId() ); assertEquals( 0, p.getContracts().size() ); p1.addContract( new Contract( null, "gail", "phone" ) ); } ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 1, p1.getContracts().size() ); Contract c = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertEquals( 1, c.getPlans().size() ); assertSame( p1, c.getPlans().iterator().next() ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testAddExistingManyToManyElementToPersistentEntity(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); scope.inTransaction( s -> { s.persist( p ); s.persist( c ); } ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = s.get( Plan.class, p.getId() ); assertEquals( 0, p1.getContracts().size() ); Contract c1 = s.get( Contract.class, c.getId() ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c1.getPlans().size() ); } p1.addContract( c1 ); } ); assertInsertCount( 0, sessionFactory ); assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 1, p1.getContracts().size() ); Contract c1 = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p1, c1.getPlans().iterator().next() ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testCreateWithEmptyManyToManyCollectionUpdateWithExistingElement(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); scope.inTransaction( s -> { s.persist( p ); s.persist( c ); } ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.addContract( c ); scope.inTransaction( s -> s.merge( p ) ); assertInsertCount( 0, sessionFactory ); assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 1, p1.getContracts().size() ); Contract c1 = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p1, c1.getPlans().iterator().next() ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test @Disabled("HHH-18419") public void testCreateWithNonEmptyManyToManyCollectionUpdateWithNewElement(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); Contract newC = new Contract( null, "sherman", "telepathy" ); p.addContract( newC ); scope.inTransaction( s -> s.merge( p ) ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 2, p1.getContracts().size() ); for ( Iterator it = p1.getContracts().iterator(); it.hasNext(); ) { Contract aContract = (Contract) it.next(); if ( aContract.getId() == c.getId() ) { assertEquals( "gail", aContract.getCustomerName() ); } else { assertEquals( "sherman", aContract.getCustomerName() ); } if ( isPlanContractsBidirectional ) { assertSame( p1, aContract.getPlans().iterator().next() ); } } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 3, sessionFactory ); } @Test public void testCreateWithEmptyManyToManyCollectionMergeWithExistingElement(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); scope.inTransaction( s -> { s.persist( p ); s.persist( c ); } ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.addContract( c ); scope.inTransaction( s -> s.merge( p ) ); assertInsertCount( 0, sessionFactory ); assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 1, p1.getContracts().size() ); Contract c1 = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p1, c1.getPlans().iterator().next() ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testCreateWithNonEmptyManyToManyCollectionMergeWithNewElement(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); Contract newC = new Contract( null, "yogi", "mail" ); p.addContract( newC ); scope.inTransaction( s -> s.merge( p ) ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 2, p1.getContracts().size() ); for ( Object o : p1.getContracts() ) { Contract aContract = (Contract) o; if ( aContract.getId() == c.getId() ) { assertEquals( "gail", aContract.getCustomerName() ); } else if ( !aContract.getCustomerName().equals( newC.getCustomerName() ) ) { fail( "unknown contract:" + aContract.getCustomerName() ); } if ( isPlanContractsBidirectional ) { assertSame( p1, aContract.getPlans().iterator().next() ); } } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 3, sessionFactory ); } @Test public void testRemoveManyToManyElementUsingUpdate(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.removeContract( c ); assertEquals( 0, p.getContracts().size() ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c.getPlans().size() ); } scope.inTransaction( s -> s.merge( p ) ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); assertDeleteCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); if ( isPlanContractsInverse ) { assertEquals( 1, p1.getContracts().size() ); Contract c1 = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); assertSame( p1, c1.getPlans().iterator().next() ); } else { assertEquals( 0, p1.getContracts().size() ); Contract c1 = getContract( s ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c1.getPlans().size() ); } s.remove( c1 ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testRemoveManyToManyElementUsingUpdateBothSides(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.removeContract( c ); assertEquals( 0, p.getContracts().size() ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c.getPlans().size() ); } scope.inTransaction( s -> { s.merge( p ); s.merge( c ); } ); assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0, sessionFactory ); assertDeleteCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 0, p1.getContracts().size() ); Contract c1 = getContract( s ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c1.getPlans().size() ); } s.remove( c1 ); s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testRemoveManyToManyElementUsingMerge(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.removeContract( c ); assertEquals( 0, p.getContracts().size() ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c.getPlans().size() ); } scope.inTransaction( s -> s.merge( p ) ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); assertDeleteCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); if ( isPlanContractsInverse ) { assertEquals( 1, p1.getContracts().size() ); Contract c1 = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); assertSame( p1, c1.getPlans().iterator().next() ); } else { assertEquals( 0, p1.getContracts().size() ); Contract c1 = (Contract) getContract( s ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c1.getPlans().size() ); } s.remove( c1 ); } s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testRemoveManyToManyElementUsingMergeBothSides(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.removeContract( c ); assertEquals( 0, p.getContracts().size() ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c.getPlans().size() ); } scope.inTransaction( s -> { s.merge( p ); s.merge( c ); } ); assertUpdateCount( isContractVersioned && isPlanVersioned ? 2 : 0, sessionFactory ); assertDeleteCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 0, p1.getContracts().size() ); Contract c1 = getContract( s ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c1.getPlans().size() ); } s.remove( c1 ); s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 2, sessionFactory ); } @Test public void testDeleteManyToManyElement(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan merged = s.merge( p ); Contract contract = (Contract) merged.getContracts().iterator().next(); merged.removeContract( contract ); s.remove( contract ); } ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); assertDeleteCount( 1, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 0, p1.getContracts().size() ); Contract c1 = getContract( s ); assertNull( c1 ); s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 1, sessionFactory ); } @Test public void testRemoveManyToManyElementByDelete(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract c = new Contract( null, "gail", "phone" ); p.addContract( c ); scope.inTransaction( s -> s.persist( p ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); p.removeContract( c ); assertEquals( 0, p.getContracts().size() ); if ( isPlanContractsBidirectional ) { assertEquals( 0, c.getPlans().size() ); } scope.inTransaction( s -> { s.merge( p ); s.remove( s.merge(c) ); } ); assertUpdateCount( isPlanVersioned ? 1 : 0, sessionFactory ); assertDeleteCount( 1, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 0, p1.getContracts().size() ); s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 1, sessionFactory ); } @Test public void testManyToManyCollectionOptimisticLockingWithMerge(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan pOrig = new Plan( "plan" ); Contract cOrig = new Contract( null, "gail", "phone" ); pOrig.addContract( cOrig ); scope.inTransaction( s -> s.persist( pOrig ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = s.get( Plan.class, pOrig.getId() ); Contract newC = new Contract( null, "sherman", "note" ); p.addContract( newC ); } ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inSession( s -> { pOrig.removeContract( cOrig ); try { s.merge( pOrig ); assertFalse( isContractVersioned ); } catch (PersistenceException ex) { assertTyping( StaleObjectStateException.class, ex.getCause() ); assertTrue( isContractVersioned ); } finally { s.getTransaction().rollback(); } } ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); s.remove( p1 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 3, sessionFactory ); } @Test public void testManyToManyCollectionOptimisticLockingWithUpdate(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan pOrig = new Plan( "plan" ); Contract cOrig = new Contract( null, "gail", "phone" ); pOrig.addContract( cOrig ); scope.inTransaction( s -> s.persist( pOrig ) ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p = s.get( Plan.class, pOrig.getId() ); Contract newC = new Contract( null, "yogi", "pawprint" ); p.addContract( newC ); } ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isContractVersioned ? 1 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inSession( s -> { s.beginTransaction(); pOrig.removeContract( cOrig ); try { s.merge( pOrig ); s.getTransaction().commit(); assertFalse( isContractVersioned ); } catch (PersistenceException ex) { s.getTransaction().rollback(); assertTrue( isContractVersioned ); assertTyping( StaleObjectStateException.class, ex.getCause() ); } } ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); s.remove( p1 ); s.createMutationQuery( "delete from Contract" ).executeUpdate(); assertAllPlansAndContractsAreDeleted( s ); } ); } @Test public void testMoveManyToManyElementToNewEntityCollection(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); scope.inTransaction( s -> { p.addContract( new Contract( null, "gail", "phone" ) ); s.persist( p ); } ); assertInsertCount( 2, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); Plan p2 = new Plan( "new plan" ); scope.inTransaction( s -> { Plan p1 = getPlan( s ); assertEquals( 1, p1.getContracts().size() ); Contract c = (Contract) p1.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p1, c.getPlans().iterator().next() ); } p1.removeContract( c ); p2.addContract( c ); s.persist( p2 ); } ); assertInsertCount( 1, sessionFactory ); assertUpdateCount( isPlanVersioned && isContractVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p3 = getPlan( s, p.getId() ); Plan p4 = getPlan( s, p2.getId() ); /* if ( isPlanContractsInverse ) { assertEquals( 1, p1.getContracts().size() ); c = ( Contract ) p1.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p1, c.getPlans().iterator().next() ); } assertEquals( 0, p2.getContracts().size() ); } else { */ assertEquals( 0, p3.getContracts().size() ); assertEquals( 1, p4.getContracts().size() ); Contract c = (Contract) p4.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p4, c.getPlans().iterator().next() ); } //} s.remove( p3 ); s.remove( p4 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 3, sessionFactory ); } @Test public void testMoveManyToManyElementToExistingEntityCollection(SessionFactoryScope scope) { SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); clearCounts( sessionFactory ); Plan p = new Plan( "plan" ); Contract contract = new Contract( null, "gail", "phone" ); p.addContract( contract ); Plan p2 = new Plan( "plan2" ); scope.inTransaction( s -> { s.persist( p ); s.persist( p2 ); } ); assertInsertCount( 3, sessionFactory ); assertUpdateCount( 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p3 = getPlan( s, p.getId() ); assertEquals( 1, p3.getContracts().size() ); Contract c = (Contract) p3.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p3, c.getPlans().iterator().next() ); } p3.removeContract( c ); } ); assertInsertCount( 0, sessionFactory ); assertUpdateCount( isPlanVersioned && isContractVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p3 = getPlan( s, p2.getId() ); Contract c1 = getContract( s, contract.getId() ); p3.addContract( c1 ); } ); assertInsertCount( 0, sessionFactory ); assertUpdateCount( isPlanVersioned && isContractVersioned ? 2 : 0, sessionFactory ); clearCounts( sessionFactory ); scope.inTransaction( s -> { Plan p3 = getPlan( s, p.getId() ); Plan p4 = getPlan( s, p2.getId() ); /* if ( isPlanContractsInverse ) { assertEquals( 1, p3.getContracts().size() ); c = ( Contract ) p3.getContracts().iterator().next(); assertEquals( "gail", c.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p3, c.getPlans().iterator().next() ); } assertEquals( 0, p4.getContracts().size() ); } else { */ assertEquals( 0, p3.getContracts().size() ); assertEquals( 1, p4.getContracts().size() ); Contract c1 = (Contract) p4.getContracts().iterator().next(); assertEquals( "gail", c1.getCustomerName() ); if ( isPlanContractsBidirectional ) { assertSame( p4, c1.getPlans().iterator().next() ); } //} s.remove( p3 ); s.remove( p4 ); assertAllPlansAndContractsAreDeleted( s ); } ); assertUpdateCount( 0, sessionFactory ); assertDeleteCount( 3, sessionFactory ); } private void assertAllPlansAndContractsAreDeleted(SessionImplementor s) { assertEquals( new Long( 0 ), getPlanRowCount( s ) ); assertEquals( new Long( 0 ), getContractRowCount( s ) ); } private Plan getPlan(SessionImplementor s) { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Plan> criteria = criteriaBuilder.createQuery( Plan.class ); criteria.from( Plan.class ); return s.createQuery( criteria ).uniqueResult(); } private Plan getPlan(SessionImplementor s, long id) { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Plan> criteria = criteriaBuilder.createQuery( Plan.class ); Root<Plan> root = criteria.from( Plan.class ); criteria.where( criteriaBuilder.equal( root.get( "id" ), id ) ); return s.createQuery( criteria ).uniqueResult(); } private Contract getContract(SessionImplementor s) { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Contract> criteria = criteriaBuilder.createQuery( Contract.class ); criteria.from( Contract.class ); return s.createQuery( criteria ).uniqueResult(); } private Contract getContract(SessionImplementor s, long id) { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Contract> criteria = criteriaBuilder.createQuery( Contract.class ); Root<Contract> root = criteria.from( Contract.class ); criteria.where( criteriaBuilder.equal( root.get( "id" ), id ) ); return s.createQuery( criteria ).uniqueResult(); } private Long getPlanRowCount(SessionImplementor s) { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Long> criteriaPlanRowCount = criteriaBuilder.createQuery( Long.class ); criteriaPlanRowCount.select( criteriaBuilder.count( criteriaPlanRowCount.from( Plan.class ) ) ); return s.createQuery( criteriaPlanRowCount ).uniqueResult(); } private Long getContractRowCount(SessionImplementor s) { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Long> criteriaContractRowCount = criteriaBuilder.createQuery( Long.class ); criteriaContractRowCount.select( criteriaBuilder.count( criteriaContractRowCount.from( Contract.class ) ) ); return s.createQuery( criteriaContractRowCount ).uniqueResult(); } protected void clearCounts(SessionFactoryImplementor sessionFactory) { sessionFactory.getStatistics().clear(); } protected void assertInsertCount(int expected, SessionFactoryImplementor sessionFactory) { int inserts = (int) sessionFactory.getStatistics().getEntityInsertCount(); assertEquals( expected, inserts, "unexpected insert count" ); } protected void assertUpdateCount(int expected, SessionFactoryImplementor sessionFactory) { int updates = (int) sessionFactory.getStatistics().getEntityUpdateCount(); assertEquals( expected, updates, "unexpected update counts" ); } protected void assertDeleteCount(int expected, SessionFactoryImplementor sessionFactory) { int deletes = (int) sessionFactory.getStatistics().getEntityDeleteCount(); assertEquals( expected, deletes, "unexpected delete counts, expected " + expected + " but got " + deletes ); } }
apache/ignite-3
36,966
modules/network/src/test/java/org/apache/ignite/internal/network/netty/RecoveryHandshakeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.network.netty; import static org.apache.ignite.internal.network.utils.ClusterServiceTestUtils.defaultSerializationRegistry; import static org.apache.ignite.internal.testframework.IgniteTestUtils.getFieldValue; import static org.apache.ignite.internal.util.CollectionUtils.nullOrEmpty; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import io.netty.buffer.ByteBuf; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.util.concurrent.AbstractScheduledEventExecutor; import java.util.Collections; import java.util.Queue; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import org.apache.ignite.internal.configuration.testframework.ConfigurationExtension; import org.apache.ignite.internal.configuration.testframework.InjectConfiguration; import org.apache.ignite.internal.network.ClusterIdSupplier; import org.apache.ignite.internal.network.ClusterNodeImpl; import org.apache.ignite.internal.network.ConstantClusterIdSupplier; import org.apache.ignite.internal.network.NetworkMessage; import org.apache.ignite.internal.network.NetworkMessagesFactory; import org.apache.ignite.internal.network.OutNetworkObject; import org.apache.ignite.internal.network.configuration.AckConfiguration; import org.apache.ignite.internal.network.handshake.HandshakeManager; import org.apache.ignite.internal.network.handshake.NoOpHandshakeEventLoopSwitcher; import org.apache.ignite.internal.network.messages.TestMessage; import org.apache.ignite.internal.network.messages.TestMessagesFactory; import org.apache.ignite.internal.network.recovery.AllIdsAreFresh; import org.apache.ignite.internal.network.recovery.AllIdsAreStale; import org.apache.ignite.internal.network.recovery.RecoveryAcceptorHandshakeManager; import org.apache.ignite.internal.network.recovery.RecoveryDescriptor; import org.apache.ignite.internal.network.recovery.RecoveryDescriptorProvider; import org.apache.ignite.internal.network.recovery.RecoveryInitiatorHandshakeManager; import org.apache.ignite.internal.network.recovery.StaleIdDetector; import org.apache.ignite.internal.network.serialization.ClassDescriptorFactory; import org.apache.ignite.internal.network.serialization.ClassDescriptorRegistry; import org.apache.ignite.internal.network.serialization.MessageSerializationRegistry; import org.apache.ignite.internal.network.serialization.PerSessionSerializationService; import org.apache.ignite.internal.network.serialization.SerializationService; import org.apache.ignite.internal.network.serialization.UserObjectSerializationContext; import org.apache.ignite.internal.network.serialization.marshal.DefaultUserObjectMarshaller; import org.apache.ignite.internal.testframework.BaseIgniteAbstractTest; import org.apache.ignite.internal.testframework.IgniteTestUtils; import org.apache.ignite.internal.version.DefaultIgniteProductVersionSource; import org.apache.ignite.network.NetworkAddress; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; /** * Recovery protocol handshake flow test. */ @ExtendWith(ConfigurationExtension.class) public class RecoveryHandshakeTest extends BaseIgniteAbstractTest { /** Connection id. */ private static final short CONNECTION_ID = 1337; private static final UUID LOWER_UUID = new UUID(100, 200); private static final UUID HIGHER_UUID = new UUID(300, 400); private static final String INITIATOR = "initiator"; private static final String ACCEPTOR = "acceptor"; private static final String ACCEPTOR_HOST = "acceptor-host"; private static final String INITIATOR_HOST = "initiator-host"; private static final int PORT = 1000; /** Serialization registry. */ private static final MessageSerializationRegistry MESSAGE_REGISTRY = defaultSerializationRegistry(); /** Message factory. */ private static final NetworkMessagesFactory MESSAGE_FACTORY = new NetworkMessagesFactory(); /** Test message factory. */ private static final TestMessagesFactory TEST_MESSAGES_FACTORY = new TestMessagesFactory(); private final ClusterIdSupplier clusterIdSupplier = new ConstantClusterIdSupplier(UUID.randomUUID()); @InjectConfiguration private AckConfiguration ackConfiguration; @Test public void testHandshake() throws Exception { RecoveryDescriptorProvider initiatorRecovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider acceptorRecovery = createRecoveryDescriptorProvider(); EmbeddedChannel initiatorSideChannel = createUnregisteredChannel(); EmbeddedChannel acceptorSideChannel = createUnregisteredChannel(); RecoveryInitiatorHandshakeManager initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( initiatorRecovery ); RecoveryAcceptorHandshakeManager acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( acceptorRecovery ); setupChannel(initiatorSideChannel, initiatorHandshakeManager, noMessageListener); setupChannel(acceptorSideChannel, acceptorHandshakeManager, noMessageListener); assertTrue(acceptorSideChannel.isActive()); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); assertNull(initiatorSideChannel.readOutbound()); assertNull(acceptorSideChannel.readOutbound()); checkHandshakeCompleted(acceptorHandshakeManager); checkHandshakeCompleted(initiatorHandshakeManager); checkPipelineAfterHandshake(acceptorSideChannel); checkPipelineAfterHandshake(initiatorSideChannel); assertFalse(acceptorSideChannel.finish()); assertFalse(initiatorSideChannel.finish()); } @Test public void testHandshakeWithUnacknowledgedAcceptorMessage() throws Exception { RecoveryDescriptorProvider initiatorRecovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider acceptorRecovery = createRecoveryDescriptorProvider(); EmbeddedChannel initiatorSideChannel = createUnregisteredChannel(); EmbeddedChannel acceptorSideChannel = createUnregisteredChannel(); UUID initiatorLaunchId = UUID.randomUUID(); RecoveryDescriptor acceptorRecoveryDescriptor = acceptorRecovery.getRecoveryDescriptor( INITIATOR, initiatorLaunchId, CONNECTION_ID ); addUnacknowledgedMessages(acceptorRecoveryDescriptor); RecoveryInitiatorHandshakeManager initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( INITIATOR, initiatorLaunchId, initiatorRecovery ); RecoveryAcceptorHandshakeManager acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( acceptorRecovery ); var messageCaptor = new AtomicReference<TestMessage>(); setupChannel(initiatorSideChannel, initiatorHandshakeManager, (inObject) -> { NetworkMessage msg = inObject.message(); assertInstanceOf(TestMessage.class, msg); messageCaptor.set((TestMessage) msg); }); setupChannel(acceptorSideChannel, acceptorHandshakeManager, noMessageListener); assertTrue(acceptorSideChannel.isActive()); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); assertNull(initiatorSideChannel.readOutbound()); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); assertNull(acceptorSideChannel.readOutbound()); TestMessage ackedMessage = messageCaptor.get(); assertNotNull(ackedMessage); checkHandshakeNotCompleted(acceptorHandshakeManager); checkHandshakeCompleted(initiatorHandshakeManager); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); checkHandshakeCompleted(acceptorHandshakeManager); checkHandshakeCompleted(initiatorHandshakeManager); checkPipelineAfterHandshake(acceptorSideChannel); checkPipelineAfterHandshake(initiatorSideChannel); assertFalse(acceptorSideChannel.finish()); assertFalse(initiatorSideChannel.finish()); } @Test public void testHandshakeWithUnacknowledgedInitiatorMessage() throws Exception { RecoveryDescriptorProvider initiatorRecovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider acceptorRecovery = createRecoveryDescriptorProvider(); EmbeddedChannel initiatorSideChannel = createUnregisteredChannel(); EmbeddedChannel acceptorSideChannel = createUnregisteredChannel(); UUID acceptorLaunchId = UUID.randomUUID(); RecoveryDescriptor initiatorRecoveryDescriptor = initiatorRecovery.getRecoveryDescriptor( ACCEPTOR, acceptorLaunchId, CONNECTION_ID ); addUnacknowledgedMessages(initiatorRecoveryDescriptor); RecoveryInitiatorHandshakeManager initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( initiatorRecovery ); RecoveryAcceptorHandshakeManager acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( ACCEPTOR, acceptorLaunchId, acceptorRecovery ); var messageCaptor = new AtomicReference<TestMessage>(); setupChannel(initiatorSideChannel, initiatorHandshakeManager, noMessageListener); setupChannel(acceptorSideChannel, acceptorHandshakeManager, (inObject) -> { NetworkMessage msg = inObject.message(); assertInstanceOf(TestMessage.class, msg); messageCaptor.set((TestMessage) msg); }); assertTrue(acceptorSideChannel.isActive()); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); assertNull(acceptorSideChannel.readOutbound()); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); assertNull(initiatorSideChannel.readOutbound()); TestMessage ackedMessage = messageCaptor.get(); assertNotNull(ackedMessage); checkHandshakeCompleted(acceptorHandshakeManager); checkHandshakeNotCompleted(initiatorHandshakeManager); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); checkHandshakeCompleted(acceptorHandshakeManager); checkHandshakeCompleted(initiatorHandshakeManager); checkPipelineAfterHandshake(acceptorSideChannel); checkPipelineAfterHandshake(initiatorSideChannel); assertFalse(acceptorSideChannel.finish()); assertFalse(initiatorSideChannel.finish()); } @Test public void testPairedRecoveryDescriptorsClinch() throws Exception { RecoveryDescriptorProvider node1Recovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider node2Recovery = createRecoveryDescriptorProvider(); EmbeddedChannel channel1Src = createUnregisteredChannel(); EmbeddedChannel channel1Dst = createUnregisteredChannel(); EmbeddedChannel channel2Src = createUnregisteredChannel(); EmbeddedChannel channel2Dst = createUnregisteredChannel(); UUID node1Uuid = LOWER_UUID; UUID node2Uuid = HIGHER_UUID; RecoveryInitiatorHandshakeManager chm1 = createRecoveryInitiatorHandshakeManager( INITIATOR, node1Uuid, node1Recovery ); RecoveryAcceptorHandshakeManager shm1 = createRecoveryAcceptorHandshakeManager(INITIATOR, node1Uuid, node1Recovery); RecoveryInitiatorHandshakeManager chm2 = createRecoveryInitiatorHandshakeManager(ACCEPTOR, node2Uuid, node2Recovery); RecoveryAcceptorHandshakeManager shm2 = createRecoveryAcceptorHandshakeManager(ACCEPTOR, node2Uuid, node2Recovery); // Channel opened from node1 to node2 is channel 1. // Channel opened from node2 to node1 is channel 2. // Channel 1. setupChannel(channel1Src, chm1, noMessageListener); setupChannel(channel1Dst, shm2, noMessageListener); // Channel 2. setupChannel(channel2Src, chm2, noMessageListener); setupChannel(channel2Dst, shm1, noMessageListener); exchangeInitiatorToAcceptor(channel2Dst, channel2Src); exchangeInitiatorToAcceptor(channel1Dst, channel1Src); exchangeAcceptorToInitiator(channel2Dst, channel2Src); exchangeAcceptorToInitiator(channel1Dst, channel1Src); exchangeInitiatorToAcceptor(channel2Dst, channel2Src); exchangeInitiatorToAcceptor(channel1Dst, channel1Src); // 2 -> 1 (Channel 2) is alive, while 1 -> 2 (Channel 1) closes because of the tie-breaking. exchangeAcceptorToInitiator(channel1Dst, channel1Src); exchangeAcceptorToInitiator(channel2Dst, channel2Src); assertFalse(channel1Src.isOpen()); assertFalse(channel1Dst.isOpen()); assertTrue(channel2Src.isOpen()); assertTrue(channel2Dst.isOpen()); assertFalse(channel1Src.finish()); assertFalse(channel2Dst.finish()); assertFalse(channel2Src.finish()); assertFalse(channel1Dst.finish()); } /** * This tests the following scenario: two handshakes in the opposite directions are started, * Handshake 1 is faster and it takes both initiator-side and acceptor-side locks (using recovery descriptors * as locks), and only then Handshake 2 tries to take the first lock (the one on the initiator side). * In such a situation, tie-breaking logic should not be applied (as Handshake 1 could have already * established, or almost established, a logical connection); instead, Handshake 2 must stop * itself (regardless of what that the Tie Breaker would prescribe). */ @ParameterizedTest @ValueSource(booleans = {false, true}) public void testLateHandshakeDoesNotUseTieBreaker(boolean node1LaunchIdIsLower) throws Exception { RecoveryDescriptorProvider node1Recovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider node2Recovery = createRecoveryDescriptorProvider(); EmbeddedChannel channel1Src = createUnregisteredChannel(); EmbeddedChannel channel1Dst = createUnregisteredChannel(); EmbeddedChannel channel2Src = createUnregisteredChannel(); EmbeddedChannel channel2Dst = createUnregisteredChannel(); UUID node1Uuid = node1LaunchIdIsLower ? LOWER_UUID : HIGHER_UUID; UUID node2Uuid = node1LaunchIdIsLower ? HIGHER_UUID : LOWER_UUID; RecoveryInitiatorHandshakeManager chm1 = createRecoveryInitiatorHandshakeManager( INITIATOR, node1Uuid, node1Recovery ); RecoveryAcceptorHandshakeManager shm1 = createRecoveryAcceptorHandshakeManager(INITIATOR, node1Uuid, node1Recovery); RecoveryInitiatorHandshakeManager chm2 = createRecoveryInitiatorHandshakeManager(ACCEPTOR, node2Uuid, node2Recovery); RecoveryAcceptorHandshakeManager shm2 = createRecoveryAcceptorHandshakeManager(ACCEPTOR, node2Uuid, node2Recovery); // Channel opened from node1 to node2 is channel 1. // Channel opened from node2 to node1 is channel 2. // Channel 1. setupChannel(channel1Src, chm1, noMessageListener); setupChannel(channel1Dst, shm2, noMessageListener); // Channel 2. setupChannel(channel2Src, chm2, noMessageListener); setupChannel(channel2Dst, shm1, noMessageListener); // Channel 2's handshake acquires both locks. exchangeInitiatorToAcceptor(channel2Dst, channel2Src); exchangeAcceptorToInitiator(channel2Dst, channel2Src); exchangeInitiatorToAcceptor(channel2Dst, channel2Src); // Now Channel 1's handshake cannot acquire even first lock. exchangeInitiatorToAcceptor(channel1Dst, channel1Src); exchangeAcceptorToInitiator(channel1Dst, channel1Src); // 2 -> 1 is alive, while 1 -> 2 closes because it is late. exchangeAcceptorToInitiator(channel2Dst, channel2Src); assertFalse(channel1Src.isOpen()); assertTrue(channel2Src.isOpen()); assertTrue(channel2Dst.isOpen()); assertFalse(channel1Src.finish()); assertFalse(channel2Dst.finish()); assertFalse(channel2Src.finish()); assertFalse(channel1Dst.finish()); } @Test public void testExactlyOnceAcceptor() throws Exception { testExactlyOnce(true); } @Test public void testExactlyOnceInitiator() throws Exception { testExactlyOnce(false); } /** * Tests that message was received exactly once in case of network failure during acknowledgement. * * @param acceptorDidntReceiveAck {@code true} if acceptor didn't receive the acknowledgement, {@code false} if initiator didn't receive * the acknowledgement. * @throws Exception If failed. */ private void testExactlyOnce(boolean acceptorDidntReceiveAck) throws Exception { var acceptor = ACCEPTOR; UUID acceptorLaunchId = UUID.randomUUID(); var initiator = INITIATOR; UUID initiatorLaunchId = UUID.randomUUID(); RecoveryDescriptorProvider initiatorRecovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider acceptorRecovery = createRecoveryDescriptorProvider(); EmbeddedChannel initiatorSideChannel = createUnregisteredChannel(); EmbeddedChannel acceptorSideChannel = createUnregisteredChannel(); RecoveryInitiatorHandshakeManager initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( initiator, initiatorLaunchId, initiatorRecovery ); RecoveryAcceptorHandshakeManager acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( acceptor, acceptorLaunchId, acceptorRecovery ); var receivedFirst = new AtomicBoolean(); var listener1 = new MessageListener("1", receivedFirst); setupChannel(initiatorSideChannel, initiatorHandshakeManager, acceptorDidntReceiveAck ? listener1 : noMessageListener); setupChannel(acceptorSideChannel, acceptorHandshakeManager, acceptorDidntReceiveAck ? noMessageListener : listener1); // Normal handshake exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); EmbeddedChannel ch = acceptorDidntReceiveAck ? acceptorSideChannel : initiatorSideChannel; // Add two messages to the outbound ch.writeOutbound(new OutNetworkObject(TEST_MESSAGES_FACTORY.testMessage().msg("1").build(), Collections.emptyList())); ch.writeOutbound(new OutNetworkObject(TEST_MESSAGES_FACTORY.testMessage().msg("2").build(), Collections.emptyList())); // Send one of the messages if (acceptorDidntReceiveAck) { exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); } else { exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); } // Message should be received assertTrue(receivedFirst.get()); // Transfer only one acknowledgement, don't transfer the second one (simulates network failure on acknowledgement) if (acceptorDidntReceiveAck) { exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); } else { exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); } // Simulate reconnection initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( initiator, initiatorLaunchId, initiatorRecovery ); acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( acceptor, acceptorLaunchId, acceptorRecovery ); var receivedSecond = new AtomicBoolean(); var listener2 = new MessageListener("2", receivedSecond); initiatorSideChannel.finishAndReleaseAll(); acceptorSideChannel.finishAndReleaseAll(); initiatorSideChannel = createUnregisteredChannel(); acceptorSideChannel = createUnregisteredChannel(); setupChannel(initiatorSideChannel, initiatorHandshakeManager, acceptorDidntReceiveAck ? listener2 : noMessageListener); setupChannel(acceptorSideChannel, acceptorHandshakeManager, acceptorDidntReceiveAck ? noMessageListener : listener2); // Handshake exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); // Resending message if (acceptorDidntReceiveAck) { exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); } else { exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); } // Send another acknowledgement if (acceptorDidntReceiveAck) { exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); } else { exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); } assertNull(acceptorSideChannel.readOutbound()); assertNull(initiatorSideChannel.readOutbound()); assertTrue(receivedSecond.get()); assertFalse(acceptorSideChannel.finish()); assertFalse(initiatorSideChannel.finish()); } @Test public void acceptorFailsHandshakeIfInitiatorIdIsAlreadySeen() throws Exception { RecoveryDescriptorProvider initiatorRecovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider acceptorRecovery = createRecoveryDescriptorProvider(); EmbeddedChannel initiatorSideChannel = createUnregisteredChannel(); EmbeddedChannel acceptorSideChannel = createUnregisteredChannel(); RecoveryInitiatorHandshakeManager initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( initiatorRecovery ); RecoveryAcceptorHandshakeManager acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( ACCEPTOR, UUID.randomUUID(), acceptorRecovery, new AllIdsAreStale() ); setupChannel(initiatorSideChannel, initiatorHandshakeManager, noMessageListener); setupChannel(acceptorSideChannel, acceptorHandshakeManager, noMessageListener); assertTrue(acceptorSideChannel.isActive()); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); assertNull(initiatorSideChannel.readOutbound()); assertNull(acceptorSideChannel.readOutbound()); checkHandshakeCompletedExceptionally(acceptorHandshakeManager); checkHandshakeCompletedExceptionally(initiatorHandshakeManager); checkPipelineAfterHandshake(acceptorSideChannel); checkPipelineAfterHandshake(initiatorSideChannel); assertFalse(acceptorSideChannel.finish()); assertFalse(initiatorSideChannel.finish()); } @Test public void initiatorFailsHandshakeIfAcceptorIdIsAlreadySeen() throws Exception { RecoveryDescriptorProvider initiatorRecovery = createRecoveryDescriptorProvider(); RecoveryDescriptorProvider acceptorRecovery = createRecoveryDescriptorProvider(); EmbeddedChannel initiatorSideChannel = createUnregisteredChannel(); EmbeddedChannel acceptorSideChannel = createUnregisteredChannel(); RecoveryInitiatorHandshakeManager initiatorHandshakeManager = createRecoveryInitiatorHandshakeManager( INITIATOR, UUID.randomUUID(), initiatorRecovery, new AllIdsAreStale() ); RecoveryAcceptorHandshakeManager acceptorHandshakeManager = createRecoveryAcceptorHandshakeManager( acceptorRecovery ); setupChannel(initiatorSideChannel, initiatorHandshakeManager, noMessageListener); setupChannel(acceptorSideChannel, acceptorHandshakeManager, noMessageListener); assertTrue(acceptorSideChannel.isActive()); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); exchangeAcceptorToInitiator(acceptorSideChannel, initiatorSideChannel); exchangeInitiatorToAcceptor(acceptorSideChannel, initiatorSideChannel); assertNull(initiatorSideChannel.readOutbound()); assertNull(acceptorSideChannel.readOutbound()); checkHandshakeCompletedExceptionally(acceptorHandshakeManager); checkHandshakeCompletedExceptionally(initiatorHandshakeManager); checkPipelineAfterHandshake(acceptorSideChannel); checkPipelineAfterHandshake(initiatorSideChannel); assertFalse(acceptorSideChannel.finish()); assertFalse(initiatorSideChannel.finish()); } /** Message listener that accepts a specific message only once. */ private static class MessageListener implements Consumer<InNetworkObject> { /** Expected message. */ private final String expectedMessage; /** Flag indicating that expected messages was received. */ private final AtomicBoolean flag; private MessageListener(String expectedMessage, AtomicBoolean flag) { this.expectedMessage = expectedMessage; this.flag = flag; } /** {@inheritDoc} */ @Override public void accept(InNetworkObject inNetworkObject) { TestMessage msg = (TestMessage) inNetworkObject.message(); if (expectedMessage.equals(msg.msg())) { if (!flag.compareAndSet(false, true)) { fail(); } return; } fail(); } } private void checkPipelineAfterHandshake(EmbeddedChannel channel) { assertNull(channel.pipeline().get(HandshakeHandler.NAME)); } private void checkHandshakeNotCompleted(HandshakeManager manager) { CompletableFuture<NettySender> localHandshakeFuture = manager.localHandshakeFuture(); assertFalse(localHandshakeFuture.isDone()); assertFalse(localHandshakeFuture.isCompletedExceptionally()); assertFalse(localHandshakeFuture.isCancelled()); CompletableFuture<NettySender> finalHandshakeFuture = manager.finalHandshakeFuture().toCompletableFuture(); assertFalse(finalHandshakeFuture.isDone()); assertFalse(finalHandshakeFuture.isCompletedExceptionally()); assertFalse(finalHandshakeFuture.isCancelled()); } private void checkHandshakeCompleted(HandshakeManager manager) { CompletableFuture<NettySender> localHandshakeFuture = manager.localHandshakeFuture(); assertTrue(localHandshakeFuture.isDone()); assertFalse(localHandshakeFuture.isCompletedExceptionally()); assertFalse(localHandshakeFuture.isCancelled()); CompletableFuture<NettySender> finalHandshakeFuture = manager.finalHandshakeFuture().toCompletableFuture(); assertTrue(finalHandshakeFuture.isDone()); assertFalse(finalHandshakeFuture.isCompletedExceptionally()); assertFalse(finalHandshakeFuture.isCancelled()); } private void checkHandshakeCompletedExceptionally(HandshakeManager manager) { CompletableFuture<NettySender> handshakeFuture = manager.localHandshakeFuture(); assertTrue(handshakeFuture.isDone()); assertTrue(handshakeFuture.isCompletedExceptionally()); assertFalse(handshakeFuture.isCancelled()); CompletableFuture<NettySender> finalHandshakeFuture = manager.finalHandshakeFuture().toCompletableFuture(); assertTrue(finalHandshakeFuture.isDone()); assertTrue(finalHandshakeFuture.isCompletedExceptionally()); assertFalse(finalHandshakeFuture.isCancelled()); } private void addUnacknowledgedMessages(RecoveryDescriptor recoveryDescriptor) { TestMessage msg = TEST_MESSAGES_FACTORY.testMessage().msg("test").build(); recoveryDescriptor.add(new OutNetworkObject(msg, Collections.emptyList())); } private void exchangeAcceptorToInitiator(EmbeddedChannel acceptorSideChannel, EmbeddedChannel initiatorSideChannel) { runPendingTasks(acceptorSideChannel, initiatorSideChannel); ByteBuf outgoingMessageBuffer = acceptorSideChannel.readOutbound(); // No need to release buffer because inbound buffers are released by InboundDecoder initiatorSideChannel.writeInbound(outgoingMessageBuffer); } private void exchangeInitiatorToAcceptor(EmbeddedChannel acceptorSideChannel, EmbeddedChannel initiatorSideChannel) { runPendingTasks(acceptorSideChannel, initiatorSideChannel); ByteBuf outgoingMessageBuffer = initiatorSideChannel.readOutbound(); // No need to release buffer because inbound buffers are released by InboundDecoder acceptorSideChannel.writeInbound(outgoingMessageBuffer); } private void runPendingTasks(EmbeddedChannel channel1, EmbeddedChannel channel2) { Queue<?> evtLoop1Queue = getFieldValue(channel1.eventLoop(), AbstractScheduledEventExecutor.class, "scheduledTaskQueue"); Queue<?> evtLoop2Queue = getFieldValue(channel2.eventLoop(), AbstractScheduledEventExecutor.class, "scheduledTaskQueue"); try { assertTrue(IgniteTestUtils.waitForCondition(() -> { channel1.runPendingTasks(); channel2.runPendingTasks(); return nullOrEmpty(evtLoop1Queue) && nullOrEmpty(evtLoop2Queue); }, 10_000)); } catch (InterruptedException e) { throw new RuntimeException(e); } } private final Consumer<InNetworkObject> noMessageListener = inNetworkObject -> fail("Received message while shouldn't have, [" + inNetworkObject.message() + "]"); private void setupChannel(EmbeddedChannel channel, HandshakeManager handshakeManager, Consumer<InNetworkObject> messageListener) throws Exception { var serializationService = new SerializationService(MESSAGE_REGISTRY, createUserObjectSerializationContext()); var sessionSerializationService = new PerSessionSerializationService(serializationService); PipelineUtils.setup(channel.pipeline(), sessionSerializationService, handshakeManager, messageListener); channel.register(); } private static EmbeddedChannel createUnregisteredChannel() { // Channel should not be registered at first, not before we add pipeline handlers // Otherwise, events like "channel active" won't be propagated to the handlers return new EmbeddedChannel(false, false); } private UserObjectSerializationContext createUserObjectSerializationContext() { var userObjectDescriptorRegistry = new ClassDescriptorRegistry(); var userObjectDescriptorFactory = new ClassDescriptorFactory(userObjectDescriptorRegistry); var userObjectMarshaller = new DefaultUserObjectMarshaller(userObjectDescriptorRegistry, userObjectDescriptorFactory); return new UserObjectSerializationContext(userObjectDescriptorRegistry, userObjectDescriptorFactory, userObjectMarshaller); } private RecoveryInitiatorHandshakeManager createRecoveryInitiatorHandshakeManager( RecoveryDescriptorProvider provider ) { return createRecoveryInitiatorHandshakeManager(INITIATOR, UUID.randomUUID(), provider); } private RecoveryInitiatorHandshakeManager createRecoveryInitiatorHandshakeManager( String consistentId, UUID launchId, RecoveryDescriptorProvider provider ) { return createRecoveryInitiatorHandshakeManager(consistentId, launchId, provider, new AllIdsAreFresh()); } private RecoveryInitiatorHandshakeManager createRecoveryInitiatorHandshakeManager( String consistentId, UUID launchId, RecoveryDescriptorProvider provider, StaleIdDetector staleIdDetector ) { return new RecoveryInitiatorHandshakeManager( new ClusterNodeImpl(launchId, consistentId, new NetworkAddress(INITIATOR_HOST, PORT)), CONNECTION_ID, provider, new NoOpHandshakeEventLoopSwitcher(), staleIdDetector, clusterIdSupplier, channel -> {}, () -> false, new DefaultIgniteProductVersionSource(), ackConfiguration ); } private RecoveryAcceptorHandshakeManager createRecoveryAcceptorHandshakeManager( RecoveryDescriptorProvider provider ) { return createRecoveryAcceptorHandshakeManager(ACCEPTOR, UUID.randomUUID(), provider); } private RecoveryAcceptorHandshakeManager createRecoveryAcceptorHandshakeManager( String consistentId, UUID launchId, RecoveryDescriptorProvider provider ) { return createRecoveryAcceptorHandshakeManager(consistentId, launchId, provider, new AllIdsAreFresh()); } private RecoveryAcceptorHandshakeManager createRecoveryAcceptorHandshakeManager( String consistentId, UUID launchId, RecoveryDescriptorProvider provider, StaleIdDetector staleIdDetector ) { return new RecoveryAcceptorHandshakeManager( new ClusterNodeImpl(launchId, consistentId, new NetworkAddress(ACCEPTOR_HOST, PORT)), MESSAGE_FACTORY, provider, new NoOpHandshakeEventLoopSwitcher(), staleIdDetector, clusterIdSupplier, channel -> {}, () -> false, new DefaultIgniteProductVersionSource(), ackConfiguration ); } private RecoveryDescriptorProvider createRecoveryDescriptorProvider() { return new DefaultRecoveryDescriptorProvider(); } }
googleads/google-ads-java
36,735
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/MoveManagerLinkRequest.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/services/customer_manager_link_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.services; /** * <pre> * Request message for * [CustomerManagerLinkService.MoveManagerLink][google.ads.googleads.v19.services.CustomerManagerLinkService.MoveManagerLink]. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.MoveManagerLinkRequest} */ public final class MoveManagerLinkRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.MoveManagerLinkRequest) MoveManagerLinkRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MoveManagerLinkRequest.newBuilder() to construct. private MoveManagerLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MoveManagerLinkRequest() { customerId_ = ""; previousCustomerManagerLink_ = ""; newManager_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MoveManagerLinkRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_MoveManagerLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.MoveManagerLinkRequest.class, com.google.ads.googleads.v19.services.MoveManagerLinkRequest.Builder.class); } public static final int CUSTOMER_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ @java.lang.Override public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PREVIOUS_CUSTOMER_MANAGER_LINK_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object previousCustomerManagerLink_ = ""; /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The previousCustomerManagerLink. */ @java.lang.Override public java.lang.String getPreviousCustomerManagerLink() { java.lang.Object ref = previousCustomerManagerLink_; 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(); previousCustomerManagerLink_ = s; return s; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for previousCustomerManagerLink. */ @java.lang.Override public com.google.protobuf.ByteString getPreviousCustomerManagerLinkBytes() { java.lang.Object ref = previousCustomerManagerLink_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); previousCustomerManagerLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NEW_MANAGER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object newManager_ = ""; /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The newManager. */ @java.lang.Override public java.lang.String getNewManager() { java.lang.Object ref = newManager_; 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(); newManager_ = s; return s; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for newManager. */ @java.lang.Override public com.google.protobuf.ByteString getNewManagerBytes() { java.lang.Object ref = newManager_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newManager_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_ = false; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(previousCustomerManagerLink_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, previousCustomerManagerLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(newManager_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, newManager_); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(previousCustomerManagerLink_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, previousCustomerManagerLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(newManager_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, newManager_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v19.services.MoveManagerLinkRequest)) { return super.equals(obj); } com.google.ads.googleads.v19.services.MoveManagerLinkRequest other = (com.google.ads.googleads.v19.services.MoveManagerLinkRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (!getPreviousCustomerManagerLink() .equals(other.getPreviousCustomerManagerLink())) return false; if (!getNewManager() .equals(other.getNewManager())) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerId().hashCode(); hash = (37 * hash) + PREVIOUS_CUSTOMER_MANAGER_LINK_FIELD_NUMBER; hash = (53 * hash) + getPreviousCustomerManagerLink().hashCode(); hash = (37 * hash) + NEW_MANAGER_FIELD_NUMBER; hash = (53 * hash) + getNewManager().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.ads.googleads.v19.services.MoveManagerLinkRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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 * [CustomerManagerLinkService.MoveManagerLink][google.ads.googleads.v19.services.CustomerManagerLinkService.MoveManagerLink]. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.MoveManagerLinkRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.MoveManagerLinkRequest) com.google.ads.googleads.v19.services.MoveManagerLinkRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_MoveManagerLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.MoveManagerLinkRequest.class, com.google.ads.googleads.v19.services.MoveManagerLinkRequest.Builder.class); } // Construct using com.google.ads.googleads.v19.services.MoveManagerLinkRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; customerId_ = ""; previousCustomerManagerLink_ = ""; newManager_ = ""; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.services.MoveManagerLinkRequest getDefaultInstanceForType() { return com.google.ads.googleads.v19.services.MoveManagerLinkRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.services.MoveManagerLinkRequest build() { com.google.ads.googleads.v19.services.MoveManagerLinkRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.services.MoveManagerLinkRequest buildPartial() { com.google.ads.googleads.v19.services.MoveManagerLinkRequest result = new com.google.ads.googleads.v19.services.MoveManagerLinkRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v19.services.MoveManagerLinkRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.customerId_ = customerId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.previousCustomerManagerLink_ = previousCustomerManagerLink_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.newManager_ = newManager_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.validateOnly_ = validateOnly_; } } @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.MoveManagerLinkRequest) { return mergeFrom((com.google.ads.googleads.v19.services.MoveManagerLinkRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.services.MoveManagerLinkRequest other) { if (other == com.google.ads.googleads.v19.services.MoveManagerLinkRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPreviousCustomerManagerLink().isEmpty()) { previousCustomerManagerLink_ = other.previousCustomerManagerLink_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getNewManager().isEmpty()) { newManager_ = other.newManager_; bitField0_ |= 0x00000004; onChanged(); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { customerId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { previousCustomerManagerLink_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { newManager_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The customerId to set. * @return This builder for chaining. */ public Builder setCustomerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for customerId to set. * @return This builder for chaining. */ public Builder setCustomerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object previousCustomerManagerLink_ = ""; /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The previousCustomerManagerLink. */ public java.lang.String getPreviousCustomerManagerLink() { java.lang.Object ref = previousCustomerManagerLink_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); previousCustomerManagerLink_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for previousCustomerManagerLink. */ public com.google.protobuf.ByteString getPreviousCustomerManagerLinkBytes() { java.lang.Object ref = previousCustomerManagerLink_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); previousCustomerManagerLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The previousCustomerManagerLink to set. * @return This builder for chaining. */ public Builder setPreviousCustomerManagerLink( java.lang.String value) { if (value == null) { throw new NullPointerException(); } previousCustomerManagerLink_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearPreviousCustomerManagerLink() { previousCustomerManagerLink_ = getDefaultInstance().getPreviousCustomerManagerLink(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for previousCustomerManagerLink to set. * @return This builder for chaining. */ public Builder setPreviousCustomerManagerLinkBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); previousCustomerManagerLink_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object newManager_ = ""; /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The newManager. */ public java.lang.String getNewManager() { java.lang.Object ref = newManager_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newManager_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for newManager. */ public com.google.protobuf.ByteString getNewManagerBytes() { java.lang.Object ref = newManager_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newManager_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The newManager to set. * @return This builder for chaining. */ public Builder setNewManager( java.lang.String value) { if (value == null) { throw new NullPointerException(); } newManager_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearNewManager() { newManager_ = getDefaultInstance().getNewManager(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for newManager to set. * @return This builder for chaining. */ public Builder setNewManagerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); newManager_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000008); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v19.services.MoveManagerLinkRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.MoveManagerLinkRequest) private static final com.google.ads.googleads.v19.services.MoveManagerLinkRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.MoveManagerLinkRequest(); } public static com.google.ads.googleads.v19.services.MoveManagerLinkRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MoveManagerLinkRequest> PARSER = new com.google.protobuf.AbstractParser<MoveManagerLinkRequest>() { @java.lang.Override public MoveManagerLinkRequest 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<MoveManagerLinkRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MoveManagerLinkRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.services.MoveManagerLinkRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,735
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/MoveManagerLinkRequest.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/services/customer_manager_link_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.services; /** * <pre> * Request message for * [CustomerManagerLinkService.MoveManagerLink][google.ads.googleads.v20.services.CustomerManagerLinkService.MoveManagerLink]. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.MoveManagerLinkRequest} */ public final class MoveManagerLinkRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.MoveManagerLinkRequest) MoveManagerLinkRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MoveManagerLinkRequest.newBuilder() to construct. private MoveManagerLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MoveManagerLinkRequest() { customerId_ = ""; previousCustomerManagerLink_ = ""; newManager_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MoveManagerLinkRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_MoveManagerLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.MoveManagerLinkRequest.class, com.google.ads.googleads.v20.services.MoveManagerLinkRequest.Builder.class); } public static final int CUSTOMER_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ @java.lang.Override public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PREVIOUS_CUSTOMER_MANAGER_LINK_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object previousCustomerManagerLink_ = ""; /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The previousCustomerManagerLink. */ @java.lang.Override public java.lang.String getPreviousCustomerManagerLink() { java.lang.Object ref = previousCustomerManagerLink_; 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(); previousCustomerManagerLink_ = s; return s; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for previousCustomerManagerLink. */ @java.lang.Override public com.google.protobuf.ByteString getPreviousCustomerManagerLinkBytes() { java.lang.Object ref = previousCustomerManagerLink_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); previousCustomerManagerLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NEW_MANAGER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object newManager_ = ""; /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The newManager. */ @java.lang.Override public java.lang.String getNewManager() { java.lang.Object ref = newManager_; 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(); newManager_ = s; return s; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for newManager. */ @java.lang.Override public com.google.protobuf.ByteString getNewManagerBytes() { java.lang.Object ref = newManager_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newManager_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_ = false; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(previousCustomerManagerLink_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, previousCustomerManagerLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(newManager_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, newManager_); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(previousCustomerManagerLink_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, previousCustomerManagerLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(newManager_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, newManager_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v20.services.MoveManagerLinkRequest)) { return super.equals(obj); } com.google.ads.googleads.v20.services.MoveManagerLinkRequest other = (com.google.ads.googleads.v20.services.MoveManagerLinkRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (!getPreviousCustomerManagerLink() .equals(other.getPreviousCustomerManagerLink())) return false; if (!getNewManager() .equals(other.getNewManager())) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerId().hashCode(); hash = (37 * hash) + PREVIOUS_CUSTOMER_MANAGER_LINK_FIELD_NUMBER; hash = (53 * hash) + getPreviousCustomerManagerLink().hashCode(); hash = (37 * hash) + NEW_MANAGER_FIELD_NUMBER; hash = (53 * hash) + getNewManager().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.ads.googleads.v20.services.MoveManagerLinkRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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 * [CustomerManagerLinkService.MoveManagerLink][google.ads.googleads.v20.services.CustomerManagerLinkService.MoveManagerLink]. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.MoveManagerLinkRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.MoveManagerLinkRequest) com.google.ads.googleads.v20.services.MoveManagerLinkRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_MoveManagerLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.MoveManagerLinkRequest.class, com.google.ads.googleads.v20.services.MoveManagerLinkRequest.Builder.class); } // Construct using com.google.ads.googleads.v20.services.MoveManagerLinkRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; customerId_ = ""; previousCustomerManagerLink_ = ""; newManager_ = ""; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.services.MoveManagerLinkRequest getDefaultInstanceForType() { return com.google.ads.googleads.v20.services.MoveManagerLinkRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.services.MoveManagerLinkRequest build() { com.google.ads.googleads.v20.services.MoveManagerLinkRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.services.MoveManagerLinkRequest buildPartial() { com.google.ads.googleads.v20.services.MoveManagerLinkRequest result = new com.google.ads.googleads.v20.services.MoveManagerLinkRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v20.services.MoveManagerLinkRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.customerId_ = customerId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.previousCustomerManagerLink_ = previousCustomerManagerLink_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.newManager_ = newManager_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.validateOnly_ = validateOnly_; } } @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.MoveManagerLinkRequest) { return mergeFrom((com.google.ads.googleads.v20.services.MoveManagerLinkRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.services.MoveManagerLinkRequest other) { if (other == com.google.ads.googleads.v20.services.MoveManagerLinkRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPreviousCustomerManagerLink().isEmpty()) { previousCustomerManagerLink_ = other.previousCustomerManagerLink_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getNewManager().isEmpty()) { newManager_ = other.newManager_; bitField0_ |= 0x00000004; onChanged(); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { customerId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { previousCustomerManagerLink_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { newManager_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The customerId to set. * @return This builder for chaining. */ public Builder setCustomerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for customerId to set. * @return This builder for chaining. */ public Builder setCustomerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object previousCustomerManagerLink_ = ""; /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The previousCustomerManagerLink. */ public java.lang.String getPreviousCustomerManagerLink() { java.lang.Object ref = previousCustomerManagerLink_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); previousCustomerManagerLink_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for previousCustomerManagerLink. */ public com.google.protobuf.ByteString getPreviousCustomerManagerLinkBytes() { java.lang.Object ref = previousCustomerManagerLink_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); previousCustomerManagerLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The previousCustomerManagerLink to set. * @return This builder for chaining. */ public Builder setPreviousCustomerManagerLink( java.lang.String value) { if (value == null) { throw new NullPointerException(); } previousCustomerManagerLink_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearPreviousCustomerManagerLink() { previousCustomerManagerLink_ = getDefaultInstance().getPreviousCustomerManagerLink(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for previousCustomerManagerLink to set. * @return This builder for chaining. */ public Builder setPreviousCustomerManagerLinkBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); previousCustomerManagerLink_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object newManager_ = ""; /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The newManager. */ public java.lang.String getNewManager() { java.lang.Object ref = newManager_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newManager_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for newManager. */ public com.google.protobuf.ByteString getNewManagerBytes() { java.lang.Object ref = newManager_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newManager_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The newManager to set. * @return This builder for chaining. */ public Builder setNewManager( java.lang.String value) { if (value == null) { throw new NullPointerException(); } newManager_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearNewManager() { newManager_ = getDefaultInstance().getNewManager(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for newManager to set. * @return This builder for chaining. */ public Builder setNewManagerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); newManager_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000008); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v20.services.MoveManagerLinkRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.MoveManagerLinkRequest) private static final com.google.ads.googleads.v20.services.MoveManagerLinkRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.MoveManagerLinkRequest(); } public static com.google.ads.googleads.v20.services.MoveManagerLinkRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MoveManagerLinkRequest> PARSER = new com.google.protobuf.AbstractParser<MoveManagerLinkRequest>() { @java.lang.Override public MoveManagerLinkRequest 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<MoveManagerLinkRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MoveManagerLinkRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.services.MoveManagerLinkRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,735
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/MoveManagerLinkRequest.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/customer_manager_link_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; /** * <pre> * Request message for * [CustomerManagerLinkService.MoveManagerLink][google.ads.googleads.v21.services.CustomerManagerLinkService.MoveManagerLink]. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.MoveManagerLinkRequest} */ public final class MoveManagerLinkRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.MoveManagerLinkRequest) MoveManagerLinkRequestOrBuilder { private static final long serialVersionUID = 0L; // Use MoveManagerLinkRequest.newBuilder() to construct. private MoveManagerLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private MoveManagerLinkRequest() { customerId_ = ""; previousCustomerManagerLink_ = ""; newManager_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MoveManagerLinkRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_MoveManagerLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.MoveManagerLinkRequest.class, com.google.ads.googleads.v21.services.MoveManagerLinkRequest.Builder.class); } public static final int CUSTOMER_ID_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ @java.lang.Override public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ @java.lang.Override public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PREVIOUS_CUSTOMER_MANAGER_LINK_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object previousCustomerManagerLink_ = ""; /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The previousCustomerManagerLink. */ @java.lang.Override public java.lang.String getPreviousCustomerManagerLink() { java.lang.Object ref = previousCustomerManagerLink_; 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(); previousCustomerManagerLink_ = s; return s; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for previousCustomerManagerLink. */ @java.lang.Override public com.google.protobuf.ByteString getPreviousCustomerManagerLinkBytes() { java.lang.Object ref = previousCustomerManagerLink_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); previousCustomerManagerLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NEW_MANAGER_FIELD_NUMBER = 3; @SuppressWarnings("serial") private volatile java.lang.Object newManager_ = ""; /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The newManager. */ @java.lang.Override public java.lang.String getNewManager() { java.lang.Object ref = newManager_; 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(); newManager_ = s; return s; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for newManager. */ @java.lang.Override public com.google.protobuf.ByteString getNewManagerBytes() { java.lang.Object ref = newManager_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newManager_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALIDATE_ONLY_FIELD_NUMBER = 4; private boolean validateOnly_ = false; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(previousCustomerManagerLink_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, previousCustomerManagerLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(newManager_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, newManager_); } if (validateOnly_ != false) { output.writeBool(4, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(previousCustomerManagerLink_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, previousCustomerManagerLink_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(newManager_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, newManager_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(4, validateOnly_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v21.services.MoveManagerLinkRequest)) { return super.equals(obj); } com.google.ads.googleads.v21.services.MoveManagerLinkRequest other = (com.google.ads.googleads.v21.services.MoveManagerLinkRequest) obj; if (!getCustomerId() .equals(other.getCustomerId())) return false; if (!getPreviousCustomerManagerLink() .equals(other.getPreviousCustomerManagerLink())) return false; if (!getNewManager() .equals(other.getNewManager())) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER; hash = (53 * hash) + getCustomerId().hashCode(); hash = (37 * hash) + PREVIOUS_CUSTOMER_MANAGER_LINK_FIELD_NUMBER; hash = (53 * hash) + getPreviousCustomerManagerLink().hashCode(); hash = (37 * hash) + NEW_MANAGER_FIELD_NUMBER; hash = (53 * hash) + getNewManager().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.ads.googleads.v21.services.MoveManagerLinkRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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.MoveManagerLinkRequest 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 * [CustomerManagerLinkService.MoveManagerLink][google.ads.googleads.v21.services.CustomerManagerLinkService.MoveManagerLink]. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.MoveManagerLinkRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.MoveManagerLinkRequest) com.google.ads.googleads.v21.services.MoveManagerLinkRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_MoveManagerLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.MoveManagerLinkRequest.class, com.google.ads.googleads.v21.services.MoveManagerLinkRequest.Builder.class); } // Construct using com.google.ads.googleads.v21.services.MoveManagerLinkRequest.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; customerId_ = ""; previousCustomerManagerLink_ = ""; newManager_ = ""; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_MoveManagerLinkRequest_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.services.MoveManagerLinkRequest getDefaultInstanceForType() { return com.google.ads.googleads.v21.services.MoveManagerLinkRequest.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.services.MoveManagerLinkRequest build() { com.google.ads.googleads.v21.services.MoveManagerLinkRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.services.MoveManagerLinkRequest buildPartial() { com.google.ads.googleads.v21.services.MoveManagerLinkRequest result = new com.google.ads.googleads.v21.services.MoveManagerLinkRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.ads.googleads.v21.services.MoveManagerLinkRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.customerId_ = customerId_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.previousCustomerManagerLink_ = previousCustomerManagerLink_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.newManager_ = newManager_; } if (((from_bitField0_ & 0x00000008) != 0)) { result.validateOnly_ = validateOnly_; } } @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.MoveManagerLinkRequest) { return mergeFrom((com.google.ads.googleads.v21.services.MoveManagerLinkRequest)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.services.MoveManagerLinkRequest other) { if (other == com.google.ads.googleads.v21.services.MoveManagerLinkRequest.getDefaultInstance()) return this; if (!other.getCustomerId().isEmpty()) { customerId_ = other.customerId_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getPreviousCustomerManagerLink().isEmpty()) { previousCustomerManagerLink_ = other.previousCustomerManagerLink_; bitField0_ |= 0x00000002; onChanged(); } if (!other.getNewManager().isEmpty()) { newManager_ = other.newManager_; bitField0_ |= 0x00000004; onChanged(); } if (other.getValidateOnly() != false) { setValidateOnly(other.getValidateOnly()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { customerId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { previousCustomerManagerLink_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { newManager_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; break; } // case 26 case 32: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000008; break; } // case 32 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object customerId_ = ""; /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The customerId. */ public java.lang.String getCustomerId() { java.lang.Object ref = customerId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); customerId_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for customerId. */ public com.google.protobuf.ByteString getCustomerIdBytes() { java.lang.Object ref = customerId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); customerId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The customerId to set. * @return This builder for chaining. */ public Builder setCustomerId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } customerId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearCustomerId() { customerId_ = getDefaultInstance().getCustomerId(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * <pre> * Required. The ID of the client customer that is being moved. * </pre> * * <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for customerId to set. * @return This builder for chaining. */ public Builder setCustomerIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); customerId_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object previousCustomerManagerLink_ = ""; /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The previousCustomerManagerLink. */ public java.lang.String getPreviousCustomerManagerLink() { java.lang.Object ref = previousCustomerManagerLink_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); previousCustomerManagerLink_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for previousCustomerManagerLink. */ public com.google.protobuf.ByteString getPreviousCustomerManagerLinkBytes() { java.lang.Object ref = previousCustomerManagerLink_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); previousCustomerManagerLink_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The previousCustomerManagerLink to set. * @return This builder for chaining. */ public Builder setPreviousCustomerManagerLink( java.lang.String value) { if (value == null) { throw new NullPointerException(); } previousCustomerManagerLink_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearPreviousCustomerManagerLink() { previousCustomerManagerLink_ = getDefaultInstance().getPreviousCustomerManagerLink(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * <pre> * Required. The resource name of the previous CustomerManagerLink. * The resource name has the form: * `customers/{customer_id}/customerManagerLinks/{manager_customer_id}~{manager_link_id}` * </pre> * * <code>string previous_customer_manager_link = 2 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for previousCustomerManagerLink to set. * @return This builder for chaining. */ public Builder setPreviousCustomerManagerLinkBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); previousCustomerManagerLink_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private java.lang.Object newManager_ = ""; /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The newManager. */ public java.lang.String getNewManager() { java.lang.Object ref = newManager_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); newManager_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return The bytes for newManager. */ public com.google.protobuf.ByteString getNewManagerBytes() { java.lang.Object ref = newManager_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); newManager_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The newManager to set. * @return This builder for chaining. */ public Builder setNewManager( java.lang.String value) { if (value == null) { throw new NullPointerException(); } newManager_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @return This builder for chaining. */ public Builder clearNewManager() { newManager_ = getDefaultInstance().getNewManager(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); return this; } /** * <pre> * Required. The resource name of the new manager customer that the client * wants to move to. Customer resource names have the format: * "customers/{customer_id}" * </pre> * * <code>string new_manager = 3 [(.google.api.field_behavior) = REQUIRED];</code> * @param value The bytes for newManager to set. * @return This builder for chaining. */ public Builder setNewManagerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); newManager_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } private boolean validateOnly_ ; /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000008; onChanged(); return this; } /** * <pre> * If true, the request is validated but not executed. Only errors are * returned, not results. * </pre> * * <code>bool validate_only = 4;</code> * @return This builder for chaining. */ public Builder clearValidateOnly() { bitField0_ = (bitField0_ & ~0x00000008); validateOnly_ = false; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v21.services.MoveManagerLinkRequest) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.MoveManagerLinkRequest) private static final com.google.ads.googleads.v21.services.MoveManagerLinkRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.MoveManagerLinkRequest(); } public static com.google.ads.googleads.v21.services.MoveManagerLinkRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<MoveManagerLinkRequest> PARSER = new com.google.protobuf.AbstractParser<MoveManagerLinkRequest>() { @java.lang.Override public MoveManagerLinkRequest 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<MoveManagerLinkRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<MoveManagerLinkRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.services.MoveManagerLinkRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,568
java-datalabeling/proto-google-cloud-datalabeling-v1beta1/src/main/java/com/google/cloud/datalabeling/v1beta1/ListDatasetsRequest.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 ListDataset. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListDatasetsRequest} */ public final class ListDatasetsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.datalabeling.v1beta1.ListDatasetsRequest) ListDatasetsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use ListDatasetsRequest.newBuilder() to construct. private ListDatasetsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDatasetsRequest() { parent_ = ""; filter_ = ""; pageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDatasetsRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.class, com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. Dataset resource parent, format: * projects/{project_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. Dataset resource parent, format: * projects/{project_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 on dataset 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 on dataset 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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.ListDatasetsRequest)) { return super.equals(obj); } com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest other = (com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest) 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.ListDatasetsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest 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.ListDatasetsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest 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.ListDatasetsRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest 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.ListDatasetsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest 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.ListDatasetsRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest 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.ListDatasetsRequest 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.ListDatasetsRequest 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.ListDatasetsRequest 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 ListDataset. * </pre> * * Protobuf type {@code google.cloud.datalabeling.v1beta1.ListDatasetsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.datalabeling.v1beta1.ListDatasetsRequest) com.google.cloud.datalabeling.v1beta1.ListDatasetsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDatasetsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.datalabeling.v1beta1.DataLabelingServiceOuterClass .internal_static_google_cloud_datalabeling_v1beta1_ListDatasetsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.class, com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.Builder.class); } // Construct using com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.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_ListDatasetsRequest_descriptor; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest getDefaultInstanceForType() { return com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest build() { com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest buildPartial() { com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest result = new com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest 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.ListDatasetsRequest) { return mergeFrom((com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest other) { if (other == com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest.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. Dataset resource parent, format: * projects/{project_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. Dataset resource parent, format: * projects/{project_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. Dataset resource parent, format: * projects/{project_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. Dataset resource parent, format: * projects/{project_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. Dataset resource parent, format: * projects/{project_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 on dataset 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 on dataset 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 on dataset 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 on dataset 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 on dataset 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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 * [ListDatasetsResponse.next_page_token][google.cloud.datalabeling.v1beta1.ListDatasetsResponse.next_page_token] of the previous * [DataLabelingService.ListDatasets] call. * Returns the 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.ListDatasetsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.datalabeling.v1beta1.ListDatasetsRequest) private static final com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest(); } public static com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDatasetsRequest> PARSER = new com.google.protobuf.AbstractParser<ListDatasetsRequest>() { @java.lang.Override public ListDatasetsRequest 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<ListDatasetsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDatasetsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.datalabeling.v1beta1.ListDatasetsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,930
java-biglake/google-cloud-biglake/src/main/java/com/google/cloud/bigquery/biglake/v1alpha1/stub/GrpcMetastoreServiceStub.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.bigquery.biglake.v1alpha1.stub; import static com.google.cloud.bigquery.biglake.v1alpha1.MetastoreServiceClient.ListCatalogsPagedResponse; import static com.google.cloud.bigquery.biglake.v1alpha1.MetastoreServiceClient.ListDatabasesPagedResponse; import static com.google.cloud.bigquery.biglake.v1alpha1.MetastoreServiceClient.ListLocksPagedResponse; import static com.google.cloud.bigquery.biglake.v1alpha1.MetastoreServiceClient.ListTablesPagedResponse; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.grpc.GrpcCallSettings; import com.google.api.gax.grpc.GrpcStubCallableFactory; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.RequestParamsBuilder; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.bigquery.biglake.v1alpha1.Catalog; import com.google.cloud.bigquery.biglake.v1alpha1.CheckLockRequest; import com.google.cloud.bigquery.biglake.v1alpha1.CreateCatalogRequest; import com.google.cloud.bigquery.biglake.v1alpha1.CreateDatabaseRequest; import com.google.cloud.bigquery.biglake.v1alpha1.CreateLockRequest; import com.google.cloud.bigquery.biglake.v1alpha1.CreateTableRequest; import com.google.cloud.bigquery.biglake.v1alpha1.Database; import com.google.cloud.bigquery.biglake.v1alpha1.DeleteCatalogRequest; import com.google.cloud.bigquery.biglake.v1alpha1.DeleteDatabaseRequest; import com.google.cloud.bigquery.biglake.v1alpha1.DeleteLockRequest; import com.google.cloud.bigquery.biglake.v1alpha1.DeleteTableRequest; import com.google.cloud.bigquery.biglake.v1alpha1.GetCatalogRequest; import com.google.cloud.bigquery.biglake.v1alpha1.GetDatabaseRequest; import com.google.cloud.bigquery.biglake.v1alpha1.GetTableRequest; import com.google.cloud.bigquery.biglake.v1alpha1.ListCatalogsRequest; import com.google.cloud.bigquery.biglake.v1alpha1.ListCatalogsResponse; import com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesRequest; import com.google.cloud.bigquery.biglake.v1alpha1.ListDatabasesResponse; import com.google.cloud.bigquery.biglake.v1alpha1.ListLocksRequest; import com.google.cloud.bigquery.biglake.v1alpha1.ListLocksResponse; import com.google.cloud.bigquery.biglake.v1alpha1.ListTablesRequest; import com.google.cloud.bigquery.biglake.v1alpha1.ListTablesResponse; import com.google.cloud.bigquery.biglake.v1alpha1.Lock; import com.google.cloud.bigquery.biglake.v1alpha1.RenameTableRequest; import com.google.cloud.bigquery.biglake.v1alpha1.Table; import com.google.cloud.bigquery.biglake.v1alpha1.UpdateDatabaseRequest; import com.google.cloud.bigquery.biglake.v1alpha1.UpdateTableRequest; import com.google.longrunning.stub.GrpcOperationsStub; import com.google.protobuf.Empty; import io.grpc.MethodDescriptor; import io.grpc.protobuf.ProtoUtils; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * gRPC stub implementation for the MetastoreService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @BetaApi @Generated("by gapic-generator-java") public class GrpcMetastoreServiceStub extends MetastoreServiceStub { private static final MethodDescriptor<CreateCatalogRequest, Catalog> createCatalogMethodDescriptor = MethodDescriptor.<CreateCatalogRequest, Catalog>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/CreateCatalog") .setRequestMarshaller( ProtoUtils.marshaller(CreateCatalogRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Catalog.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteCatalogRequest, Catalog> deleteCatalogMethodDescriptor = MethodDescriptor.<DeleteCatalogRequest, Catalog>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/DeleteCatalog") .setRequestMarshaller( ProtoUtils.marshaller(DeleteCatalogRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Catalog.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetCatalogRequest, Catalog> getCatalogMethodDescriptor = MethodDescriptor.<GetCatalogRequest, Catalog>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/GetCatalog") .setRequestMarshaller(ProtoUtils.marshaller(GetCatalogRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Catalog.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListCatalogsRequest, ListCatalogsResponse> listCatalogsMethodDescriptor = MethodDescriptor.<ListCatalogsRequest, ListCatalogsResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/ListCatalogs") .setRequestMarshaller(ProtoUtils.marshaller(ListCatalogsRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListCatalogsResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<CreateDatabaseRequest, Database> createDatabaseMethodDescriptor = MethodDescriptor.<CreateDatabaseRequest, Database>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/CreateDatabase") .setRequestMarshaller( ProtoUtils.marshaller(CreateDatabaseRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Database.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteDatabaseRequest, Database> deleteDatabaseMethodDescriptor = MethodDescriptor.<DeleteDatabaseRequest, Database>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/DeleteDatabase") .setRequestMarshaller( ProtoUtils.marshaller(DeleteDatabaseRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Database.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UpdateDatabaseRequest, Database> updateDatabaseMethodDescriptor = MethodDescriptor.<UpdateDatabaseRequest, Database>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/UpdateDatabase") .setRequestMarshaller( ProtoUtils.marshaller(UpdateDatabaseRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Database.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetDatabaseRequest, Database> getDatabaseMethodDescriptor = MethodDescriptor.<GetDatabaseRequest, Database>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/GetDatabase") .setRequestMarshaller(ProtoUtils.marshaller(GetDatabaseRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Database.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListDatabasesRequest, ListDatabasesResponse> listDatabasesMethodDescriptor = MethodDescriptor.<ListDatabasesRequest, ListDatabasesResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/ListDatabases") .setRequestMarshaller( ProtoUtils.marshaller(ListDatabasesRequest.getDefaultInstance())) .setResponseMarshaller( ProtoUtils.marshaller(ListDatabasesResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<CreateTableRequest, Table> createTableMethodDescriptor = MethodDescriptor.<CreateTableRequest, Table>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/CreateTable") .setRequestMarshaller(ProtoUtils.marshaller(CreateTableRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Table.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteTableRequest, Table> deleteTableMethodDescriptor = MethodDescriptor.<DeleteTableRequest, Table>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/DeleteTable") .setRequestMarshaller(ProtoUtils.marshaller(DeleteTableRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Table.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<UpdateTableRequest, Table> updateTableMethodDescriptor = MethodDescriptor.<UpdateTableRequest, Table>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/UpdateTable") .setRequestMarshaller(ProtoUtils.marshaller(UpdateTableRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Table.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<RenameTableRequest, Table> renameTableMethodDescriptor = MethodDescriptor.<RenameTableRequest, Table>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/RenameTable") .setRequestMarshaller(ProtoUtils.marshaller(RenameTableRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Table.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<GetTableRequest, Table> getTableMethodDescriptor = MethodDescriptor.<GetTableRequest, Table>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/GetTable") .setRequestMarshaller(ProtoUtils.marshaller(GetTableRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Table.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListTablesRequest, ListTablesResponse> listTablesMethodDescriptor = MethodDescriptor.<ListTablesRequest, ListTablesResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/ListTables") .setRequestMarshaller(ProtoUtils.marshaller(ListTablesRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(ListTablesResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<CreateLockRequest, Lock> createLockMethodDescriptor = MethodDescriptor.<CreateLockRequest, Lock>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/CreateLock") .setRequestMarshaller(ProtoUtils.marshaller(CreateLockRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Lock.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<DeleteLockRequest, Empty> deleteLockMethodDescriptor = MethodDescriptor.<DeleteLockRequest, Empty>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/DeleteLock") .setRequestMarshaller(ProtoUtils.marshaller(DeleteLockRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<CheckLockRequest, Lock> checkLockMethodDescriptor = MethodDescriptor.<CheckLockRequest, Lock>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.bigquery.biglake.v1alpha1.MetastoreService/CheckLock") .setRequestMarshaller(ProtoUtils.marshaller(CheckLockRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(Lock.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private static final MethodDescriptor<ListLocksRequest, ListLocksResponse> listLocksMethodDescriptor = MethodDescriptor.<ListLocksRequest, ListLocksResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName( "google.cloud.bigquery.biglake.v1alpha1.MetastoreService/ListLocks") .setRequestMarshaller(ProtoUtils.marshaller(ListLocksRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(ListLocksResponse.getDefaultInstance())) .setSampledToLocalTracing(true) .build(); private final UnaryCallable<CreateCatalogRequest, Catalog> createCatalogCallable; private final UnaryCallable<DeleteCatalogRequest, Catalog> deleteCatalogCallable; private final UnaryCallable<GetCatalogRequest, Catalog> getCatalogCallable; private final UnaryCallable<ListCatalogsRequest, ListCatalogsResponse> listCatalogsCallable; private final UnaryCallable<ListCatalogsRequest, ListCatalogsPagedResponse> listCatalogsPagedCallable; private final UnaryCallable<CreateDatabaseRequest, Database> createDatabaseCallable; private final UnaryCallable<DeleteDatabaseRequest, Database> deleteDatabaseCallable; private final UnaryCallable<UpdateDatabaseRequest, Database> updateDatabaseCallable; private final UnaryCallable<GetDatabaseRequest, Database> getDatabaseCallable; private final UnaryCallable<ListDatabasesRequest, ListDatabasesResponse> listDatabasesCallable; private final UnaryCallable<ListDatabasesRequest, ListDatabasesPagedResponse> listDatabasesPagedCallable; private final UnaryCallable<CreateTableRequest, Table> createTableCallable; private final UnaryCallable<DeleteTableRequest, Table> deleteTableCallable; private final UnaryCallable<UpdateTableRequest, Table> updateTableCallable; private final UnaryCallable<RenameTableRequest, Table> renameTableCallable; private final UnaryCallable<GetTableRequest, Table> getTableCallable; private final UnaryCallable<ListTablesRequest, ListTablesResponse> listTablesCallable; private final UnaryCallable<ListTablesRequest, ListTablesPagedResponse> listTablesPagedCallable; private final UnaryCallable<CreateLockRequest, Lock> createLockCallable; private final UnaryCallable<DeleteLockRequest, Empty> deleteLockCallable; private final UnaryCallable<CheckLockRequest, Lock> checkLockCallable; private final UnaryCallable<ListLocksRequest, ListLocksResponse> listLocksCallable; private final UnaryCallable<ListLocksRequest, ListLocksPagedResponse> listLocksPagedCallable; private final BackgroundResource backgroundResources; private final GrpcOperationsStub operationsStub; private final GrpcStubCallableFactory callableFactory; public static final GrpcMetastoreServiceStub create(MetastoreServiceStubSettings settings) throws IOException { return new GrpcMetastoreServiceStub(settings, ClientContext.create(settings)); } public static final GrpcMetastoreServiceStub create(ClientContext clientContext) throws IOException { return new GrpcMetastoreServiceStub( MetastoreServiceStubSettings.newBuilder().build(), clientContext); } public static final GrpcMetastoreServiceStub create( ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { return new GrpcMetastoreServiceStub( MetastoreServiceStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of GrpcMetastoreServiceStub, 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 GrpcMetastoreServiceStub( MetastoreServiceStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new GrpcMetastoreServiceCallableFactory()); } /** * Constructs an instance of GrpcMetastoreServiceStub, 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 GrpcMetastoreServiceStub( MetastoreServiceStubSettings settings, ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory); GrpcCallSettings<CreateCatalogRequest, Catalog> createCatalogTransportSettings = GrpcCallSettings.<CreateCatalogRequest, Catalog>newBuilder() .setMethodDescriptor(createCatalogMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<DeleteCatalogRequest, Catalog> deleteCatalogTransportSettings = GrpcCallSettings.<DeleteCatalogRequest, Catalog>newBuilder() .setMethodDescriptor(deleteCatalogMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<GetCatalogRequest, Catalog> getCatalogTransportSettings = GrpcCallSettings.<GetCatalogRequest, Catalog>newBuilder() .setMethodDescriptor(getCatalogMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListCatalogsRequest, ListCatalogsResponse> listCatalogsTransportSettings = GrpcCallSettings.<ListCatalogsRequest, ListCatalogsResponse>newBuilder() .setMethodDescriptor(listCatalogsMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<CreateDatabaseRequest, Database> createDatabaseTransportSettings = GrpcCallSettings.<CreateDatabaseRequest, Database>newBuilder() .setMethodDescriptor(createDatabaseMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<DeleteDatabaseRequest, Database> deleteDatabaseTransportSettings = GrpcCallSettings.<DeleteDatabaseRequest, Database>newBuilder() .setMethodDescriptor(deleteDatabaseMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<UpdateDatabaseRequest, Database> updateDatabaseTransportSettings = GrpcCallSettings.<UpdateDatabaseRequest, Database>newBuilder() .setMethodDescriptor(updateDatabaseMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("database.name", String.valueOf(request.getDatabase().getName())); return builder.build(); }) .build(); GrpcCallSettings<GetDatabaseRequest, Database> getDatabaseTransportSettings = GrpcCallSettings.<GetDatabaseRequest, Database>newBuilder() .setMethodDescriptor(getDatabaseMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListDatabasesRequest, ListDatabasesResponse> listDatabasesTransportSettings = GrpcCallSettings.<ListDatabasesRequest, ListDatabasesResponse>newBuilder() .setMethodDescriptor(listDatabasesMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<CreateTableRequest, Table> createTableTransportSettings = GrpcCallSettings.<CreateTableRequest, Table>newBuilder() .setMethodDescriptor(createTableMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<DeleteTableRequest, Table> deleteTableTransportSettings = GrpcCallSettings.<DeleteTableRequest, Table>newBuilder() .setMethodDescriptor(deleteTableMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<UpdateTableRequest, Table> updateTableTransportSettings = GrpcCallSettings.<UpdateTableRequest, Table>newBuilder() .setMethodDescriptor(updateTableMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("table.name", String.valueOf(request.getTable().getName())); return builder.build(); }) .build(); GrpcCallSettings<RenameTableRequest, Table> renameTableTransportSettings = GrpcCallSettings.<RenameTableRequest, Table>newBuilder() .setMethodDescriptor(renameTableMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<GetTableRequest, Table> getTableTransportSettings = GrpcCallSettings.<GetTableRequest, Table>newBuilder() .setMethodDescriptor(getTableMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListTablesRequest, ListTablesResponse> listTablesTransportSettings = GrpcCallSettings.<ListTablesRequest, ListTablesResponse>newBuilder() .setMethodDescriptor(listTablesMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<CreateLockRequest, Lock> createLockTransportSettings = GrpcCallSettings.<CreateLockRequest, Lock>newBuilder() .setMethodDescriptor(createLockMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); GrpcCallSettings<DeleteLockRequest, Empty> deleteLockTransportSettings = GrpcCallSettings.<DeleteLockRequest, Empty>newBuilder() .setMethodDescriptor(deleteLockMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<CheckLockRequest, Lock> checkLockTransportSettings = GrpcCallSettings.<CheckLockRequest, Lock>newBuilder() .setMethodDescriptor(checkLockMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("name", String.valueOf(request.getName())); return builder.build(); }) .build(); GrpcCallSettings<ListLocksRequest, ListLocksResponse> listLocksTransportSettings = GrpcCallSettings.<ListLocksRequest, ListLocksResponse>newBuilder() .setMethodDescriptor(listLocksMethodDescriptor) .setParamsExtractor( request -> { RequestParamsBuilder builder = RequestParamsBuilder.create(); builder.add("parent", String.valueOf(request.getParent())); return builder.build(); }) .build(); this.createCatalogCallable = callableFactory.createUnaryCallable( createCatalogTransportSettings, settings.createCatalogSettings(), clientContext); this.deleteCatalogCallable = callableFactory.createUnaryCallable( deleteCatalogTransportSettings, settings.deleteCatalogSettings(), clientContext); this.getCatalogCallable = callableFactory.createUnaryCallable( getCatalogTransportSettings, settings.getCatalogSettings(), clientContext); this.listCatalogsCallable = callableFactory.createUnaryCallable( listCatalogsTransportSettings, settings.listCatalogsSettings(), clientContext); this.listCatalogsPagedCallable = callableFactory.createPagedCallable( listCatalogsTransportSettings, settings.listCatalogsSettings(), clientContext); this.createDatabaseCallable = callableFactory.createUnaryCallable( createDatabaseTransportSettings, settings.createDatabaseSettings(), clientContext); this.deleteDatabaseCallable = callableFactory.createUnaryCallable( deleteDatabaseTransportSettings, settings.deleteDatabaseSettings(), clientContext); this.updateDatabaseCallable = callableFactory.createUnaryCallable( updateDatabaseTransportSettings, settings.updateDatabaseSettings(), clientContext); this.getDatabaseCallable = callableFactory.createUnaryCallable( getDatabaseTransportSettings, settings.getDatabaseSettings(), clientContext); this.listDatabasesCallable = callableFactory.createUnaryCallable( listDatabasesTransportSettings, settings.listDatabasesSettings(), clientContext); this.listDatabasesPagedCallable = callableFactory.createPagedCallable( listDatabasesTransportSettings, settings.listDatabasesSettings(), clientContext); this.createTableCallable = callableFactory.createUnaryCallable( createTableTransportSettings, settings.createTableSettings(), clientContext); this.deleteTableCallable = callableFactory.createUnaryCallable( deleteTableTransportSettings, settings.deleteTableSettings(), clientContext); this.updateTableCallable = callableFactory.createUnaryCallable( updateTableTransportSettings, settings.updateTableSettings(), clientContext); this.renameTableCallable = callableFactory.createUnaryCallable( renameTableTransportSettings, settings.renameTableSettings(), clientContext); this.getTableCallable = callableFactory.createUnaryCallable( getTableTransportSettings, settings.getTableSettings(), clientContext); this.listTablesCallable = callableFactory.createUnaryCallable( listTablesTransportSettings, settings.listTablesSettings(), clientContext); this.listTablesPagedCallable = callableFactory.createPagedCallable( listTablesTransportSettings, settings.listTablesSettings(), clientContext); this.createLockCallable = callableFactory.createUnaryCallable( createLockTransportSettings, settings.createLockSettings(), clientContext); this.deleteLockCallable = callableFactory.createUnaryCallable( deleteLockTransportSettings, settings.deleteLockSettings(), clientContext); this.checkLockCallable = callableFactory.createUnaryCallable( checkLockTransportSettings, settings.checkLockSettings(), clientContext); this.listLocksCallable = callableFactory.createUnaryCallable( listLocksTransportSettings, settings.listLocksSettings(), clientContext); this.listLocksPagedCallable = callableFactory.createPagedCallable( listLocksTransportSettings, settings.listLocksSettings(), clientContext); this.backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } public GrpcOperationsStub getOperationsStub() { return operationsStub; } @Override public UnaryCallable<CreateCatalogRequest, Catalog> createCatalogCallable() { return createCatalogCallable; } @Override public UnaryCallable<DeleteCatalogRequest, Catalog> deleteCatalogCallable() { return deleteCatalogCallable; } @Override public UnaryCallable<GetCatalogRequest, Catalog> getCatalogCallable() { return getCatalogCallable; } @Override public UnaryCallable<ListCatalogsRequest, ListCatalogsResponse> listCatalogsCallable() { return listCatalogsCallable; } @Override public UnaryCallable<ListCatalogsRequest, ListCatalogsPagedResponse> listCatalogsPagedCallable() { return listCatalogsPagedCallable; } @Override public UnaryCallable<CreateDatabaseRequest, Database> createDatabaseCallable() { return createDatabaseCallable; } @Override public UnaryCallable<DeleteDatabaseRequest, Database> deleteDatabaseCallable() { return deleteDatabaseCallable; } @Override public UnaryCallable<UpdateDatabaseRequest, Database> updateDatabaseCallable() { return updateDatabaseCallable; } @Override public UnaryCallable<GetDatabaseRequest, Database> getDatabaseCallable() { return getDatabaseCallable; } @Override public UnaryCallable<ListDatabasesRequest, ListDatabasesResponse> listDatabasesCallable() { return listDatabasesCallable; } @Override public UnaryCallable<ListDatabasesRequest, ListDatabasesPagedResponse> listDatabasesPagedCallable() { return listDatabasesPagedCallable; } @Override public UnaryCallable<CreateTableRequest, Table> createTableCallable() { return createTableCallable; } @Override public UnaryCallable<DeleteTableRequest, Table> deleteTableCallable() { return deleteTableCallable; } @Override public UnaryCallable<UpdateTableRequest, Table> updateTableCallable() { return updateTableCallable; } @Override public UnaryCallable<RenameTableRequest, Table> renameTableCallable() { return renameTableCallable; } @Override public UnaryCallable<GetTableRequest, Table> getTableCallable() { return getTableCallable; } @Override public UnaryCallable<ListTablesRequest, ListTablesResponse> listTablesCallable() { return listTablesCallable; } @Override public UnaryCallable<ListTablesRequest, ListTablesPagedResponse> listTablesPagedCallable() { return listTablesPagedCallable; } @Override public UnaryCallable<CreateLockRequest, Lock> createLockCallable() { return createLockCallable; } @Override public UnaryCallable<DeleteLockRequest, Empty> deleteLockCallable() { return deleteLockCallable; } @Override public UnaryCallable<CheckLockRequest, Lock> checkLockCallable() { return checkLockCallable; } @Override public UnaryCallable<ListLocksRequest, ListLocksResponse> listLocksCallable() { return listLocksCallable; } @Override public UnaryCallable<ListLocksRequest, ListLocksPagedResponse> listLocksPagedCallable() { return listLocksPagedCallable; } @Override public final void close() { try { backgroundResources.close(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new IllegalStateException("Failed to close resource", e); } } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
googleapis/google-cloud-java
36,580
java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/CreateHttpRouteRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/networkservices/v1/http_route.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.networkservices.v1; /** * * * <pre> * Request used by the HttpRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateHttpRouteRequest} */ public final class CreateHttpRouteRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.CreateHttpRouteRequest) CreateHttpRouteRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateHttpRouteRequest.newBuilder() to construct. private CreateHttpRouteRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateHttpRouteRequest() { parent_ = ""; httpRouteId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateHttpRouteRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.HttpRouteProto .internal_static_google_cloud_networkservices_v1_CreateHttpRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.HttpRouteProto .internal_static_google_cloud_networkservices_v1_CreateHttpRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateHttpRouteRequest.class, com.google.cloud.networkservices.v1.CreateHttpRouteRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int HTTP_ROUTE_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object httpRouteId_ = ""; /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The httpRouteId. */ @java.lang.Override public java.lang.String getHttpRouteId() { java.lang.Object ref = httpRouteId_; 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(); httpRouteId_ = s; return s; } } /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for httpRouteId. */ @java.lang.Override public com.google.protobuf.ByteString getHttpRouteIdBytes() { java.lang.Object ref = httpRouteId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); httpRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int HTTP_ROUTE_FIELD_NUMBER = 3; private com.google.cloud.networkservices.v1.HttpRoute httpRoute_; /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the httpRoute field is set. */ @java.lang.Override public boolean hasHttpRoute() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The httpRoute. */ @java.lang.Override public com.google.cloud.networkservices.v1.HttpRoute getHttpRoute() { return httpRoute_ == null ? com.google.cloud.networkservices.v1.HttpRoute.getDefaultInstance() : httpRoute_; } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.networkservices.v1.HttpRouteOrBuilder getHttpRouteOrBuilder() { return httpRoute_ == null ? com.google.cloud.networkservices.v1.HttpRoute.getDefaultInstance() : httpRoute_; } 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(httpRouteId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, httpRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getHttpRoute()); } 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(httpRouteId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, httpRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getHttpRoute()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.networkservices.v1.CreateHttpRouteRequest)) { return super.equals(obj); } com.google.cloud.networkservices.v1.CreateHttpRouteRequest other = (com.google.cloud.networkservices.v1.CreateHttpRouteRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getHttpRouteId().equals(other.getHttpRouteId())) return false; if (hasHttpRoute() != other.hasHttpRoute()) return false; if (hasHttpRoute()) { if (!getHttpRoute().equals(other.getHttpRoute())) 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) + HTTP_ROUTE_ID_FIELD_NUMBER; hash = (53 * hash) + getHttpRouteId().hashCode(); if (hasHttpRoute()) { hash = (37 * hash) + HTTP_ROUTE_FIELD_NUMBER; hash = (53 * hash) + getHttpRoute().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.networkservices.v1.CreateHttpRouteRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request used by the HttpRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateHttpRouteRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.CreateHttpRouteRequest) com.google.cloud.networkservices.v1.CreateHttpRouteRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.HttpRouteProto .internal_static_google_cloud_networkservices_v1_CreateHttpRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.HttpRouteProto .internal_static_google_cloud_networkservices_v1_CreateHttpRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateHttpRouteRequest.class, com.google.cloud.networkservices.v1.CreateHttpRouteRequest.Builder.class); } // Construct using com.google.cloud.networkservices.v1.CreateHttpRouteRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getHttpRouteFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; httpRouteId_ = ""; httpRoute_ = null; if (httpRouteBuilder_ != null) { httpRouteBuilder_.dispose(); httpRouteBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.networkservices.v1.HttpRouteProto .internal_static_google_cloud_networkservices_v1_CreateHttpRouteRequest_descriptor; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateHttpRouteRequest getDefaultInstanceForType() { return com.google.cloud.networkservices.v1.CreateHttpRouteRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.networkservices.v1.CreateHttpRouteRequest build() { com.google.cloud.networkservices.v1.CreateHttpRouteRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateHttpRouteRequest buildPartial() { com.google.cloud.networkservices.v1.CreateHttpRouteRequest result = new com.google.cloud.networkservices.v1.CreateHttpRouteRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.networkservices.v1.CreateHttpRouteRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.httpRouteId_ = httpRouteId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.httpRoute_ = httpRouteBuilder_ == null ? httpRoute_ : httpRouteBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.networkservices.v1.CreateHttpRouteRequest) { return mergeFrom((com.google.cloud.networkservices.v1.CreateHttpRouteRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.networkservices.v1.CreateHttpRouteRequest other) { if (other == com.google.cloud.networkservices.v1.CreateHttpRouteRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getHttpRouteId().isEmpty()) { httpRouteId_ = other.httpRouteId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasHttpRoute()) { mergeHttpRoute(other.getHttpRoute()); } 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: { httpRouteId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getHttpRouteFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the HttpRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object httpRouteId_ = ""; /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The httpRouteId. */ public java.lang.String getHttpRouteId() { java.lang.Object ref = httpRouteId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); httpRouteId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for httpRouteId. */ public com.google.protobuf.ByteString getHttpRouteIdBytes() { java.lang.Object ref = httpRouteId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); httpRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The httpRouteId to set. * @return This builder for chaining. */ public Builder setHttpRouteId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } httpRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearHttpRouteId() { httpRouteId_ = getDefaultInstance().getHttpRouteId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Short name of the HttpRoute resource to be created. * </pre> * * <code>string http_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for httpRouteId to set. * @return This builder for chaining. */ public Builder setHttpRouteIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); httpRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.networkservices.v1.HttpRoute httpRoute_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.HttpRoute, com.google.cloud.networkservices.v1.HttpRoute.Builder, com.google.cloud.networkservices.v1.HttpRouteOrBuilder> httpRouteBuilder_; /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the httpRoute field is set. */ public boolean hasHttpRoute() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The httpRoute. */ public com.google.cloud.networkservices.v1.HttpRoute getHttpRoute() { if (httpRouteBuilder_ == null) { return httpRoute_ == null ? com.google.cloud.networkservices.v1.HttpRoute.getDefaultInstance() : httpRoute_; } else { return httpRouteBuilder_.getMessage(); } } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setHttpRoute(com.google.cloud.networkservices.v1.HttpRoute value) { if (httpRouteBuilder_ == null) { if (value == null) { throw new NullPointerException(); } httpRoute_ = value; } else { httpRouteBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setHttpRoute( com.google.cloud.networkservices.v1.HttpRoute.Builder builderForValue) { if (httpRouteBuilder_ == null) { httpRoute_ = builderForValue.build(); } else { httpRouteBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeHttpRoute(com.google.cloud.networkservices.v1.HttpRoute value) { if (httpRouteBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && httpRoute_ != null && httpRoute_ != com.google.cloud.networkservices.v1.HttpRoute.getDefaultInstance()) { getHttpRouteBuilder().mergeFrom(value); } else { httpRoute_ = value; } } else { httpRouteBuilder_.mergeFrom(value); } if (httpRoute_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearHttpRoute() { bitField0_ = (bitField0_ & ~0x00000004); httpRoute_ = null; if (httpRouteBuilder_ != null) { httpRouteBuilder_.dispose(); httpRouteBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.HttpRoute.Builder getHttpRouteBuilder() { bitField0_ |= 0x00000004; onChanged(); return getHttpRouteFieldBuilder().getBuilder(); } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.HttpRouteOrBuilder getHttpRouteOrBuilder() { if (httpRouteBuilder_ != null) { return httpRouteBuilder_.getMessageOrBuilder(); } else { return httpRoute_ == null ? com.google.cloud.networkservices.v1.HttpRoute.getDefaultInstance() : httpRoute_; } } /** * * * <pre> * Required. HttpRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.HttpRoute http_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.HttpRoute, com.google.cloud.networkservices.v1.HttpRoute.Builder, com.google.cloud.networkservices.v1.HttpRouteOrBuilder> getHttpRouteFieldBuilder() { if (httpRouteBuilder_ == null) { httpRouteBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.HttpRoute, com.google.cloud.networkservices.v1.HttpRoute.Builder, com.google.cloud.networkservices.v1.HttpRouteOrBuilder>( getHttpRoute(), getParentForChildren(), isClean()); httpRoute_ = null; } return httpRouteBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.networkservices.v1.CreateHttpRouteRequest) } // @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.CreateHttpRouteRequest) private static final com.google.cloud.networkservices.v1.CreateHttpRouteRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.CreateHttpRouteRequest(); } public static com.google.cloud.networkservices.v1.CreateHttpRouteRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateHttpRouteRequest> PARSER = new com.google.protobuf.AbstractParser<CreateHttpRouteRequest>() { @java.lang.Override public CreateHttpRouteRequest 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<CreateHttpRouteRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateHttpRouteRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateHttpRouteRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,616
java-service-usage/proto-google-cloud-service-usage-v1/src/main/java/com/google/api/serviceusage/v1/DisableServiceRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/serviceusage/v1/serviceusage.proto // Protobuf Java Version: 3.25.8 package com.google.api.serviceusage.v1; /** * * * <pre> * Request message for the `DisableService` method. * </pre> * * Protobuf type {@code google.api.serviceusage.v1.DisableServiceRequest} */ public final class DisableServiceRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.api.serviceusage.v1.DisableServiceRequest) DisableServiceRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DisableServiceRequest.newBuilder() to construct. private DisableServiceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DisableServiceRequest() { name_ = ""; checkIfServiceHasUsage_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DisableServiceRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.serviceusage.v1.ServiceUsageProto .internal_static_google_api_serviceusage_v1_DisableServiceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.serviceusage.v1.ServiceUsageProto .internal_static_google_api_serviceusage_v1_DisableServiceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.serviceusage.v1.DisableServiceRequest.class, com.google.api.serviceusage.v1.DisableServiceRequest.Builder.class); } /** * * * <pre> * Enum to determine if service usage should be checked when disabling a * service. * </pre> * * Protobuf enum {@code google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage} */ public enum CheckIfServiceHasUsage implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * When unset, the default behavior is used, which is SKIP. * </pre> * * <code>CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED = 0;</code> */ CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED(0), /** * * * <pre> * If set, skip checking service usage when disabling a service. * </pre> * * <code>SKIP = 1;</code> */ SKIP(1), /** * * * <pre> * If set, service usage is checked when disabling the service. If a * service, or its dependents, has usage in the last 30 days, the request * returns a FAILED_PRECONDITION error. * </pre> * * <code>CHECK = 2;</code> */ CHECK(2), UNRECOGNIZED(-1), ; /** * * * <pre> * When unset, the default behavior is used, which is SKIP. * </pre> * * <code>CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED = 0;</code> */ public static final int CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * If set, skip checking service usage when disabling a service. * </pre> * * <code>SKIP = 1;</code> */ public static final int SKIP_VALUE = 1; /** * * * <pre> * If set, service usage is checked when disabling the service. If a * service, or its dependents, has usage in the last 30 days, the request * returns a FAILED_PRECONDITION error. * </pre> * * <code>CHECK = 2;</code> */ public static final int CHECK_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 CheckIfServiceHasUsage 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 CheckIfServiceHasUsage forNumber(int value) { switch (value) { case 0: return CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED; case 1: return SKIP; case 2: return CHECK; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<CheckIfServiceHasUsage> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<CheckIfServiceHasUsage> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<CheckIfServiceHasUsage>() { public CheckIfServiceHasUsage findValueByNumber(int number) { return CheckIfServiceHasUsage.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.api.serviceusage.v1.DisableServiceRequest.getDescriptor() .getEnumTypes() .get(0); } private static final CheckIfServiceHasUsage[] VALUES = values(); public static CheckIfServiceHasUsage 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 CheckIfServiceHasUsage(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage) } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</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> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</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 DISABLE_DEPENDENT_SERVICES_FIELD_NUMBER = 2; private boolean disableDependentServices_ = false; /** * * * <pre> * Indicates if services that are enabled and which depend on this service * should also be disabled. If not set, an error will be generated if any * enabled services depend on the service to be disabled. When set, the * service, and any enabled services that depend on it, will be disabled * together. * </pre> * * <code>bool disable_dependent_services = 2;</code> * * @return The disableDependentServices. */ @java.lang.Override public boolean getDisableDependentServices() { return disableDependentServices_; } public static final int CHECK_IF_SERVICE_HAS_USAGE_FIELD_NUMBER = 3; private int checkIfServiceHasUsage_ = 0; /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @return The enum numeric value on the wire for checkIfServiceHasUsage. */ @java.lang.Override public int getCheckIfServiceHasUsageValue() { return checkIfServiceHasUsage_; } /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @return The checkIfServiceHasUsage. */ @java.lang.Override public com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage getCheckIfServiceHasUsage() { com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage result = com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage.forNumber( checkIfServiceHasUsage_); return result == null ? com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage.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(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (disableDependentServices_ != false) { output.writeBool(2, disableDependentServices_); } if (checkIfServiceHasUsage_ != com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage .CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED .getNumber()) { output.writeEnum(3, checkIfServiceHasUsage_); } 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 (disableDependentServices_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(2, disableDependentServices_); } if (checkIfServiceHasUsage_ != com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage .CHECK_IF_SERVICE_HAS_USAGE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(3, checkIfServiceHasUsage_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.api.serviceusage.v1.DisableServiceRequest)) { return super.equals(obj); } com.google.api.serviceusage.v1.DisableServiceRequest other = (com.google.api.serviceusage.v1.DisableServiceRequest) obj; if (!getName().equals(other.getName())) return false; if (getDisableDependentServices() != other.getDisableDependentServices()) return false; if (checkIfServiceHasUsage_ != other.checkIfServiceHasUsage_) 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) + DISABLE_DEPENDENT_SERVICES_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getDisableDependentServices()); hash = (37 * hash) + CHECK_IF_SERVICE_HAS_USAGE_FIELD_NUMBER; hash = (53 * hash) + checkIfServiceHasUsage_; hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.api.serviceusage.v1.DisableServiceRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.api.serviceusage.v1.DisableServiceRequest 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 `DisableService` method. * </pre> * * Protobuf type {@code google.api.serviceusage.v1.DisableServiceRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.api.serviceusage.v1.DisableServiceRequest) com.google.api.serviceusage.v1.DisableServiceRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.api.serviceusage.v1.ServiceUsageProto .internal_static_google_api_serviceusage_v1_DisableServiceRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.api.serviceusage.v1.ServiceUsageProto .internal_static_google_api_serviceusage_v1_DisableServiceRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.api.serviceusage.v1.DisableServiceRequest.class, com.google.api.serviceusage.v1.DisableServiceRequest.Builder.class); } // Construct using com.google.api.serviceusage.v1.DisableServiceRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; disableDependentServices_ = false; checkIfServiceHasUsage_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.api.serviceusage.v1.ServiceUsageProto .internal_static_google_api_serviceusage_v1_DisableServiceRequest_descriptor; } @java.lang.Override public com.google.api.serviceusage.v1.DisableServiceRequest getDefaultInstanceForType() { return com.google.api.serviceusage.v1.DisableServiceRequest.getDefaultInstance(); } @java.lang.Override public com.google.api.serviceusage.v1.DisableServiceRequest build() { com.google.api.serviceusage.v1.DisableServiceRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.api.serviceusage.v1.DisableServiceRequest buildPartial() { com.google.api.serviceusage.v1.DisableServiceRequest result = new com.google.api.serviceusage.v1.DisableServiceRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.api.serviceusage.v1.DisableServiceRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.disableDependentServices_ = disableDependentServices_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.checkIfServiceHasUsage_ = checkIfServiceHasUsage_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.api.serviceusage.v1.DisableServiceRequest) { return mergeFrom((com.google.api.serviceusage.v1.DisableServiceRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.api.serviceusage.v1.DisableServiceRequest other) { if (other == com.google.api.serviceusage.v1.DisableServiceRequest.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (other.getDisableDependentServices() != false) { setDisableDependentServices(other.getDisableDependentServices()); } if (other.checkIfServiceHasUsage_ != 0) { setCheckIfServiceHasUsageValue(other.getCheckIfServiceHasUsageValue()); } 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: { disableDependentServices_ = input.readBool(); bitField0_ |= 0x00000002; break; } // case 16 case 24: { checkIfServiceHasUsage_ = input.readEnum(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</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> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</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> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</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> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</code> * * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Name of the consumer and service to disable the service on. * * The enable and disable methods currently only support projects. * * An example name would be: * `projects/123/services/serviceusage.googleapis.com` where `123` is the * project number. * </pre> * * <code>string name = 1;</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 boolean disableDependentServices_; /** * * * <pre> * Indicates if services that are enabled and which depend on this service * should also be disabled. If not set, an error will be generated if any * enabled services depend on the service to be disabled. When set, the * service, and any enabled services that depend on it, will be disabled * together. * </pre> * * <code>bool disable_dependent_services = 2;</code> * * @return The disableDependentServices. */ @java.lang.Override public boolean getDisableDependentServices() { return disableDependentServices_; } /** * * * <pre> * Indicates if services that are enabled and which depend on this service * should also be disabled. If not set, an error will be generated if any * enabled services depend on the service to be disabled. When set, the * service, and any enabled services that depend on it, will be disabled * together. * </pre> * * <code>bool disable_dependent_services = 2;</code> * * @param value The disableDependentServices to set. * @return This builder for chaining. */ public Builder setDisableDependentServices(boolean value) { disableDependentServices_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Indicates if services that are enabled and which depend on this service * should also be disabled. If not set, an error will be generated if any * enabled services depend on the service to be disabled. When set, the * service, and any enabled services that depend on it, will be disabled * together. * </pre> * * <code>bool disable_dependent_services = 2;</code> * * @return This builder for chaining. */ public Builder clearDisableDependentServices() { bitField0_ = (bitField0_ & ~0x00000002); disableDependentServices_ = false; onChanged(); return this; } private int checkIfServiceHasUsage_ = 0; /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @return The enum numeric value on the wire for checkIfServiceHasUsage. */ @java.lang.Override public int getCheckIfServiceHasUsageValue() { return checkIfServiceHasUsage_; } /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @param value The enum numeric value on the wire for checkIfServiceHasUsage to set. * @return This builder for chaining. */ public Builder setCheckIfServiceHasUsageValue(int value) { checkIfServiceHasUsage_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @return The checkIfServiceHasUsage. */ @java.lang.Override public com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage getCheckIfServiceHasUsage() { com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage result = com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage.forNumber( checkIfServiceHasUsage_); return result == null ? com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage.UNRECOGNIZED : result; } /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @param value The checkIfServiceHasUsage to set. * @return This builder for chaining. */ public Builder setCheckIfServiceHasUsage( com.google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; checkIfServiceHasUsage_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Defines the behavior for checking service usage when disabling a service. * </pre> * * <code> * .google.api.serviceusage.v1.DisableServiceRequest.CheckIfServiceHasUsage check_if_service_has_usage = 3; * </code> * * @return This builder for chaining. */ public Builder clearCheckIfServiceHasUsage() { bitField0_ = (bitField0_ & ~0x00000004); checkIfServiceHasUsage_ = 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.api.serviceusage.v1.DisableServiceRequest) } // @@protoc_insertion_point(class_scope:google.api.serviceusage.v1.DisableServiceRequest) private static final com.google.api.serviceusage.v1.DisableServiceRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.api.serviceusage.v1.DisableServiceRequest(); } public static com.google.api.serviceusage.v1.DisableServiceRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DisableServiceRequest> PARSER = new com.google.protobuf.AbstractParser<DisableServiceRequest>() { @java.lang.Override public DisableServiceRequest 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<DisableServiceRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DisableServiceRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.api.serviceusage.v1.DisableServiceRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,893
java-profiler/grpc-google-cloud-profiler-v2/src/main/java/com/google/devtools/cloudprofiler/v2/ProfilerServiceGrpc.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.devtools.cloudprofiler.v2; import static io.grpc.MethodDescriptor.generateFullMethodName; /** * * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: google/devtools/cloudprofiler/v2/profiler.proto") @io.grpc.stub.annotations.GrpcGenerated public final class ProfilerServiceGrpc { private ProfilerServiceGrpc() {} public static final java.lang.String SERVICE_NAME = "google.devtools.cloudprofiler.v2.ProfilerService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.CreateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getCreateProfileMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateProfile", requestType = com.google.devtools.cloudprofiler.v2.CreateProfileRequest.class, responseType = com.google.devtools.cloudprofiler.v2.Profile.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.CreateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getCreateProfileMethod() { io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.CreateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getCreateProfileMethod; if ((getCreateProfileMethod = ProfilerServiceGrpc.getCreateProfileMethod) == null) { synchronized (ProfilerServiceGrpc.class) { if ((getCreateProfileMethod = ProfilerServiceGrpc.getCreateProfileMethod) == null) { ProfilerServiceGrpc.getCreateProfileMethod = getCreateProfileMethod = io.grpc.MethodDescriptor .<com.google.devtools.cloudprofiler.v2.CreateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.devtools.cloudprofiler.v2.CreateProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.devtools.cloudprofiler.v2.Profile.getDefaultInstance())) .setSchemaDescriptor( new ProfilerServiceMethodDescriptorSupplier("CreateProfile")) .build(); } } } return getCreateProfileMethod; } private static volatile io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getCreateOfflineProfileMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "CreateOfflineProfile", requestType = com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest.class, responseType = com.google.devtools.cloudprofiler.v2.Profile.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getCreateOfflineProfileMethod() { io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getCreateOfflineProfileMethod; if ((getCreateOfflineProfileMethod = ProfilerServiceGrpc.getCreateOfflineProfileMethod) == null) { synchronized (ProfilerServiceGrpc.class) { if ((getCreateOfflineProfileMethod = ProfilerServiceGrpc.getCreateOfflineProfileMethod) == null) { ProfilerServiceGrpc.getCreateOfflineProfileMethod = getCreateOfflineProfileMethod = io.grpc.MethodDescriptor .<com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName( generateFullMethodName(SERVICE_NAME, "CreateOfflineProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.devtools.cloudprofiler.v2.Profile.getDefaultInstance())) .setSchemaDescriptor( new ProfilerServiceMethodDescriptorSupplier("CreateOfflineProfile")) .build(); } } } return getCreateOfflineProfileMethod; } private static volatile io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.UpdateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getUpdateProfileMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "UpdateProfile", requestType = com.google.devtools.cloudprofiler.v2.UpdateProfileRequest.class, responseType = com.google.devtools.cloudprofiler.v2.Profile.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.UpdateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getUpdateProfileMethod() { io.grpc.MethodDescriptor< com.google.devtools.cloudprofiler.v2.UpdateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> getUpdateProfileMethod; if ((getUpdateProfileMethod = ProfilerServiceGrpc.getUpdateProfileMethod) == null) { synchronized (ProfilerServiceGrpc.class) { if ((getUpdateProfileMethod = ProfilerServiceGrpc.getUpdateProfileMethod) == null) { ProfilerServiceGrpc.getUpdateProfileMethod = getUpdateProfileMethod = io.grpc.MethodDescriptor .<com.google.devtools.cloudprofiler.v2.UpdateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile> newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateProfile")) .setSampledToLocalTracing(true) .setRequestMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.devtools.cloudprofiler.v2.UpdateProfileRequest .getDefaultInstance())) .setResponseMarshaller( io.grpc.protobuf.ProtoUtils.marshaller( com.google.devtools.cloudprofiler.v2.Profile.getDefaultInstance())) .setSchemaDescriptor( new ProfilerServiceMethodDescriptorSupplier("UpdateProfile")) .build(); } } } return getUpdateProfileMethod; } /** Creates a new async stub that supports all call types for the service */ public static ProfilerServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceStub>() { @java.lang.Override public ProfilerServiceStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceStub(channel, callOptions); } }; return ProfilerServiceStub.newStub(factory, channel); } /** Creates a new blocking-style stub that supports all types of calls on the service */ public static ProfilerServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceBlockingV2Stub>() { @java.lang.Override public ProfilerServiceBlockingV2Stub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceBlockingV2Stub(channel, callOptions); } }; return ProfilerServiceBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static ProfilerServiceBlockingStub newBlockingStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceBlockingStub>() { @java.lang.Override public ProfilerServiceBlockingStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceBlockingStub(channel, callOptions); } }; return ProfilerServiceBlockingStub.newStub(factory, channel); } /** Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static ProfilerServiceFutureStub newFutureStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<ProfilerServiceFutureStub>() { @java.lang.Override public ProfilerServiceFutureStub newStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceFutureStub(channel, callOptions); } }; return ProfilerServiceFutureStub.newStub(factory, channel); } /** * * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ public interface AsyncService { /** * * * <pre> * CreateProfile creates a new profile resource in the online mode. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * The server ensures that the new profiles are created at a constant rate per * deployment, so the creation request may hang for some time until the next * profile session is available. * The request may fail with ABORTED error if the creation is not available * within ~1m, the response will indicate the duration of the backoff the * client should take before attempting creating a profile again. The backoff * duration is returned in google.rpc.RetryInfo extension on the response * status. To a gRPC client, the extension will be return as a * binary-serialized proto in the trailing metadata item named * "google.rpc.retryinfo-bin". * </pre> */ default void createProfile( com.google.devtools.cloudprofiler.v2.CreateProfileRequest request, io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCreateProfileMethod(), responseObserver); } /** * * * <pre> * CreateOfflineProfile creates a new profile resource in the offline * mode. The client provides the profile to create along with the profile * bytes, the server records it. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ default void createOfflineProfile( com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest request, io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getCreateOfflineProfileMethod(), responseObserver); } /** * * * <pre> * UpdateProfile updates the profile bytes and labels on the profile resource * created in the online mode. Updating the bytes for profiles created in the * offline mode is currently not supported: the profile content must be * provided at the time of the profile creation. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ default void updateProfile( com.google.devtools.cloudprofiler.v2.UpdateProfileRequest request, io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile> responseObserver) { io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall( getUpdateProfileMethod(), responseObserver); } } /** * Base class for the server implementation of the service ProfilerService. * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ public abstract static class ProfilerServiceImplBase implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return ProfilerServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service ProfilerService. * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ public static final class ProfilerServiceStub extends io.grpc.stub.AbstractAsyncStub<ProfilerServiceStub> { private ProfilerServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfilerServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceStub(channel, callOptions); } /** * * * <pre> * CreateProfile creates a new profile resource in the online mode. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * The server ensures that the new profiles are created at a constant rate per * deployment, so the creation request may hang for some time until the next * profile session is available. * The request may fail with ABORTED error if the creation is not available * within ~1m, the response will indicate the duration of the backoff the * client should take before attempting creating a profile again. The backoff * duration is returned in google.rpc.RetryInfo extension on the response * status. To a gRPC client, the extension will be return as a * binary-serialized proto in the trailing metadata item named * "google.rpc.retryinfo-bin". * </pre> */ public void createProfile( com.google.devtools.cloudprofiler.v2.CreateProfileRequest request, io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateProfileMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * CreateOfflineProfile creates a new profile resource in the offline * mode. The client provides the profile to create along with the profile * bytes, the server records it. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public void createOfflineProfile( com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest request, io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getCreateOfflineProfileMethod(), getCallOptions()), request, responseObserver); } /** * * * <pre> * UpdateProfile updates the profile bytes and labels on the profile resource * created in the online mode. Updating the bytes for profiles created in the * offline mode is currently not supported: the profile content must be * provided at the time of the profile creation. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public void updateProfile( com.google.devtools.cloudprofiler.v2.UpdateProfileRequest request, io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile> responseObserver) { io.grpc.stub.ClientCalls.asyncUnaryCall( getChannel().newCall(getUpdateProfileMethod(), getCallOptions()), request, responseObserver); } } /** * A stub to allow clients to do synchronous rpc calls to service ProfilerService. * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ public static final class ProfilerServiceBlockingV2Stub extends io.grpc.stub.AbstractBlockingStub<ProfilerServiceBlockingV2Stub> { private ProfilerServiceBlockingV2Stub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfilerServiceBlockingV2Stub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceBlockingV2Stub(channel, callOptions); } /** * * * <pre> * CreateProfile creates a new profile resource in the online mode. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * The server ensures that the new profiles are created at a constant rate per * deployment, so the creation request may hang for some time until the next * profile session is available. * The request may fail with ABORTED error if the creation is not available * within ~1m, the response will indicate the duration of the backoff the * client should take before attempting creating a profile again. The backoff * duration is returned in google.rpc.RetryInfo extension on the response * status. To a gRPC client, the extension will be return as a * binary-serialized proto in the trailing metadata item named * "google.rpc.retryinfo-bin". * </pre> */ public com.google.devtools.cloudprofiler.v2.Profile createProfile( com.google.devtools.cloudprofiler.v2.CreateProfileRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateProfileMethod(), getCallOptions(), request); } /** * * * <pre> * CreateOfflineProfile creates a new profile resource in the offline * mode. The client provides the profile to create along with the profile * bytes, the server records it. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public com.google.devtools.cloudprofiler.v2.Profile createOfflineProfile( com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateOfflineProfileMethod(), getCallOptions(), request); } /** * * * <pre> * UpdateProfile updates the profile bytes and labels on the profile resource * created in the online mode. Updating the bytes for profiles created in the * offline mode is currently not supported: the profile content must be * provided at the time of the profile creation. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public com.google.devtools.cloudprofiler.v2.Profile updateProfile( com.google.devtools.cloudprofiler.v2.UpdateProfileRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateProfileMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do limited synchronous rpc calls to service ProfilerService. * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ public static final class ProfilerServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<ProfilerServiceBlockingStub> { private ProfilerServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfilerServiceBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceBlockingStub(channel, callOptions); } /** * * * <pre> * CreateProfile creates a new profile resource in the online mode. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * The server ensures that the new profiles are created at a constant rate per * deployment, so the creation request may hang for some time until the next * profile session is available. * The request may fail with ABORTED error if the creation is not available * within ~1m, the response will indicate the duration of the backoff the * client should take before attempting creating a profile again. The backoff * duration is returned in google.rpc.RetryInfo extension on the response * status. To a gRPC client, the extension will be return as a * binary-serialized proto in the trailing metadata item named * "google.rpc.retryinfo-bin". * </pre> */ public com.google.devtools.cloudprofiler.v2.Profile createProfile( com.google.devtools.cloudprofiler.v2.CreateProfileRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateProfileMethod(), getCallOptions(), request); } /** * * * <pre> * CreateOfflineProfile creates a new profile resource in the offline * mode. The client provides the profile to create along with the profile * bytes, the server records it. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public com.google.devtools.cloudprofiler.v2.Profile createOfflineProfile( com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getCreateOfflineProfileMethod(), getCallOptions(), request); } /** * * * <pre> * UpdateProfile updates the profile bytes and labels on the profile resource * created in the online mode. Updating the bytes for profiles created in the * offline mode is currently not supported: the profile content must be * provided at the time of the profile creation. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public com.google.devtools.cloudprofiler.v2.Profile updateProfile( com.google.devtools.cloudprofiler.v2.UpdateProfileRequest request) { return io.grpc.stub.ClientCalls.blockingUnaryCall( getChannel(), getUpdateProfileMethod(), getCallOptions(), request); } } /** * A stub to allow clients to do ListenableFuture-style rpc calls to service ProfilerService. * * <pre> * Manage the collection of continuous profiling data provided by profiling * agents running in the cloud or by an offline provider of profiling data. * __The APIs listed in this service are intended for use within our profiler * agents only.__ * </pre> */ public static final class ProfilerServiceFutureStub extends io.grpc.stub.AbstractFutureStub<ProfilerServiceFutureStub> { private ProfilerServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected ProfilerServiceFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new ProfilerServiceFutureStub(channel, callOptions); } /** * * * <pre> * CreateProfile creates a new profile resource in the online mode. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * The server ensures that the new profiles are created at a constant rate per * deployment, so the creation request may hang for some time until the next * profile session is available. * The request may fail with ABORTED error if the creation is not available * within ~1m, the response will indicate the duration of the backoff the * client should take before attempting creating a profile again. The backoff * duration is returned in google.rpc.RetryInfo extension on the response * status. To a gRPC client, the extension will be return as a * binary-serialized proto in the trailing metadata item named * "google.rpc.retryinfo-bin". * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.devtools.cloudprofiler.v2.Profile> createProfile(com.google.devtools.cloudprofiler.v2.CreateProfileRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateProfileMethod(), getCallOptions()), request); } /** * * * <pre> * CreateOfflineProfile creates a new profile resource in the offline * mode. The client provides the profile to create along with the profile * bytes, the server records it. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.devtools.cloudprofiler.v2.Profile> createOfflineProfile( com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getCreateOfflineProfileMethod(), getCallOptions()), request); } /** * * * <pre> * UpdateProfile updates the profile bytes and labels on the profile resource * created in the online mode. Updating the bytes for profiles created in the * offline mode is currently not supported: the profile content must be * provided at the time of the profile creation. * _Direct use of this API is discouraged, please use a [supported * profiler * agent](https://cloud.google.com/profiler/docs/about-profiler#profiling_agent) * instead for profile collection._ * </pre> */ public com.google.common.util.concurrent.ListenableFuture< com.google.devtools.cloudprofiler.v2.Profile> updateProfile(com.google.devtools.cloudprofiler.v2.UpdateProfileRequest request) { return io.grpc.stub.ClientCalls.futureUnaryCall( getChannel().newCall(getUpdateProfileMethod(), getCallOptions()), request); } } private static final int METHODID_CREATE_PROFILE = 0; private static final int METHODID_CREATE_OFFLINE_PROFILE = 1; private static final int METHODID_UPDATE_PROFILE = 2; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final AsyncService serviceImpl; private final int methodId; MethodHandlers(AsyncService serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_CREATE_PROFILE: serviceImpl.createProfile( (com.google.devtools.cloudprofiler.v2.CreateProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile>) responseObserver); break; case METHODID_CREATE_OFFLINE_PROFILE: serviceImpl.createOfflineProfile( (com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile>) responseObserver); break; case METHODID_UPDATE_PROFILE: serviceImpl.updateProfile( (com.google.devtools.cloudprofiler.v2.UpdateProfileRequest) request, (io.grpc.stub.StreamObserver<com.google.devtools.cloudprofiler.v2.Profile>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getCreateProfileMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.devtools.cloudprofiler.v2.CreateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile>( service, METHODID_CREATE_PROFILE))) .addMethod( getCreateOfflineProfileMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.devtools.cloudprofiler.v2.CreateOfflineProfileRequest, com.google.devtools.cloudprofiler.v2.Profile>( service, METHODID_CREATE_OFFLINE_PROFILE))) .addMethod( getUpdateProfileMethod(), io.grpc.stub.ServerCalls.asyncUnaryCall( new MethodHandlers< com.google.devtools.cloudprofiler.v2.UpdateProfileRequest, com.google.devtools.cloudprofiler.v2.Profile>( service, METHODID_UPDATE_PROFILE))) .build(); } private abstract static class ProfilerServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { ProfilerServiceBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.google.devtools.cloudprofiler.v2.ProfilerProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("ProfilerService"); } } private static final class ProfilerServiceFileDescriptorSupplier extends ProfilerServiceBaseDescriptorSupplier { ProfilerServiceFileDescriptorSupplier() {} } private static final class ProfilerServiceMethodDescriptorSupplier extends ProfilerServiceBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final java.lang.String methodName; ProfilerServiceMethodDescriptorSupplier(java.lang.String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (ProfilerServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new ProfilerServiceFileDescriptorSupplier()) .addMethod(getCreateProfileMethod()) .addMethod(getCreateOfflineProfileMethod()) .addMethod(getUpdateProfileMethod()) .build(); } } } return result; } }
apache/druid
36,549
server/src/test/java/org/apache/druid/server/coordination/ServerManagerTest.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.druid.server.coordination; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.testing.fieldbinder.Bind; import com.google.inject.testing.fieldbinder.BoundFieldModule; import org.apache.druid.client.cache.Cache; import org.apache.druid.client.cache.CacheConfig; import org.apache.druid.client.cache.CachePopulator; import org.apache.druid.client.cache.CachePopulatorStats; import org.apache.druid.client.cache.ForegroundCachePopulator; import org.apache.druid.client.cache.LocalCacheProvider; import org.apache.druid.error.DruidException; import org.apache.druid.guice.annotations.Smile; import org.apache.druid.jackson.DefaultObjectMapper; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.Intervals; import org.apache.druid.java.util.common.Pair; import org.apache.druid.java.util.common.concurrent.Execs; import org.apache.druid.java.util.common.granularity.Granularities; import org.apache.druid.java.util.common.granularity.Granularity; import org.apache.druid.java.util.common.guava.Sequence; import org.apache.druid.java.util.common.guava.Sequences; import org.apache.druid.java.util.common.guava.Yielder; import org.apache.druid.java.util.common.guava.YieldingAccumulator; import org.apache.druid.java.util.common.guava.YieldingSequenceBase; import org.apache.druid.java.util.emitter.EmittingLogger; import org.apache.druid.java.util.emitter.service.ServiceEmitter; import org.apache.druid.query.DataSource; import org.apache.druid.query.DefaultQueryMetrics; import org.apache.druid.query.DefaultQueryRunnerFactoryConglomerate; import org.apache.druid.query.Druids; import org.apache.druid.query.ForwardingQueryProcessingPool; import org.apache.druid.query.NoopQueryRunner; import org.apache.druid.query.Query; import org.apache.druid.query.QueryDataSource; import org.apache.druid.query.QueryMetrics; import org.apache.druid.query.QueryPlus; import org.apache.druid.query.QueryProcessingPool; import org.apache.druid.query.QueryRunner; import org.apache.druid.query.QueryRunnerFactory; import org.apache.druid.query.QueryRunnerFactoryConglomerate; import org.apache.druid.query.QueryToolChest; import org.apache.druid.query.QueryUnsupportedException; import org.apache.druid.query.RestrictedDataSource; import org.apache.druid.query.Result; import org.apache.druid.query.SegmentDescriptor; import org.apache.druid.query.TableDataSource; import org.apache.druid.query.aggregation.MetricManipulationFn; import org.apache.druid.query.context.DefaultResponseContext; import org.apache.druid.query.context.ResponseContext; import org.apache.druid.query.planning.ExecutionVertex; import org.apache.druid.query.policy.NoRestrictionPolicy; import org.apache.druid.query.policy.NoopPolicyEnforcer; import org.apache.druid.query.policy.PolicyEnforcer; import org.apache.druid.query.policy.RestrictAllTablesPolicyEnforcer; import org.apache.druid.query.search.SearchQuery; import org.apache.druid.query.search.SearchResultValue; import org.apache.druid.query.spec.MultipleSpecificSegmentSpec; import org.apache.druid.segment.ReferenceCountedSegmentProvider; import org.apache.druid.segment.Segment; import org.apache.druid.segment.TestSegmentUtils; import org.apache.druid.segment.TestSegmentUtils.SegmentForTesting; import org.apache.druid.segment.loading.SegmentLoadingException; import org.apache.druid.server.SegmentManager; import org.apache.druid.server.ServerManager; import org.apache.druid.server.initialization.ServerConfig; import org.apache.druid.server.metrics.NoopServiceEmitter; import org.apache.druid.test.utils.TestSegmentCacheManager; import org.apache.druid.timeline.DataSegment; import org.apache.druid.timeline.TimelineObjectHolder; import org.apache.druid.timeline.VersionedIntervalTimeline; import org.apache.druid.timeline.partition.PartitionChunk; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertThrows; public class ServerManagerTest { private static ImmutableSet<DataSegment> DATA_SEGMENTS = new ImmutableSet.Builder<DataSegment>() .add(TestSegmentUtils.makeSegment("test", "1", Intervals.of("P1d/2011-04-01"))) .add(TestSegmentUtils.makeSegment("test", "1", Intervals.of("P1d/2011-04-02"))) .add(TestSegmentUtils.makeSegment("test", "2", Intervals.of("P1d/2011-04-02"))) .add(TestSegmentUtils.makeSegment("test", "1", Intervals.of("P1d/2011-04-03"))) .add(TestSegmentUtils.makeSegment("test", "1", Intervals.of("P1d/2011-04-04"))) .add(TestSegmentUtils.makeSegment("test", "1", Intervals.of("P1d/2011-04-05"))) .add(TestSegmentUtils.makeSegment("test", "2", Intervals.of("PT1h/2011-04-04T01"))) .add(TestSegmentUtils.makeSegment("test", "2", Intervals.of("PT1h/2011-04-04T02"))) .add(TestSegmentUtils.makeSegment("test", "2", Intervals.of("PT1h/2011-04-04T03"))) .add(TestSegmentUtils.makeSegment("test", "2", Intervals.of("PT1h/2011-04-04T05"))) .add(TestSegmentUtils.makeSegment("test", "2", Intervals.of("PT1h/2011-04-04T06"))) .add(TestSegmentUtils.makeSegment("test2", "1", Intervals.of("P1d/2011-04-01"))) .add(TestSegmentUtils.makeSegment("test2", "1", Intervals.of("P1d/2011-04-02"))) .build(); @Bind private QueryRunnerFactoryConglomerate conglomerate; @Bind private SegmentManager segmentManager; @Bind private PolicyEnforcer policyEnforcer; @Bind private ServerConfig serverConfig; @Bind private ServiceEmitter serviceEmitter; @Bind private QueryProcessingPool queryProcessingPool; @Bind private CachePopulator cachePopulator; @Bind @Smile private ObjectMapper objectMapper; @Bind private Cache cache; @Bind private CacheConfig cacheConfig; private MyQueryRunnerFactory factory; private ExecutorService serverManagerExec; @Inject private ServerManager serverManager; @Before public void setUp() { serviceEmitter = new NoopServiceEmitter(); EmittingLogger.registerEmitter(new NoopServiceEmitter()); segmentManager = new SegmentManager(new TestSegmentCacheManager(DATA_SEGMENTS)); for (DataSegment segment : DATA_SEGMENTS) { loadQueryable(segment.getDataSource(), segment.getVersion(), segment.getInterval()); } factory = new MyQueryRunnerFactory(new CountDownLatch(1), new CountDownLatch(1), new CountDownLatch(1)); // Only SearchQuery is supported in this test. conglomerate = DefaultQueryRunnerFactoryConglomerate.buildFromQueryRunnerFactories(ImmutableMap.of( SearchQuery.class, factory )); serverManagerExec = Execs.multiThreaded(2, "ServerManagerTest-%d"); queryProcessingPool = new ForwardingQueryProcessingPool(serverManagerExec); cachePopulator = new ForegroundCachePopulator(new DefaultObjectMapper(), new CachePopulatorStats(), -1); objectMapper = new DefaultObjectMapper(); cache = new LocalCacheProvider().get(); cacheConfig = new CacheConfig(); serverConfig = new ServerConfig(); policyEnforcer = NoopPolicyEnforcer.instance(); Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this); } @Test public void testSimpleGet() { Future future = assertQueryable( Granularities.DAY, "test", Intervals.of("P1d/2011-04-01"), ImmutableList.of(new Pair<>("1", Intervals.of("P1d/2011-04-01"))) ); waitForTestVerificationAndCleanup(future); future = assertQueryable( Granularities.DAY, "test", Intervals.of("P2d/2011-04-02"), ImmutableList.of( new Pair<>("1", Intervals.of("P1d/2011-04-01")), new Pair<>("2", Intervals.of("P1d/2011-04-02")) ) ); waitForTestVerificationAndCleanup(future); } @Test public void testSimpleGetTombstone() { Future future = assertQueryable( Granularities.DAY, "testTombstone", Intervals.of("P1d/2011-04-01"), Collections.emptyList() // tombstone returns no data ); waitForTestVerificationAndCleanup(future); } @Test public void testDelete1() { final String dataSouce = "test"; final Interval interval = Intervals.of("2011-04-01/2011-04-02"); Future future = assertQueryable( Granularities.DAY, dataSouce, interval, ImmutableList.of( new Pair<>("2", interval) ) ); waitForTestVerificationAndCleanup(future); dropQueryable(dataSouce, "2", interval); future = assertQueryable( Granularities.DAY, dataSouce, interval, ImmutableList.of( new Pair<>("1", interval) ) ); waitForTestVerificationAndCleanup(future); } @Test public void testDelete2() { loadQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); Future future = assertQueryable( Granularities.DAY, "test", Intervals.of("2011-04-04/2011-04-06"), ImmutableList.of( new Pair<>("3", Intervals.of("2011-04-04/2011-04-05")) ) ); waitForTestVerificationAndCleanup(future); dropQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); dropQueryable("test", "1", Intervals.of("2011-04-04/2011-04-05")); future = assertQueryable( Granularities.HOUR, "test", Intervals.of("2011-04-04/2011-04-04T06"), ImmutableList.of( new Pair<>("2", Intervals.of("2011-04-04T00/2011-04-04T01")), new Pair<>("2", Intervals.of("2011-04-04T01/2011-04-04T02")), new Pair<>("2", Intervals.of("2011-04-04T02/2011-04-04T03")), new Pair<>("2", Intervals.of("2011-04-04T04/2011-04-04T05")), new Pair<>("2", Intervals.of("2011-04-04T05/2011-04-04T06")) ) ); waitForTestVerificationAndCleanup(future); future = assertQueryable( Granularities.HOUR, "test", Intervals.of("2011-04-04/2011-04-04T03"), ImmutableList.of( new Pair<>("2", Intervals.of("2011-04-04T00/2011-04-04T01")), new Pair<>("2", Intervals.of("2011-04-04T01/2011-04-04T02")), new Pair<>("2", Intervals.of("2011-04-04T02/2011-04-04T03")) ) ); waitForTestVerificationAndCleanup(future); future = assertQueryable( Granularities.HOUR, "test", Intervals.of("2011-04-04T04/2011-04-04T06"), ImmutableList.of( new Pair<>("2", Intervals.of("2011-04-04T04/2011-04-04T05")), new Pair<>("2", Intervals.of("2011-04-04T05/2011-04-04T06")) ) ); waitForTestVerificationAndCleanup(future); } @Test public void testReferenceCounting() throws Exception { loadQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); Future future = assertQueryable( Granularities.DAY, "test", Intervals.of("2011-04-04/2011-04-06"), ImmutableList.of( new Pair<>("3", Intervals.of("2011-04-04/2011-04-05")) ) ); factory.notifyLatch.await(1000, TimeUnit.MILLISECONDS); Assert.assertEquals(1, factory.getReferenceProviders().size()); for (ReferenceCountedSegmentProvider referenceCountingSegment : factory.getReferenceProviders()) { Assert.assertEquals(1, referenceCountingSegment.getNumReferences()); } factory.waitYieldLatch.countDown(); Assert.assertEquals(1, factory.getSegments().size()); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertFalse(segment.isClosed()); } factory.waitLatch.countDown(); future.get(); dropQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertTrue(segment.isClosed()); } } @Test public void testReferenceCounting_whileQueryExecuting() throws Exception { loadQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); Future future = assertQueryable( Granularities.DAY, "test", Intervals.of("2011-04-04/2011-04-06"), ImmutableList.of( new Pair<>("3", Intervals.of("2011-04-04/2011-04-05")) ) ); factory.notifyLatch.await(1000, TimeUnit.MILLISECONDS); Assert.assertEquals(1, factory.getReferenceProviders().size()); for (ReferenceCountedSegmentProvider referenceCountingSegment : factory.getReferenceProviders()) { Assert.assertEquals(1, referenceCountingSegment.getNumReferences()); } factory.waitYieldLatch.countDown(); Assert.assertEquals(1, factory.getSegments().size()); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertFalse(segment.isClosed()); } dropQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertFalse(segment.isClosed()); } factory.waitLatch.countDown(); future.get(); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertTrue(segment.isClosed()); } } @Test public void testReferenceCounting_multipleDrops() throws Exception { loadQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); Future future = assertQueryable( Granularities.DAY, "test", Intervals.of("2011-04-04/2011-04-06"), ImmutableList.of( new Pair<>("3", Intervals.of("2011-04-04/2011-04-05")) ) ); factory.notifyLatch.await(1000, TimeUnit.MILLISECONDS); Assert.assertEquals(1, factory.getReferenceProviders().size()); for (ReferenceCountedSegmentProvider referenceCountingSegment : factory.getReferenceProviders()) { Assert.assertEquals(1, referenceCountingSegment.getNumReferences()); } factory.waitYieldLatch.countDown(); Assert.assertEquals(1, factory.getSegments().size()); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertFalse(segment.isClosed()); } dropQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); dropQueryable("test", "3", Intervals.of("2011-04-04/2011-04-05")); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertFalse(segment.isClosed()); } factory.waitLatch.countDown(); future.get(); for (TestSegmentUtils.SegmentForTesting segment : factory.getSegments()) { Assert.assertTrue(segment.isClosed()); } } @Test public void testReferenceCounting_restrictedSegment() throws Exception { factory = new MyQueryRunnerFactory(new CountDownLatch(1), new CountDownLatch(1), new CountDownLatch(2)); conglomerate = DefaultQueryRunnerFactoryConglomerate.buildFromQueryRunnerFactories(ImmutableMap.of( SearchQuery.class, factory )); serverManager = Guice.createInjector(BoundFieldModule.of(this)).getInstance(ServerManager.class); Interval interval = Intervals.of("P1d/2011-04-01"); loadQueryable("test", "1", interval); SearchQuery query = searchQuery("test", interval, Granularities.ALL); SearchQuery queryOnRestricted = searchQuery(RestrictedDataSource.create( TableDataSource.create("test"), NoRestrictionPolicy.instance() ), interval, Granularities.ALL); Future<?> future = assertQuery(query, interval, ImmutableList.of(new Pair<>("1", interval))); // sleep for 1s to make sure the first query hits/finishes factory.createRunner first, since we can't test adapter // and segmentReference for RestrictedSegment unless there's already a ReferenceCountingSegment. Thread.sleep(1000L); Future<?> futureOnRestricted = assertQuery( queryOnRestricted, interval, ImmutableList.of(new Pair<>("1", interval)) ); Assert.assertTrue(factory.notifyLatch.await(1000, TimeUnit.MILLISECONDS)); Assert.assertEquals(1, factory.getReferenceProviders().size()); // Expect 2 references here: 1 for query and 1 for queryOnRestricted Assert.assertEquals(2, factory.getReferenceProviders().get(0).getNumReferences()); factory.waitYieldLatch.countDown(); factory.waitLatch.countDown(); future.get(); futureOnRestricted.get(); Assert.assertEquals(1, factory.getReferenceProviders().size()); // no references since both query are finished Assert.assertEquals(0, factory.getReferenceProviders().get(0).getNumReferences()); } @Test public void testGetQueryRunnerForIntervals_whenTimelineIsMissingReturningNoopQueryRunner() { final Interval interval = Intervals.of("0000-01-01/P1D"); final QueryRunner<Result<SearchResultValue>> queryRunner = serverManager.getQueryRunnerForIntervals( searchQuery("unknown_datasource", interval, Granularities.ALL), Collections.singletonList(interval) ); Assert.assertSame(NoopQueryRunner.class, queryRunner.getClass()); } @Test public void testGetQueryRunnerForSegments_whenTimelineIsMissingReportingMissingSegmentsOnQueryDataSource() { final Interval interval = Intervals.of("0000-01-01/P1D"); final SearchQuery query = searchQueryWithQueryDataSource("unknown_datasource", interval, Granularities.ALL); final List<SegmentDescriptor> unknownSegments = Collections.singletonList( new SegmentDescriptor(interval, "unknown_version", 0) ); DruidException e = assertThrows( DruidException.class, () -> serverManager.getQueryRunnerForSegments(query, unknownSegments) ); Assert.assertTrue(e.getMessage().startsWith("Base dataSource")); Assert.assertTrue(e.getMessage().endsWith("is not a table!")); } @Test public void testGetQueryRunnerForSegments_whenTimelineIsMissingReportingMissingSegments() { final Interval interval = Intervals.of("0000-01-01/P1D"); final SearchQuery query = searchQuery("unknown_datasource", interval, Granularities.ALL); final List<SegmentDescriptor> unknownSegments = Collections.singletonList( new SegmentDescriptor(interval, "unknown_version", 0) ); final ResponseContext responseContext = DefaultResponseContext.createEmpty(); final List<Result<SearchResultValue>> results = serverManager.getQueryRunnerForSegments(query, unknownSegments) .run(QueryPlus.wrap(query), responseContext) .toList(); Assert.assertTrue(results.isEmpty()); Assert.assertNotNull(responseContext.getMissingSegments()); Assert.assertEquals(unknownSegments, responseContext.getMissingSegments()); } @Test public void testGetQueryRunnerForSegments_whenTimelineEntryIsMissingReportingMissingSegments() { final Interval interval = Intervals.of("P1d/2011-04-01"); final SearchQuery query = searchQuery("test", interval, Granularities.ALL); final List<SegmentDescriptor> unknownSegments = Collections.singletonList( new SegmentDescriptor(interval, "unknown_version", 0) ); final ResponseContext responseContext = DefaultResponseContext.createEmpty(); final List<Result<SearchResultValue>> results = serverManager.getQueryRunnerForSegments(query, unknownSegments) .run(QueryPlus.wrap(query), responseContext) .toList(); Assert.assertTrue(results.isEmpty()); Assert.assertNotNull(responseContext.getMissingSegments()); Assert.assertEquals(unknownSegments, responseContext.getMissingSegments()); } @Test public void testGetQueryRunnerForSegments_whenTimelinePartitionChunkIsMissingReportingMissingSegments() { final Interval interval = Intervals.of("P1d/2011-04-01"); final int unknownPartitionId = 1000; final SearchQuery query = searchQuery("test", interval, Granularities.ALL); final List<SegmentDescriptor> unknownSegments = Collections.singletonList( new SegmentDescriptor(interval, "1", unknownPartitionId) ); final ResponseContext responseContext = DefaultResponseContext.createEmpty(); final List<Result<SearchResultValue>> results = serverManager.getQueryRunnerForSegments(query, unknownSegments) .run(QueryPlus.wrap(query), responseContext) .toList(); Assert.assertTrue(results.isEmpty()); Assert.assertNotNull(responseContext.getMissingSegments()); Assert.assertEquals(unknownSegments, responseContext.getMissingSegments()); } @Test public void testGetQueryRunnerForSegments_whenSegmentIsClosedReportingMissingSegments() { final Interval interval = Intervals.of("P1d/2011-04-01"); final SearchQuery query = searchQuery("test", interval, Granularities.ALL); final Optional<VersionedIntervalTimeline<String, DataSegment>> maybeTimeline = segmentManager .getTimeline(ExecutionVertex.of(query).getBaseTableDataSource()); Assume.assumeTrue(maybeTimeline.isPresent()); // close all segments in interval final List<TimelineObjectHolder<String, DataSegment>> holders = maybeTimeline.get().lookup(interval); final List<SegmentDescriptor> closedSegments = new ArrayList<>(); for (TimelineObjectHolder<String, DataSegment> holder : holders) { for (PartitionChunk<DataSegment> chunk : holder.getObject()) { final DataSegment segment = chunk.getObject(); Assert.assertNotNull(segment.getId()); closedSegments.add( new SegmentDescriptor(segment.getInterval(), segment.getVersion(), segment.getId().getPartitionNum()) ); segmentManager.dropSegment(segment); } } final ResponseContext responseContext = DefaultResponseContext.createEmpty(); final List<Result<SearchResultValue>> results = serverManager.getQueryRunnerForSegments(query, closedSegments) .run(QueryPlus.wrap(query), responseContext) .toList(); Assert.assertTrue(results.isEmpty()); Assert.assertNotNull(responseContext.getMissingSegments()); Assert.assertEquals(closedSegments, responseContext.getMissingSegments()); } @Test public void testGetQueryRunnerForSegments_forUnknownQueryThrowingException() { final Interval interval = Intervals.of("P1d/2011-04-01"); final List<SegmentDescriptor> descriptors = Collections.singletonList(new SegmentDescriptor(interval, "1", 0)); Query<?> query = Druids.newTimeBoundaryQueryBuilder() .dataSource("test") .intervals(interval.toString()) .build(); // We only have QueryRunnerFactory for SearchQuery in test. QueryUnsupportedException e = Assert.assertThrows( QueryUnsupportedException.class, () -> serverManager.getQueryRunnerForSegments(query, descriptors) ); Assert.assertTrue(e.getMessage().startsWith("Unknown query type")); } @Test public void testGetQueryRunnerForSegments_restricted() throws Exception { conglomerate = DefaultQueryRunnerFactoryConglomerate.buildFromQueryRunnerFactories(ImmutableMap.of( SearchQuery.class, factory )); serverManager = Guice.createInjector(BoundFieldModule.of(this)).getInstance(ServerManager.class); Interval interval = Intervals.of("P1d/2011-04-01"); SearchQuery query = searchQuery("test", interval, Granularities.ALL); SearchQuery queryOnRestricted = searchQuery(RestrictedDataSource.create( TableDataSource.create("test"), NoRestrictionPolicy.instance() ), interval, Granularities.ALL); serverManager.getQueryRunnerForIntervals(query, ImmutableList.of(interval)).run(QueryPlus.wrap(query)).toList(); // switch to a policy enforcer that restricts all tables policyEnforcer = new RestrictAllTablesPolicyEnforcer(ImmutableList.of(NoRestrictionPolicy.class.getName())); serverManager = Guice.createInjector(BoundFieldModule.of(this)).getInstance(ServerManager.class); // fail on query DruidException e = Assert.assertThrows( DruidException.class, () -> serverManager.getQueryRunnerForIntervals(query, ImmutableList.of(interval)) .run(QueryPlus.wrap(query)) .toList() ); Assert.assertEquals(DruidException.Category.FORBIDDEN, e.getCategory()); Assert.assertEquals(DruidException.Persona.OPERATOR, e.getTargetPersona()); Assert.assertEquals( "Failed security validation with segment [test_2011-03-31T00:00:00.000Z_2011-04-01T00:00:00.000Z_1]", e.getMessage() ); // succeed on queryOnRestricted serverManager.getQueryRunnerForIntervals(queryOnRestricted, ImmutableList.of(interval)) .run(QueryPlus.wrap(queryOnRestricted)) .toList(); } private void waitForTestVerificationAndCleanup(Future future) { try { factory.notifyLatch.await(1000, TimeUnit.MILLISECONDS); factory.waitLatch.countDown(); future.get(); factory.clearSegments(); } catch (Exception e) { throw new RuntimeException(e.getCause()); } } private static SearchQuery searchQueryWithQueryDataSource( String datasource, Interval interval, Granularity granularity ) { final ImmutableList<SegmentDescriptor> descriptors = ImmutableList.of( new SegmentDescriptor(Intervals.of("2000/3000"), "0", 0), new SegmentDescriptor(Intervals.of("2000/3000"), "0", 1) ); return searchQuery(new QueryDataSource(Druids.newTimeseriesQueryBuilder() .dataSource(datasource) .intervals(new MultipleSpecificSegmentSpec(descriptors)) .granularity(Granularities.ALL) .build()), interval, granularity); } private static SearchQuery searchQuery(String datasource, Interval interval, Granularity granularity) { return searchQuery(TableDataSource.create(datasource), interval, granularity); } private static SearchQuery searchQuery(DataSource datasource, Interval interval, Granularity granularity) { return Druids.newSearchQueryBuilder() .dataSource(datasource) .intervals(Collections.singletonList(interval)) .granularity(granularity) .limit(10000) .query("wow") .build(); } private Future<?> assertQueryable( Granularity granularity, String dataSource, Interval interval, List<Pair<String, Interval>> expected ) { final SearchQuery query = searchQuery(dataSource, interval, granularity); return assertQuery(query, interval, expected); } private Future<?> assertQuery( SearchQuery query, Interval interval, List<Pair<String, Interval>> expected ) { final Iterator<Pair<String, Interval>> expectedIter = expected.iterator(); final List<Interval> intervals = Collections.singletonList(interval); final QueryRunner<Result<SearchResultValue>> runner = serverManager.getQueryRunnerForIntervals(query, intervals); return serverManagerExec.submit( () -> { Sequence<Result<SearchResultValue>> seq = runner.run(QueryPlus.wrap(query)); seq.toList(); Iterator<SegmentForTesting> adaptersIter = factory.getSegments().iterator(); while (expectedIter.hasNext() && adaptersIter.hasNext()) { Pair<String, Interval> expectedVals = expectedIter.next(); SegmentForTesting value = adaptersIter.next(); Assert.assertEquals(expectedVals.lhs, value.getVersion()); Assert.assertEquals(expectedVals.rhs, value.getInterval()); } Assert.assertFalse(expectedIter.hasNext()); Assert.assertFalse(adaptersIter.hasNext()); } ); } private void loadQueryable(String dataSource, String version, Interval interval) { try { DataSegment segment = "testTombstone".equals(dataSource) ? TestSegmentUtils.makeTombstoneSegment(dataSource, version, interval) : TestSegmentUtils.makeSegment(dataSource, version, interval); segmentManager.loadSegment(segment); } catch (SegmentLoadingException | IOException e) { throw new RuntimeException(e); } } private void dropQueryable(String dataSource, String version, Interval interval) { segmentManager.dropSegment(TestSegmentUtils.makeSegment(dataSource, version, interval)); } private static class MyQueryRunnerFactory implements QueryRunnerFactory<Result<SearchResultValue>, SearchQuery> { private final CountDownLatch waitLatch; private final CountDownLatch waitYieldLatch; private final CountDownLatch notifyLatch; private final List<TestSegmentUtils.SegmentForTesting> segments = new ArrayList<>(); private final List<ReferenceCountedSegmentProvider> referenceProviders = new ArrayList<>(); public MyQueryRunnerFactory( CountDownLatch waitLatch, CountDownLatch waitYieldLatch, CountDownLatch notifyLatch ) { this.waitLatch = waitLatch; this.waitYieldLatch = waitYieldLatch; this.notifyLatch = notifyLatch; } @Override public QueryRunner<Result<SearchResultValue>> createRunner(Segment segment) { if (this.segments.stream() .map(SegmentForTesting::getId) .anyMatch(segmentId -> segment.getId().equals(segmentId))) { // Already have adapter for this segment, skip. // For RestrictedSegment, we don't have access to RestrictedSegment.delegate, but it'd be recorded in segmentReferences. // This means we can't test adapter and segmentReference unless there's already a ReferenceCountingSegment. } else if (segment instanceof ReferenceCountedSegmentProvider.ReferenceClosingSegment) { final ReferenceCountedSegmentProvider provider = ((ReferenceCountedSegmentProvider.ReferenceClosingSegment) segment).getProvider(); referenceProviders.add(provider); segments.add((SegmentForTesting) provider.getBaseSegment()); } else { throw new IAE("Unsupported segment instance: [%s]", segment.getClass()); } return new BlockingQueryRunner<>(new NoopQueryRunner<>(), waitLatch, waitYieldLatch, notifyLatch); } @Override public QueryRunner<Result<SearchResultValue>> mergeRunners( QueryProcessingPool queryProcessingPool, Iterable<QueryRunner<Result<SearchResultValue>>> queryRunners ) { return (queryPlus, responseContext) -> Sequences.concat( Sequences.map( Sequences.simple(queryRunners), runner -> runner.run(queryPlus, responseContext) ) ); } @Override public QueryToolChest<Result<SearchResultValue>, SearchQuery> getToolchest() { return new NoopQueryToolChest<>(); } public List<SegmentForTesting> getSegments() { return segments; } public List<ReferenceCountedSegmentProvider> getReferenceProviders() { return referenceProviders; } public void clearSegments() { segments.clear(); } } public static class NoopQueryToolChest<T, QueryType extends Query<T>> extends QueryToolChest<T, QueryType> { @Override public QueryRunner<T> mergeResults(QueryRunner<T> runner) { return runner; } @Override public QueryMetrics<Query<?>> makeMetrics(QueryType query) { return new DefaultQueryMetrics<>(); } @Override public Function<T, T> makePreComputeManipulatorFn(QueryType query, MetricManipulationFn fn) { return Functions.identity(); } @Override public TypeReference<T> getResultTypeReference() { return new TypeReference<>() { }; } } private static class BlockingQueryRunner<T> implements QueryRunner<T> { private final QueryRunner<T> runner; private final CountDownLatch waitLatch; private final CountDownLatch waitYieldLatch; private final CountDownLatch notifyLatch; public BlockingQueryRunner( QueryRunner<T> runner, CountDownLatch waitLatch, CountDownLatch waitYieldLatch, CountDownLatch notifyLatch ) { this.runner = runner; this.waitLatch = waitLatch; this.waitYieldLatch = waitYieldLatch; this.notifyLatch = notifyLatch; } @Override public Sequence<T> run(QueryPlus<T> queryPlus, ResponseContext responseContext) { return new BlockingSequence<>(runner.run(queryPlus, responseContext), waitLatch, waitYieldLatch, notifyLatch); } } /** * A Sequence that count-down {@code notifyLatch} when {@link #toYielder} is called, and the returned Yielder waits * for {@code waitYieldLatch} and {@code waitLatch} count-down. */ private static class BlockingSequence<T> extends YieldingSequenceBase<T> { private final Sequence<T> baseSequence; private final CountDownLatch waitLatch; private final CountDownLatch waitYieldLatch; private final CountDownLatch notifyLatch; private BlockingSequence( Sequence<T> baseSequence, CountDownLatch waitLatch, CountDownLatch waitYieldLatch, CountDownLatch notifyLatch ) { this.baseSequence = baseSequence; this.waitLatch = waitLatch; this.waitYieldLatch = waitYieldLatch; this.notifyLatch = notifyLatch; } @Override public <OutType> Yielder<OutType> toYielder( final OutType initValue, final YieldingAccumulator<OutType, T> accumulator ) { notifyLatch.countDown(); try { waitYieldLatch.await(1000, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new RuntimeException(e); } final Yielder<OutType> baseYielder = baseSequence.toYielder(initValue, accumulator); return new Yielder<>() { @Override public OutType get() { try { waitLatch.await(1000, TimeUnit.MILLISECONDS); } catch (Exception e) { throw new RuntimeException(e); } return baseYielder.get(); } @Override public Yielder<OutType> next(OutType initValue) { return baseYielder.next(initValue); } @Override public boolean isDone() { return baseYielder.isDone(); } @Override public void close() throws IOException { baseYielder.close(); } }; } } }
google/j2objc
36,843
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/jar/Pack200.java
/* * Copyright (c) 2003, 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.util.jar; import java.util.SortedMap; import java.io.InputStream; import java.io.OutputStream; import java.io.File; import java.io.IOException; /* J2ObjC removed. import java.beans.PropertyChangeListener; */ /** * Transforms a JAR file to or from a packed stream in Pack200 format. * Please refer to Network Transfer Format JSR 200 Specification at * <a href=http://jcp.org/aboutJava/communityprocess/review/jsr200/index.html>http://jcp.org/aboutJava/communityprocess/review/jsr200/index.html</a> * <p> * Typically the packer engine is used by application developers * to deploy or host JAR files on a website. * The unpacker engine is used by deployment applications to * transform the byte-stream back to JAR format. * <p> * Here is an example using packer and unpacker: * <pre>{@code * import java.util.jar.Pack200; * import java.util.jar.Pack200.*; * ... * // Create the Packer object * Packer packer = Pack200.newPacker(); * * // Initialize the state by setting the desired properties * Map p = packer.properties(); * // take more time choosing codings for better compression * p.put(Packer.EFFORT, "7"); // default is "5" * // use largest-possible archive segments (>10% better compression). * p.put(Packer.SEGMENT_LIMIT, "-1"); * // reorder files for better compression. * p.put(Packer.KEEP_FILE_ORDER, Packer.FALSE); * // smear modification times to a single value. * p.put(Packer.MODIFICATION_TIME, Packer.LATEST); * // ignore all JAR deflation requests, * // transmitting a single request to use "store" mode. * p.put(Packer.DEFLATE_HINT, Packer.FALSE); * // discard debug attributes * p.put(Packer.CODE_ATTRIBUTE_PFX+"LineNumberTable", Packer.STRIP); * // throw an error if an attribute is unrecognized * p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR); * // pass one class file uncompressed: * p.put(Packer.PASS_FILE_PFX+0, "mutants/Rogue.class"); * try { * JarFile jarFile = new JarFile("/tmp/testref.jar"); * FileOutputStream fos = new FileOutputStream("/tmp/test.pack"); * // Call the packer * packer.pack(jarFile, fos); * jarFile.close(); * fos.close(); * * File f = new File("/tmp/test.pack"); * FileOutputStream fostream = new FileOutputStream("/tmp/test.jar"); * JarOutputStream jostream = new JarOutputStream(fostream); * Unpacker unpacker = Pack200.newUnpacker(); * // Call the unpacker * unpacker.unpack(f, jostream); * // Must explicitly close the output. * jostream.close(); * } catch (IOException ioe) { * ioe.printStackTrace(); * } * }</pre> * <p> * A Pack200 file compressed with gzip can be hosted on HTTP/1.1 web servers. * The deployment applications can use "Accept-Encoding=pack200-gzip". This * indicates to the server that the client application desires a version of * the file encoded with Pack200 and further compressed with gzip. Please * refer to <a href="{@docRoot}/../technotes/guides/deployment/deployment-guide/pack200.html">Java Deployment Guide</a> for more details and * techniques. * <p> * Unless otherwise noted, passing a <tt>null</tt> argument to a constructor or * method in this class will cause a {@link NullPointerException} to be thrown. * * @author John Rose * @author Kumar Srinivasan * @since 1.5 */ public abstract class Pack200 { private Pack200() {} //prevent instantiation // Static methods of the Pack200 class. /** * Obtain new instance of a class that implements Packer. * <ul> * <li><p>If the system property <tt>java.util.jar.Pack200.Packer</tt> * is defined, then the value is taken to be the fully-qualified name * of a concrete implementation class, which must implement Packer. * This class is loaded and instantiated. If this process fails * then an unspecified error is thrown.</p></li> * * <li><p>If an implementation has not been specified with the system * property, then the system-default implementation class is instantiated, * and the result is returned.</p></li> * </ul> * * <p>Note: The returned object is not guaranteed to operate * correctly if multiple threads use it at the same time. * A multi-threaded application should either allocate multiple * packer engines, or else serialize use of one engine with a lock. * * @return A newly allocated Packer engine. */ public synchronized static Packer newPacker() { return (Packer) newInstance(PACK_PROVIDER); } /** * Obtain new instance of a class that implements Unpacker. * <ul> * <li><p>If the system property <tt>java.util.jar.Pack200.Unpacker</tt> * is defined, then the value is taken to be the fully-qualified * name of a concrete implementation class, which must implement Unpacker. * The class is loaded and instantiated. If this process fails * then an unspecified error is thrown.</p></li> * * <li><p>If an implementation has not been specified with the * system property, then the system-default implementation class * is instantiated, and the result is returned.</p></li> * </ul> * * <p>Note: The returned object is not guaranteed to operate * correctly if multiple threads use it at the same time. * A multi-threaded application should either allocate multiple * unpacker engines, or else serialize use of one engine with a lock. * * @return A newly allocated Unpacker engine. */ public static Unpacker newUnpacker() { return (Unpacker) newInstance(UNPACK_PROVIDER); } // Interfaces /** * The packer engine applies various transformations to the input JAR file, * making the pack stream highly compressible by a compressor such as * gzip or zip. An instance of the engine can be obtained * using {@link #newPacker}. * The high degree of compression is achieved * by using a number of techniques described in the JSR 200 specification. * Some of the techniques are sorting, re-ordering and co-location of the * constant pool. * <p> * The pack engine is initialized to an initial state as described * by their properties below. * The initial state can be manipulated by getting the * engine properties (using {@link #properties}) and storing * the modified properties on the map. * The resource files will be passed through with no changes at all. * The class files will not contain identical bytes, since the unpacker * is free to change minor class file features such as constant pool order. * However, the class files will be semantically identical, * as specified in * <cite>The Java&trade; Virtual Machine Specification</cite>. * <p> * By default, the packer does not change the order of JAR elements. * Also, the modification time and deflation hint of each * JAR element is passed unchanged. * (Any other ZIP-archive information, such as extra attributes * giving Unix file permissions, are lost.) * <p> * Note that packing and unpacking a JAR will in general alter the * bytewise contents of classfiles in the JAR. This means that packing * and unpacking will in general invalidate any digital signatures * which rely on bytewise images of JAR elements. In order both to sign * and to pack a JAR, you must first pack and unpack the JAR to * "normalize" it, then compute signatures on the unpacked JAR elements, * and finally repack the signed JAR. * Both packing steps should * use precisely the same options, and the segment limit may also * need to be set to "-1", to prevent accidental variation of segment * boundaries as class file sizes change slightly. * <p> * (Here's why this works: Any reordering the packer does * of any classfile structures is idempotent, so the second packing * does not change the orderings produced by the first packing. * Also, the unpacker is guaranteed by the JSR 200 specification * to produce a specific bytewise image for any given transmission * ordering of archive elements.) * <p> * In order to maintain backward compatibility, the pack file's version is * set to accommodate the class files present in the input JAR file. In * other words, the pack file version will be the latest, if the class files * are the latest and conversely the pack file version will be the oldest * if the class file versions are also the oldest. For intermediate class * file versions the corresponding pack file version will be used. * For example: * If the input JAR-files are solely comprised of 1.5 (or lesser) * class files, a 1.5 compatible pack file is produced. This will also be * the case for archives that have no class files. * If the input JAR-files contains a 1.6 class file, then the pack file * version will be set to 1.6. * <p> * Note: Unless otherwise noted, passing a <tt>null</tt> argument to a * constructor or method in this class will cause a {@link NullPointerException} * to be thrown. * <p> * @since 1.5 */ public interface Packer { /** * This property is a numeral giving the estimated target size N * (in bytes) of each archive segment. * If a single input file requires more than N bytes, * it will be given its own archive segment. * <p> * As a special case, a value of -1 will produce a single large * segment with all input files, while a value of 0 will * produce one segment for each class. * Larger archive segments result in less fragmentation and * better compression, but processing them requires more memory. * <p> * The size of each segment is estimated by counting the size of each * input file to be transmitted in the segment, along with the size * of its name and other transmitted properties. * <p> * The default is -1, which means the packer will always create a single * segment output file. In cases where extremely large output files are * generated, users are strongly encouraged to use segmenting or break * up the input file into smaller JARs. * <p> * A 10Mb JAR packed without this limit will * typically pack about 10% smaller, but the packer may require * a larger Java heap (about ten times the segment limit). */ String SEGMENT_LIMIT = "pack.segment.limit"; /** * If this property is set to {@link #TRUE}, the packer will transmit * all elements in their original order within the source archive. * <p> * If it is set to {@link #FALSE}, the packer may reorder elements, * and also remove JAR directory entries, which carry no useful * information for Java applications. * (Typically this enables better compression.) * <p> * The default is {@link #TRUE}, which preserves the input information, * but may cause the transmitted archive to be larger than necessary. */ String KEEP_FILE_ORDER = "pack.keep.file.order"; /** * If this property is set to a single decimal digit, the packer will * use the indicated amount of effort in compressing the archive. * Level 1 may produce somewhat larger size and faster compression speed, * while level 9 will take much longer but may produce better compression. * <p> * The special value 0 instructs the packer to copy through the * original JAR file directly, with no compression. The JSR 200 * standard requires any unpacker to understand this special case * as a pass-through of the entire archive. * <p> * The default is 5, investing a modest amount of time to * produce reasonable compression. */ String EFFORT = "pack.effort"; /** * If this property is set to {@link #TRUE} or {@link #FALSE}, the packer * will set the deflation hint accordingly in the output archive, and * will not transmit the individual deflation hints of archive elements. * <p> * If this property is set to the special string {@link #KEEP}, the packer * will attempt to determine an independent deflation hint for each * available element of the input archive, and transmit this hint separately. * <p> * The default is {@link #KEEP}, which preserves the input information, * but may cause the transmitted archive to be larger than necessary. * <p> * It is up to the unpacker implementation * to take action upon the hint to suitably compress the elements of * the resulting unpacked jar. * <p> * The deflation hint of a ZIP or JAR element indicates * whether the element was deflated or stored directly. */ String DEFLATE_HINT = "pack.deflate.hint"; /** * If this property is set to the special string {@link #LATEST}, * the packer will attempt to determine the latest modification time, * among all the available entries in the original archive or the latest * modification time of all the available entries in each segment. * This single value will be transmitted as part of the segment and applied * to all the entries in each segment, {@link #SEGMENT_LIMIT}. * <p> * This can marginally decrease the transmitted size of the * archive, at the expense of setting all installed files to a single * date. * <p> * If this property is set to the special string {@link #KEEP}, * the packer transmits a separate modification time for each input * element. * <p> * The default is {@link #KEEP}, which preserves the input information, * but may cause the transmitted archive to be larger than necessary. * <p> * It is up to the unpacker implementation to take action to suitably * set the modification time of each element of its output file. * @see #SEGMENT_LIMIT */ String MODIFICATION_TIME = "pack.modification.time"; /** * Indicates that a file should be passed through bytewise, with no * compression. Multiple files may be specified by specifying * additional properties with distinct strings appended, to * make a family of properties with the common prefix. * <p> * There is no pathname transformation, except * that the system file separator is replaced by the JAR file * separator '/'. * <p> * The resulting file names must match exactly as strings with their * occurrences in the JAR file. * <p> * If a property value is a directory name, all files under that * directory will be passed also. * <p> * Examples: * <pre>{@code * Map p = packer.properties(); * p.put(PASS_FILE_PFX+0, "mutants/Rogue.class"); * p.put(PASS_FILE_PFX+1, "mutants/Wolverine.class"); * p.put(PASS_FILE_PFX+2, "mutants/Storm.class"); * # Pass all files in an entire directory hierarchy: * p.put(PASS_FILE_PFX+3, "police/"); * }</pre> */ String PASS_FILE_PFX = "pack.pass.file."; /// Attribute control. /** * Indicates the action to take when a class-file containing an unknown * attribute is encountered. Possible values are the strings {@link #ERROR}, * {@link #STRIP}, and {@link #PASS}. * <p> * The string {@link #ERROR} means that the pack operation * as a whole will fail, with an exception of type <code>IOException</code>. * The string * {@link #STRIP} means that the attribute will be dropped. * The string * {@link #PASS} means that the whole class-file will be passed through * (as if it were a resource file) without compression, with a suitable warning. * This is the default value for this property. * <p> * Examples: * <pre>{@code * Map p = pack200.getProperties(); * p.put(UNKNOWN_ATTRIBUTE, ERROR); * p.put(UNKNOWN_ATTRIBUTE, STRIP); * p.put(UNKNOWN_ATTRIBUTE, PASS); * }</pre> */ String UNKNOWN_ATTRIBUTE = "pack.unknown.attribute"; /** * When concatenated with a class attribute name, * indicates the format of that attribute, * using the layout language specified in the JSR 200 specification. * <p> * For example, the effect of this option is built in: * <code>pack.class.attribute.SourceFile=RUH</code>. * <p> * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} are * also allowed, with the same meaning as {@link #UNKNOWN_ATTRIBUTE}. * This provides a way for users to request that specific attributes be * refused, stripped, or passed bitwise (with no class compression). * <p> * Code like this might be used to support attributes for JCOV: * <pre><code> * Map p = packer.properties(); * p.put(CODE_ATTRIBUTE_PFX+"CoverageTable", "NH[PHHII]"); * p.put(CODE_ATTRIBUTE_PFX+"CharacterRangeTable", "NH[PHPOHIIH]"); * p.put(CLASS_ATTRIBUTE_PFX+"SourceID", "RUH"); * p.put(CLASS_ATTRIBUTE_PFX+"CompilationID", "RUH"); * </code></pre> * <p> * Code like this might be used to strip debugging attributes: * <pre><code> * Map p = packer.properties(); * p.put(CODE_ATTRIBUTE_PFX+"LineNumberTable", STRIP); * p.put(CODE_ATTRIBUTE_PFX+"LocalVariableTable", STRIP); * p.put(CLASS_ATTRIBUTE_PFX+"SourceFile", STRIP); * </code></pre> */ String CLASS_ATTRIBUTE_PFX = "pack.class.attribute."; /** * When concatenated with a field attribute name, * indicates the format of that attribute. * For example, the effect of this option is built in: * <code>pack.field.attribute.Deprecated=</code>. * The special strings {@link #ERROR}, {@link #STRIP}, and * {@link #PASS} are also allowed. * @see #CLASS_ATTRIBUTE_PFX */ String FIELD_ATTRIBUTE_PFX = "pack.field.attribute."; /** * When concatenated with a method attribute name, * indicates the format of that attribute. * For example, the effect of this option is built in: * <code>pack.method.attribute.Exceptions=NH[RCH]</code>. * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} * are also allowed. * @see #CLASS_ATTRIBUTE_PFX */ String METHOD_ATTRIBUTE_PFX = "pack.method.attribute."; /** * When concatenated with a code attribute name, * indicates the format of that attribute. * For example, the effect of this option is built in: * <code>pack.code.attribute.LocalVariableTable=NH[PHOHRUHRSHH]</code>. * The special strings {@link #ERROR}, {@link #STRIP}, and {@link #PASS} * are also allowed. * @see #CLASS_ATTRIBUTE_PFX */ String CODE_ATTRIBUTE_PFX = "pack.code.attribute."; /** * The unpacker's progress as a percentage, as periodically * updated by the unpacker. * Values of 0 - 100 are normal, and -1 indicates a stall. * Progress can be monitored by polling the value of this * property. * <p> * At a minimum, the unpacker must set progress to 0 * at the beginning of a packing operation, and to 100 * at the end. */ String PROGRESS = "pack.progress"; /** The string "keep", a possible value for certain properties. * @see #DEFLATE_HINT * @see #MODIFICATION_TIME */ String KEEP = "keep"; /** The string "pass", a possible value for certain properties. * @see #UNKNOWN_ATTRIBUTE * @see #CLASS_ATTRIBUTE_PFX * @see #FIELD_ATTRIBUTE_PFX * @see #METHOD_ATTRIBUTE_PFX * @see #CODE_ATTRIBUTE_PFX */ String PASS = "pass"; /** The string "strip", a possible value for certain properties. * @see #UNKNOWN_ATTRIBUTE * @see #CLASS_ATTRIBUTE_PFX * @see #FIELD_ATTRIBUTE_PFX * @see #METHOD_ATTRIBUTE_PFX * @see #CODE_ATTRIBUTE_PFX */ String STRIP = "strip"; /** The string "error", a possible value for certain properties. * @see #UNKNOWN_ATTRIBUTE * @see #CLASS_ATTRIBUTE_PFX * @see #FIELD_ATTRIBUTE_PFX * @see #METHOD_ATTRIBUTE_PFX * @see #CODE_ATTRIBUTE_PFX */ String ERROR = "error"; /** The string "true", a possible value for certain properties. * @see #KEEP_FILE_ORDER * @see #DEFLATE_HINT */ String TRUE = "true"; /** The string "false", a possible value for certain properties. * @see #KEEP_FILE_ORDER * @see #DEFLATE_HINT */ String FALSE = "false"; /** The string "latest", a possible value for certain properties. * @see #MODIFICATION_TIME */ String LATEST = "latest"; /** * Get the set of this engine's properties. * This set is a "live view", so that changing its * contents immediately affects the Packer engine, and * changes from the engine (such as progress indications) * are immediately visible in the map. * * <p>The property map may contain pre-defined implementation * specific and default properties. Users are encouraged to * read the information and fully understand the implications, * before modifying pre-existing properties. * <p> * Implementation specific properties are prefixed with a * package name associated with the implementor, beginning * with <tt>com.</tt> or a similar prefix. * All property names beginning with <tt>pack.</tt> and * <tt>unpack.</tt> are reserved for use by this API. * <p> * Unknown properties may be ignored or rejected with an * unspecified error, and invalid entries may cause an * unspecified error to be thrown. * * <p> * The returned map implements all optional {@link SortedMap} operations * @return A sorted association of property key strings to property * values. */ SortedMap<String,String> properties(); /** * Takes a JarFile and converts it into a Pack200 archive. * <p> * Closes its input but not its output. (Pack200 archives are appendable.) * @param in a JarFile * @param out an OutputStream * @exception IOException if an error is encountered. */ void pack(JarFile in, OutputStream out) throws IOException ; /** * Takes a JarInputStream and converts it into a Pack200 archive. * <p> * Closes its input but not its output. (Pack200 archives are appendable.) * <p> * The modification time and deflation hint attributes are not available, * for the JAR manifest file and its containing directory. * * @see #MODIFICATION_TIME * @see #DEFLATE_HINT * @param in a JarInputStream * @param out an OutputStream * @exception IOException if an error is encountered. */ void pack(JarInputStream in, OutputStream out) throws IOException ; /** * Registers a listener for PropertyChange events on the properties map. * This is typically used by applications to update a progress bar. * * <p> The default implementation of this method does nothing and has * no side-effects.</p> * * <p><b>WARNING:</b> This method is omitted from the interface * declaration in all subset Profiles of Java SE that do not include * the {@code java.beans} package. </p> * @see #properties * @see #PROGRESS * @param listener An object to be invoked when a property is changed. * @deprecated The dependency on {@code PropertyChangeListener} creates * a significant impediment to future modularization of the * Java platform. This method will be removed in a future * release. * Applications that need to monitor progress of the packer * can poll the value of the {@link #PROGRESS PROGRESS} * property instead. */ /* J2ObjC removed: avoid PropertyChangeListener. @Deprecated default void addPropertyChangeListener(PropertyChangeListener listener) { } */ /** * Remove a listener for PropertyChange events, added by * the {@link #addPropertyChangeListener}. * * <p> The default implementation of this method does nothing and has * no side-effects.</p> * * <p><b>WARNING:</b> This method is omitted from the interface * declaration in all subset Profiles of Java SE that do not include * the {@code java.beans} package. </p> * * @see #addPropertyChangeListener * @param listener The PropertyChange listener to be removed. * @deprecated The dependency on {@code PropertyChangeListener} creates * a significant impediment to future modularization of the * Java platform. This method will be removed in a future * release. */ /* J2ObjC removed: avoid PropertyChangeListener. @Deprecated default void removePropertyChangeListener(PropertyChangeListener listener) { } */ } /** * The unpacker engine converts the packed stream to a JAR file. * An instance of the engine can be obtained * using {@link #newUnpacker}. * <p> * Every JAR file produced by this engine will include the string * "<tt>PACK200</tt>" as a zip file comment. * This allows a deployer to detect if a JAR archive was packed and unpacked. * <p> * Note: Unless otherwise noted, passing a <tt>null</tt> argument to a * constructor or method in this class will cause a {@link NullPointerException} * to be thrown. * <p> * This version of the unpacker is compatible with all previous versions. * @since 1.5 */ public interface Unpacker { /** The string "keep", a possible value for certain properties. * @see #DEFLATE_HINT */ String KEEP = "keep"; /** The string "true", a possible value for certain properties. * @see #DEFLATE_HINT */ String TRUE = "true"; /** The string "false", a possible value for certain properties. * @see #DEFLATE_HINT */ String FALSE = "false"; /** * Property indicating that the unpacker should * ignore all transmitted values for DEFLATE_HINT, * replacing them by the given value, {@link #TRUE} or {@link #FALSE}. * The default value is the special string {@link #KEEP}, * which asks the unpacker to preserve all transmitted * deflation hints. */ String DEFLATE_HINT = "unpack.deflate.hint"; /** * The unpacker's progress as a percentage, as periodically * updated by the unpacker. * Values of 0 - 100 are normal, and -1 indicates a stall. * Progress can be monitored by polling the value of this * property. * <p> * At a minimum, the unpacker must set progress to 0 * at the beginning of a packing operation, and to 100 * at the end. */ String PROGRESS = "unpack.progress"; /** * Get the set of this engine's properties. This set is * a "live view", so that changing its * contents immediately affects the Packer engine, and * changes from the engine (such as progress indications) * are immediately visible in the map. * * <p>The property map may contain pre-defined implementation * specific and default properties. Users are encouraged to * read the information and fully understand the implications, * before modifying pre-existing properties. * <p> * Implementation specific properties are prefixed with a * package name associated with the implementor, beginning * with <tt>com.</tt> or a similar prefix. * All property names beginning with <tt>pack.</tt> and * <tt>unpack.</tt> are reserved for use by this API. * <p> * Unknown properties may be ignored or rejected with an * unspecified error, and invalid entries may cause an * unspecified error to be thrown. * * @return A sorted association of option key strings to option values. */ SortedMap<String,String> properties(); /** * Read a Pack200 archive, and write the encoded JAR to * a JarOutputStream. * The entire contents of the input stream will be read. * It may be more efficient to read the Pack200 archive * to a file and pass the File object, using the alternate * method described below. * <p> * Closes its input but not its output. (The output can accumulate more elements.) * @param in an InputStream. * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ void unpack(InputStream in, JarOutputStream out) throws IOException; /** * Read a Pack200 archive, and write the encoded JAR to * a JarOutputStream. * <p> * Does not close its output. (The output can accumulate more elements.) * @param in a File. * @param out a JarOutputStream. * @exception IOException if an error is encountered. */ void unpack(File in, JarOutputStream out) throws IOException; /** * Registers a listener for PropertyChange events on the properties map. * This is typically used by applications to update a progress bar. * * <p> The default implementation of this method does nothing and has * no side-effects.</p> * * <p><b>WARNING:</b> This method is omitted from the interface * declaration in all subset Profiles of Java SE that do not include * the {@code java.beans} package. </p> * * @see #properties * @see #PROGRESS * @param listener An object to be invoked when a property is changed. * @deprecated The dependency on {@code PropertyChangeListener} creates * a significant impediment to future modularization of the * Java platform. This method will be removed in a future * release. * Applications that need to monitor progress of the * unpacker can poll the value of the {@link #PROGRESS * PROGRESS} property instead. */ /* J2ObjC removed: avoid PropertyChangeListener. @Deprecated default void addPropertyChangeListener(PropertyChangeListener listener) { } */ /** * Remove a listener for PropertyChange events, added by * the {@link #addPropertyChangeListener}. * * <p> The default implementation of this method does nothing and has * no side-effects.</p> * * <p><b>WARNING:</b> This method is omitted from the interface * declaration in all subset Profiles of Java SE that do not include * the {@code java.beans} package. </p> * * @see #addPropertyChangeListener * @param listener The PropertyChange listener to be removed. * @deprecated The dependency on {@code PropertyChangeListener} creates * a significant impediment to future modularization of the * Java platform. This method will be removed in a future * release. */ /* J2ObjC removed: avoid PropertyChangeListener. @Deprecated default void removePropertyChangeListener(PropertyChangeListener listener) { } */ } // Private stuff.... private static final String PACK_PROVIDER = "java.util.jar.Pack200.Packer"; private static final String UNPACK_PROVIDER = "java.util.jar.Pack200.Unpacker"; private static Class<?> packerImpl; private static Class<?> unpackerImpl; private synchronized static Object newInstance(String prop) { String implName = "(unknown)"; try { Class<?> impl = (PACK_PROVIDER.equals(prop))? packerImpl: unpackerImpl; if (impl == null) { // The first time, we must decide which class to use. implName = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction(prop,"")); if (implName != null && !implName.equals("")) impl = Class.forName(implName); // Android-changed: Remove default Packer Impl. // // else if (PACK_PROVIDER.equals(prop)) // impl = com.sun.java.util.jar.pack.PackerImpl.class; // else // impl = com.sun.java.util.jar.pack.UnpackerImpl.class; } // We have a class. Now instantiate it. return impl.newInstance(); } catch (ClassNotFoundException e) { throw new Error("Class not found: " + implName + ":\ncheck property " + prop + " in your properties file.", e); } catch (InstantiationException e) { throw new Error("Could not instantiate: " + implName + ":\ncheck property " + prop + " in your properties file.", e); } catch (IllegalAccessException e) { throw new Error("Cannot access class: " + implName + ":\ncheck property " + prop + " in your properties file.", e); } } }
googleapis/google-cloud-java
36,618
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListDataSchemasResponse.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 ListDataSchemas. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListDataSchemasResponse} */ public final class ListDataSchemasResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListDataSchemasResponse) ListDataSchemasResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListDataSchemasResponse.newBuilder() to construct. private ListDataSchemasResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListDataSchemasResponse() { dataSchemas_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListDataSchemasResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListDataSchemasResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListDataSchemasResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListDataSchemasResponse.class, com.google.cloud.visionai.v1.ListDataSchemasResponse.Builder.class); } public static final int DATA_SCHEMAS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.visionai.v1.DataSchema> dataSchemas_; /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.visionai.v1.DataSchema> getDataSchemasList() { return dataSchemas_; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.visionai.v1.DataSchemaOrBuilder> getDataSchemasOrBuilderList() { return dataSchemas_; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ @java.lang.Override public int getDataSchemasCount() { return dataSchemas_.size(); } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.DataSchema getDataSchemas(int index) { return dataSchemas_.get(index); } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ @java.lang.Override public com.google.cloud.visionai.v1.DataSchemaOrBuilder getDataSchemasOrBuilder(int index) { return dataSchemas_.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 < dataSchemas_.size(); i++) { output.writeMessage(1, dataSchemas_.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 < dataSchemas_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataSchemas_.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.ListDataSchemasResponse)) { return super.equals(obj); } com.google.cloud.visionai.v1.ListDataSchemasResponse other = (com.google.cloud.visionai.v1.ListDataSchemasResponse) obj; if (!getDataSchemasList().equals(other.getDataSchemasList())) 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 (getDataSchemasCount() > 0) { hash = (37 * hash) + DATA_SCHEMAS_FIELD_NUMBER; hash = (53 * hash) + getDataSchemasList().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.ListDataSchemasResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListDataSchemasResponse 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.ListDataSchemasResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListDataSchemasResponse 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.ListDataSchemasResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.visionai.v1.ListDataSchemasResponse 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.ListDataSchemasResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListDataSchemasResponse 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.ListDataSchemasResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.visionai.v1.ListDataSchemasResponse 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.ListDataSchemasResponse 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.ListDataSchemasResponse 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.ListDataSchemasResponse 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 ListDataSchemas. * </pre> * * Protobuf type {@code google.cloud.visionai.v1.ListDataSchemasResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListDataSchemasResponse) com.google.cloud.visionai.v1.ListDataSchemasResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListDataSchemasResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.visionai.v1.WarehouseProto .internal_static_google_cloud_visionai_v1_ListDataSchemasResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.visionai.v1.ListDataSchemasResponse.class, com.google.cloud.visionai.v1.ListDataSchemasResponse.Builder.class); } // Construct using com.google.cloud.visionai.v1.ListDataSchemasResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (dataSchemasBuilder_ == null) { dataSchemas_ = java.util.Collections.emptyList(); } else { dataSchemas_ = null; dataSchemasBuilder_.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_ListDataSchemasResponse_descriptor; } @java.lang.Override public com.google.cloud.visionai.v1.ListDataSchemasResponse getDefaultInstanceForType() { return com.google.cloud.visionai.v1.ListDataSchemasResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.visionai.v1.ListDataSchemasResponse build() { com.google.cloud.visionai.v1.ListDataSchemasResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.visionai.v1.ListDataSchemasResponse buildPartial() { com.google.cloud.visionai.v1.ListDataSchemasResponse result = new com.google.cloud.visionai.v1.ListDataSchemasResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.visionai.v1.ListDataSchemasResponse result) { if (dataSchemasBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { dataSchemas_ = java.util.Collections.unmodifiableList(dataSchemas_); bitField0_ = (bitField0_ & ~0x00000001); } result.dataSchemas_ = dataSchemas_; } else { result.dataSchemas_ = dataSchemasBuilder_.build(); } } private void buildPartial0(com.google.cloud.visionai.v1.ListDataSchemasResponse 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.ListDataSchemasResponse) { return mergeFrom((com.google.cloud.visionai.v1.ListDataSchemasResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.visionai.v1.ListDataSchemasResponse other) { if (other == com.google.cloud.visionai.v1.ListDataSchemasResponse.getDefaultInstance()) return this; if (dataSchemasBuilder_ == null) { if (!other.dataSchemas_.isEmpty()) { if (dataSchemas_.isEmpty()) { dataSchemas_ = other.dataSchemas_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDataSchemasIsMutable(); dataSchemas_.addAll(other.dataSchemas_); } onChanged(); } } else { if (!other.dataSchemas_.isEmpty()) { if (dataSchemasBuilder_.isEmpty()) { dataSchemasBuilder_.dispose(); dataSchemasBuilder_ = null; dataSchemas_ = other.dataSchemas_; bitField0_ = (bitField0_ & ~0x00000001); dataSchemasBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDataSchemasFieldBuilder() : null; } else { dataSchemasBuilder_.addAllMessages(other.dataSchemas_); } } } 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.DataSchema m = input.readMessage( com.google.cloud.visionai.v1.DataSchema.parser(), extensionRegistry); if (dataSchemasBuilder_ == null) { ensureDataSchemasIsMutable(); dataSchemas_.add(m); } else { dataSchemasBuilder_.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.DataSchema> dataSchemas_ = java.util.Collections.emptyList(); private void ensureDataSchemasIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { dataSchemas_ = new java.util.ArrayList<com.google.cloud.visionai.v1.DataSchema>(dataSchemas_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.visionai.v1.DataSchema, com.google.cloud.visionai.v1.DataSchema.Builder, com.google.cloud.visionai.v1.DataSchemaOrBuilder> dataSchemasBuilder_; /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public java.util.List<com.google.cloud.visionai.v1.DataSchema> getDataSchemasList() { if (dataSchemasBuilder_ == null) { return java.util.Collections.unmodifiableList(dataSchemas_); } else { return dataSchemasBuilder_.getMessageList(); } } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public int getDataSchemasCount() { if (dataSchemasBuilder_ == null) { return dataSchemas_.size(); } else { return dataSchemasBuilder_.getCount(); } } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public com.google.cloud.visionai.v1.DataSchema getDataSchemas(int index) { if (dataSchemasBuilder_ == null) { return dataSchemas_.get(index); } else { return dataSchemasBuilder_.getMessage(index); } } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder setDataSchemas(int index, com.google.cloud.visionai.v1.DataSchema value) { if (dataSchemasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataSchemasIsMutable(); dataSchemas_.set(index, value); onChanged(); } else { dataSchemasBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder setDataSchemas( int index, com.google.cloud.visionai.v1.DataSchema.Builder builderForValue) { if (dataSchemasBuilder_ == null) { ensureDataSchemasIsMutable(); dataSchemas_.set(index, builderForValue.build()); onChanged(); } else { dataSchemasBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder addDataSchemas(com.google.cloud.visionai.v1.DataSchema value) { if (dataSchemasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataSchemasIsMutable(); dataSchemas_.add(value); onChanged(); } else { dataSchemasBuilder_.addMessage(value); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder addDataSchemas(int index, com.google.cloud.visionai.v1.DataSchema value) { if (dataSchemasBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDataSchemasIsMutable(); dataSchemas_.add(index, value); onChanged(); } else { dataSchemasBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder addDataSchemas(com.google.cloud.visionai.v1.DataSchema.Builder builderForValue) { if (dataSchemasBuilder_ == null) { ensureDataSchemasIsMutable(); dataSchemas_.add(builderForValue.build()); onChanged(); } else { dataSchemasBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder addDataSchemas( int index, com.google.cloud.visionai.v1.DataSchema.Builder builderForValue) { if (dataSchemasBuilder_ == null) { ensureDataSchemasIsMutable(); dataSchemas_.add(index, builderForValue.build()); onChanged(); } else { dataSchemasBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder addAllDataSchemas( java.lang.Iterable<? extends com.google.cloud.visionai.v1.DataSchema> values) { if (dataSchemasBuilder_ == null) { ensureDataSchemasIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataSchemas_); onChanged(); } else { dataSchemasBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder clearDataSchemas() { if (dataSchemasBuilder_ == null) { dataSchemas_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { dataSchemasBuilder_.clear(); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public Builder removeDataSchemas(int index) { if (dataSchemasBuilder_ == null) { ensureDataSchemasIsMutable(); dataSchemas_.remove(index); onChanged(); } else { dataSchemasBuilder_.remove(index); } return this; } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public com.google.cloud.visionai.v1.DataSchema.Builder getDataSchemasBuilder(int index) { return getDataSchemasFieldBuilder().getBuilder(index); } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public com.google.cloud.visionai.v1.DataSchemaOrBuilder getDataSchemasOrBuilder(int index) { if (dataSchemasBuilder_ == null) { return dataSchemas_.get(index); } else { return dataSchemasBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public java.util.List<? extends com.google.cloud.visionai.v1.DataSchemaOrBuilder> getDataSchemasOrBuilderList() { if (dataSchemasBuilder_ != null) { return dataSchemasBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(dataSchemas_); } } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public com.google.cloud.visionai.v1.DataSchema.Builder addDataSchemasBuilder() { return getDataSchemasFieldBuilder() .addBuilder(com.google.cloud.visionai.v1.DataSchema.getDefaultInstance()); } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public com.google.cloud.visionai.v1.DataSchema.Builder addDataSchemasBuilder(int index) { return getDataSchemasFieldBuilder() .addBuilder(index, com.google.cloud.visionai.v1.DataSchema.getDefaultInstance()); } /** * * * <pre> * The data schemas from the specified corpus. * </pre> * * <code>repeated .google.cloud.visionai.v1.DataSchema data_schemas = 1;</code> */ public java.util.List<com.google.cloud.visionai.v1.DataSchema.Builder> getDataSchemasBuilderList() { return getDataSchemasFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.visionai.v1.DataSchema, com.google.cloud.visionai.v1.DataSchema.Builder, com.google.cloud.visionai.v1.DataSchemaOrBuilder> getDataSchemasFieldBuilder() { if (dataSchemasBuilder_ == null) { dataSchemasBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.visionai.v1.DataSchema, com.google.cloud.visionai.v1.DataSchema.Builder, com.google.cloud.visionai.v1.DataSchemaOrBuilder>( dataSchemas_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); dataSchemas_ = null; } return dataSchemasBuilder_; } 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.visionai.v1.ListDataSchemasResponse) } // @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListDataSchemasResponse) private static final com.google.cloud.visionai.v1.ListDataSchemasResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListDataSchemasResponse(); } public static com.google.cloud.visionai.v1.ListDataSchemasResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListDataSchemasResponse> PARSER = new com.google.protobuf.AbstractParser<ListDataSchemasResponse>() { @java.lang.Override public ListDataSchemasResponse 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<ListDataSchemasResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListDataSchemasResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.visionai.v1.ListDataSchemasResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/xmlgraphics-fop
36,898
fop-core/src/main/java/org/apache/fop/render/intermediate/BorderPainter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.intermediate; import java.awt.Color; import java.awt.Rectangle; import java.io.IOException; import org.apache.fop.traits.BorderProps; /** * This is an abstract base class for handling border painting. */ public class BorderPainter { // TODO Use a class to model border instead of an array /** Convention index of before top */ protected static final int TOP = 0; /** Convention index of right border */ protected static final int RIGHT = 1; /** Convention index of bottom border */ protected static final int BOTTOM = 2; /** Convention index of left border */ protected static final int LEFT = 3; // TODO Use a class to model border corners instead of an array /** Convention index of top-left border corners */ protected static final int TOP_LEFT = 0; /** Convention index of top-right-end border corners */ protected static final int TOP_RIGHT = 1; /** Convention index of bottom-right border corners */ protected static final int BOTTOM_RIGHT = 2; /** Convention index of bottom-left border corners */ protected static final int BOTTOM_LEFT = 3; /** The ratio between a solid dash and the white-space in a dashed-border */ public static final float DASHED_BORDER_SPACE_RATIO = 0.5f; /** The length of the dash as a factor of the border width i.e. 2 -&gt; dashWidth = 2*borderWidth */ protected static final float DASHED_BORDER_LENGTH_FACTOR = 2.0f; private final GraphicsPainter graphicsPainter; public BorderPainter(GraphicsPainter graphicsPainter) { this.graphicsPainter = graphicsPainter; } /** * Draws borders. * @param borderRect the border rectangle * @param bpsTop the border specification on the top side * @param bpsBottom the border specification on the bottom side * @param bpsLeft the border specification on the left side * @param bpsRight the border specification on the end side * @param innerBackgroundColor the inner background color * @throws IFException if an error occurs while drawing the borders */ public void drawBorders(Rectangle borderRect, BorderProps bpsTop, BorderProps bpsBottom, BorderProps bpsLeft, BorderProps bpsRight, Color innerBackgroundColor) throws IFException { try { drawRoundedBorders(borderRect, bpsTop, bpsBottom, bpsLeft, bpsRight); } catch (IOException ioe) { throw new IFException("IO error drawing borders", ioe); } } private BorderProps sanitizeBorderProps(BorderProps bps) { return bps == null ? bps : bps.width == 0 ? (BorderProps) null : bps; } /** * TODO merge with drawRoundedBorders()? * @param borderRect the border rectangle * @param bpsTop the border specification on the top side * @param bpsBottom the border specification on the bottom side * @param bpsLeft the border specification on the left side * @param bpsRight the border specification on the end side * @throws IOException */ protected void drawRectangularBorders(Rectangle borderRect, BorderProps bpsTop, BorderProps bpsBottom, BorderProps bpsLeft, BorderProps bpsRight) throws IOException { bpsTop = sanitizeBorderProps(bpsTop); bpsBottom = sanitizeBorderProps(bpsBottom); bpsLeft = sanitizeBorderProps(bpsLeft); bpsRight = sanitizeBorderProps(bpsRight); int startx = borderRect.x; int starty = borderRect.y; int width = borderRect.width; int height = borderRect.height; boolean[] b = new boolean[] { (bpsTop != null), (bpsRight != null), (bpsBottom != null), (bpsLeft != null)}; if (!b[TOP] && !b[RIGHT] && !b[BOTTOM] && !b[LEFT]) { return; } int[] bw = new int[] { (b[TOP] ? bpsTop.width : 0), (b[RIGHT] ? bpsRight.width : 0), (b[BOTTOM] ? bpsBottom.width : 0), (b[LEFT] ? bpsLeft.width : 0)}; int[] clipw = new int[] { BorderProps.getClippedWidth(bpsTop), BorderProps.getClippedWidth(bpsRight), BorderProps.getClippedWidth(bpsBottom), BorderProps.getClippedWidth(bpsLeft)}; starty += clipw[TOP]; height -= clipw[TOP]; height -= clipw[BOTTOM]; startx += clipw[LEFT]; width -= clipw[LEFT]; width -= clipw[RIGHT]; boolean[] slant = new boolean[] { (b[LEFT] && b[TOP]), (b[TOP] && b[RIGHT]), (b[RIGHT] && b[BOTTOM]), (b[BOTTOM] && b[LEFT])}; if (bpsTop != null) { int sx1 = startx; int sx2 = (slant[TOP_LEFT] ? sx1 + bw[LEFT] - clipw[LEFT] : sx1); int ex1 = startx + width; int ex2 = (slant[TOP_RIGHT] ? ex1 - bw[RIGHT] + clipw[RIGHT] : ex1); int outery = starty - clipw[TOP]; int clipy = outery + clipw[TOP]; int innery = outery + bw[TOP]; saveGraphicsState(); moveTo(sx1, clipy); int sx1a = sx1; int ex1a = ex1; if (isCollapseOuter(bpsTop)) { if (isCollapseOuter(bpsLeft)) { sx1a -= clipw[LEFT]; } if (isCollapseOuter(bpsRight)) { ex1a += clipw[RIGHT]; } lineTo(sx1a, outery); lineTo(ex1a, outery); } lineTo(ex1, clipy); lineTo(ex2, innery); lineTo(sx2, innery); closePath(); clip(); drawBorderLine(sx1a, outery, ex1a, innery, true, true, bpsTop.style, bpsTop.color); restoreGraphicsState(); } if (bpsRight != null) { int sy1 = starty; int sy2 = (slant[TOP_RIGHT] ? sy1 + bw[TOP] - clipw[TOP] : sy1); int ey1 = starty + height; int ey2 = (slant[BOTTOM_RIGHT] ? ey1 - bw[BOTTOM] + clipw[BOTTOM] : ey1); int outerx = startx + width + clipw[RIGHT]; int clipx = outerx - clipw[RIGHT]; int innerx = outerx - bw[RIGHT]; saveGraphicsState(); moveTo(clipx, sy1); int sy1a = sy1; int ey1a = ey1; if (isCollapseOuter(bpsRight)) { if (isCollapseOuter(bpsTop)) { sy1a -= clipw[TOP]; } if (isCollapseOuter(bpsBottom)) { ey1a += clipw[BOTTOM]; } lineTo(outerx, sy1a); lineTo(outerx, ey1a); } lineTo(clipx, ey1); lineTo(innerx, ey2); lineTo(innerx, sy2); closePath(); clip(); drawBorderLine(innerx, sy1a, outerx, ey1a, false, false, bpsRight.style, bpsRight.color); restoreGraphicsState(); } if (bpsBottom != null) { int sx1 = startx; int sx2 = (slant[BOTTOM_LEFT] ? sx1 + bw[LEFT] - clipw[LEFT] : sx1); int ex1 = startx + width; int ex2 = (slant[BOTTOM_RIGHT] ? ex1 - bw[RIGHT] + clipw[RIGHT] : ex1); int outery = starty + height + clipw[BOTTOM]; int clipy = outery - clipw[BOTTOM]; int innery = outery - bw[BOTTOM]; saveGraphicsState(); moveTo(ex1, clipy); int sx1a = sx1; int ex1a = ex1; if (isCollapseOuter(bpsBottom)) { if (isCollapseOuter(bpsLeft)) { sx1a -= clipw[LEFT]; } if (isCollapseOuter(bpsRight)) { ex1a += clipw[RIGHT]; } lineTo(ex1a, outery); lineTo(sx1a, outery); } lineTo(sx1, clipy); lineTo(sx2, innery); lineTo(ex2, innery); closePath(); clip(); drawBorderLine(sx1a, innery, ex1a, outery, true, false, bpsBottom.style, bpsBottom.color); restoreGraphicsState(); } if (bpsLeft != null) { int sy1 = starty; int sy2 = (slant[TOP_LEFT] ? sy1 + bw[TOP] - clipw[TOP] : sy1); int ey1 = sy1 + height; int ey2 = (slant[BOTTOM_LEFT] ? ey1 - bw[BOTTOM] + clipw[BOTTOM] : ey1); int outerx = startx - clipw[LEFT]; int clipx = outerx + clipw[LEFT]; int innerx = outerx + bw[LEFT]; saveGraphicsState(); moveTo(clipx, ey1); int sy1a = sy1; int ey1a = ey1; if (isCollapseOuter(bpsLeft)) { if (isCollapseOuter(bpsTop)) { sy1a -= clipw[TOP]; } if (isCollapseOuter(bpsBottom)) { ey1a += clipw[BOTTOM]; } lineTo(outerx, ey1a); lineTo(outerx, sy1a); } lineTo(clipx, sy1); lineTo(innerx, sy2); lineTo(innerx, ey2); closePath(); clip(); drawBorderLine(outerx, sy1a, innerx, ey1a, false, true, bpsLeft.style, bpsLeft.color); restoreGraphicsState(); } } private boolean isCollapseOuter(BorderProps bp) { return bp != null && bp.isCollapseOuter(); } /** * This method calculates the length of the "dash" in a dashed border. The dash satisfies the * condition that corners start on a dash and end with a dash (rather than ending with a white space). * @param borderLength The length of the border. * @param borderWidth The width/thickness of the border. * @return returns the length of the dash such that it fits the criteria above. */ public static float dashWidthCalculator(float borderLength, float borderWidth) { float dashWidth = DASHED_BORDER_LENGTH_FACTOR * borderWidth; if (borderWidth < 3) { dashWidth = (DASHED_BORDER_LENGTH_FACTOR * 3) * borderWidth; } int period = (int) ((borderLength - dashWidth) / dashWidth / (1.0f + DASHED_BORDER_SPACE_RATIO)); period = period < 0 ? 0 : period; return borderLength / (period * (1.0f + DASHED_BORDER_SPACE_RATIO) + 1.0f); } /** TODO merge with drawRectangularBorders? * @param borderRect the border rectangle * @throws IOException on io exception * */ protected void drawRoundedBorders(Rectangle borderRect, BorderProps beforeBorderProps, BorderProps afterBorderProps, BorderProps startBorderProps, BorderProps endBorderProps) throws IOException { BorderSegment before = borderSegmentForBefore(beforeBorderProps); BorderSegment after = borderSegmentForAfter(afterBorderProps); BorderSegment start = borderSegmentForStart(startBorderProps); BorderSegment end = borderSegmentForEnd(endBorderProps); if (before.getWidth() == 0 && after.getWidth() == 0 && start.getWidth() == 0 && end.getWidth() == 0) { return; } final int startx = borderRect.x + start.getClippedWidth(); final int starty = borderRect.y + before.getClippedWidth(); final int width = borderRect.width - start.getClippedWidth() - end.getClippedWidth(); final int height = borderRect.height - before.getClippedWidth() - after.getClippedWidth(); //Determine scale factor if any adjacent elliptic corners overlap double cornerCorrectionFactor = calculateCornerScaleCorrection(width, height, before, after, start, end); drawBorderSegment(start, before, end, 0, width, startx, starty, cornerCorrectionFactor); drawBorderSegment(before, end, after, 1, height, startx + width, starty, cornerCorrectionFactor); drawBorderSegment(end, after, start, 2, width, startx + width, starty + height, cornerCorrectionFactor); drawBorderSegment(after, start, before, 3, height, startx, starty + height, cornerCorrectionFactor); } private void drawBorderSegment(BorderSegment start, BorderSegment before, BorderSegment end, int orientation, int width, int x, int y, double cornerCorrectionFactor) throws IOException { if (before.getWidth() != 0) { //Let x increase in the START->END direction final int sx2 = start.getWidth() - start.getClippedWidth(); final int ex1 = width; final int ex2 = ex1 - end.getWidth() + end.getClippedWidth(); final int outery = -before.getClippedWidth(); final int innery = outery + before.getWidth(); final int ellipseSBRadiusX = correctRadius(cornerCorrectionFactor, start.getRadiusEnd()); final int ellipseSBRadiusY = correctRadius(cornerCorrectionFactor, before.getRadiusStart()); final int ellipseBERadiusX = correctRadius(cornerCorrectionFactor, end.getRadiusStart()); final int ellipseBERadiusY = correctRadius(cornerCorrectionFactor, before.getRadiusEnd()); saveGraphicsState(); translateCoordinates(x, y); if (orientation != 0) { rotateCoordinates(Math.PI * orientation / 2d); } final int ellipseSBX = ellipseSBRadiusX; final int ellipseSBY = ellipseSBRadiusY; final int ellipseBEX = ex1 - ellipseBERadiusX; final int ellipseBEY = ellipseBERadiusY; int sx1a = 0; int ex1a = ex1; if (ellipseSBRadiusX != 0 && ellipseSBRadiusY != 0) { final double[] joinMetrics = getCornerBorderJoinMetrics(ellipseSBRadiusX, ellipseSBRadiusY, sx2, innery); final double outerJoinPointX = joinMetrics[0]; final double outerJoinPointY = joinMetrics[1]; final double sbJoinAngle = joinMetrics[2]; moveTo((int) outerJoinPointX, (int) outerJoinPointY); arcTo(Math.PI + sbJoinAngle, Math.PI * 3 / 2, ellipseSBX, ellipseSBY, ellipseSBRadiusX, ellipseSBRadiusY); } else { moveTo(0, 0); if (before.isCollapseOuter()) { if (start.isCollapseOuter()) { sx1a -= start.getClippedWidth(); } if (end.isCollapseOuter()) { ex1a += end.getClippedWidth(); } lineTo(sx1a, outery); lineTo(ex1a, outery); } } if (ellipseBERadiusX != 0 && ellipseBERadiusY != 0) { final double[] outerJoinMetrics = getCornerBorderJoinMetrics( ellipseBERadiusX, ellipseBERadiusY, ex1 - ex2, innery); final double beJoinAngle = ex1 == ex2 ? Math.PI / 2 : Math.PI / 2 - outerJoinMetrics[2]; lineTo(ellipseBEX, 0); arcTo(Math.PI * 3 / 2 , Math.PI * 3 / 2 + beJoinAngle, ellipseBEX, ellipseBEY, ellipseBERadiusX, ellipseBERadiusY); if (ellipseBEX < ex2 && ellipseBEY > innery) { final double[] innerJoinMetrics = getCornerBorderJoinMetrics( (double) ex2 - ellipseBEX, (double) ellipseBEY - innery, ex1 - ex2, innery); final double innerJoinPointX = innerJoinMetrics[0]; final double innerJoinPointY = innerJoinMetrics[1]; final double beInnerJoinAngle = Math.PI / 2 - innerJoinMetrics[2]; lineTo((int) (ex2 - innerJoinPointX), (int) (innerJoinPointY + innery)); arcTo(beInnerJoinAngle + Math.PI * 3 / 2, Math.PI * 3 / 2, ellipseBEX, ellipseBEY, ex2 - ellipseBEX, ellipseBEY - innery); } else { lineTo(ex2, innery); } } else { lineTo(ex1, 0); lineTo(ex2, innery); } if (ellipseSBRadiusX == 0) { lineTo(sx2, innery); } else { if (ellipseSBX > sx2 && ellipseSBY > innery) { final double[] innerJoinMetrics = getCornerBorderJoinMetrics(ellipseSBRadiusX - sx2, ellipseSBRadiusY - innery, sx2, innery); final double sbInnerJoinAngle = innerJoinMetrics[2]; lineTo(ellipseSBX, innery); arcTo(Math.PI * 3 / 2, sbInnerJoinAngle + Math.PI, ellipseSBX, ellipseSBY, ellipseSBX - sx2, ellipseSBY - innery); } else { lineTo(sx2, innery); } } closePath(); clip(); if (ellipseBERadiusY == 0 && ellipseSBRadiusY == 0) { drawBorderLine(sx1a, outery, ex1a, innery, true, true, before.getStyle(), before.getColor()); } else { int innerFillY = Math.max(Math.max(ellipseBEY, ellipseSBY), innery); drawBorderLine(sx1a, outery, ex1a, innerFillY, true, true, before.getStyle(), before.getColor()); } restoreGraphicsState(); } } private static int correctRadius(double cornerCorrectionFactor, int radius) { return (int) (Math.round(cornerCorrectionFactor * radius)); } private static BorderSegment borderSegmentForBefore(BorderProps before) { return AbstractBorderSegment.asBorderSegment(before); } private static BorderSegment borderSegmentForAfter(BorderProps after) { return AbstractBorderSegment.asFlippedBorderSegment(after); } private static BorderSegment borderSegmentForStart(BorderProps start) { return AbstractBorderSegment.asFlippedBorderSegment(start); } private static BorderSegment borderSegmentForEnd(BorderProps end) { return AbstractBorderSegment.asBorderSegment(end); } private interface BorderSegment { Color getColor(); int getStyle(); int getWidth(); int getClippedWidth(); int getRadiusStart(); int getRadiusEnd(); boolean isCollapseOuter(); boolean isSpecified(); } private abstract static class AbstractBorderSegment implements BorderSegment { private static BorderSegment asBorderSegment(BorderProps borderProps) { return borderProps == null ? NullBorderSegment.INSTANCE : new WrappingBorderSegment(borderProps); } private static BorderSegment asFlippedBorderSegment(BorderProps borderProps) { return borderProps == null ? NullBorderSegment.INSTANCE : new FlippedBorderSegment(borderProps); } public boolean isSpecified() { return !(this instanceof NullBorderSegment); } private static class WrappingBorderSegment extends AbstractBorderSegment { protected final BorderProps borderProps; private final int clippedWidth; WrappingBorderSegment(BorderProps borderProps) { this.borderProps = borderProps; clippedWidth = BorderProps.getClippedWidth(borderProps); } public int getStyle() { return borderProps.style; } public Color getColor() { return borderProps.color; } public int getWidth() { return borderProps.width; } public int getClippedWidth() { return clippedWidth; } public boolean isCollapseOuter() { return borderProps.isCollapseOuter(); } public int getRadiusStart() { return borderProps.getRadiusStart(); } public int getRadiusEnd() { return borderProps.getRadiusEnd(); } } private static class FlippedBorderSegment extends WrappingBorderSegment { FlippedBorderSegment(BorderProps borderProps) { super(borderProps); } public int getRadiusStart() { return borderProps.getRadiusEnd(); } public int getRadiusEnd() { return borderProps.getRadiusStart(); } } private static final class NullBorderSegment extends AbstractBorderSegment { public static final NullBorderSegment INSTANCE = new NullBorderSegment(); private NullBorderSegment() { } public int getWidth() { return 0; } public int getClippedWidth() { return 0; } public int getRadiusStart() { return 0; } public int getRadiusEnd() { return 0; } public boolean isCollapseOuter() { return false; } public Color getColor() { throw new UnsupportedOperationException(); } public int getStyle() { throw new UnsupportedOperationException(); } public boolean isSpecified() { return false; } } } private double[] getCornerBorderJoinMetrics(double ellipseCenterX, double ellipseCenterY, double xWidth, double yWidth) { if (xWidth > 0) { return getCornerBorderJoinMetrics(ellipseCenterX, ellipseCenterY, yWidth / xWidth); } else { return new double[]{0, ellipseCenterY, 0}; } } private double[] getCornerBorderJoinMetrics(double ellipseCenterX, double ellipseCenterY, double borderWidthRatio) { double x = ellipseCenterY * ellipseCenterX * ( ellipseCenterY + ellipseCenterX * borderWidthRatio - Math.sqrt(2d * ellipseCenterX * ellipseCenterY * borderWidthRatio) ) / (ellipseCenterY * ellipseCenterY + ellipseCenterX * ellipseCenterX * borderWidthRatio * borderWidthRatio); double y = borderWidthRatio * x; return new double[]{x, y, Math.atan((ellipseCenterY - y) / (ellipseCenterX - x))}; } /** * Clip the background to the inner border * @param rect clipping rectangle * @param bpsBefore before border * @param bpsAfter after border * @param bpsStart start border * @param bpsEnd end border * @throws IOException if an I/O error occurs */ public void clipBackground(Rectangle rect, BorderProps bpsBefore, BorderProps bpsAfter, BorderProps bpsStart, BorderProps bpsEnd) throws IOException { BorderSegment before = borderSegmentForBefore(bpsBefore); BorderSegment after = borderSegmentForAfter(bpsAfter); BorderSegment start = borderSegmentForStart(bpsStart); BorderSegment end = borderSegmentForEnd(bpsEnd); int startx = rect.x; int starty = rect.y; int width = rect.width; int height = rect.height; double correctionFactor = calculateCornerCorrectionFactor(width + start.getWidth() + end.getWidth(), height + before.getWidth() + after.getWidth(), bpsBefore, bpsAfter, bpsStart, bpsEnd); Corner cornerBeforeEnd = Corner.createBeforeEndCorner(before, end, correctionFactor); Corner cornerEndAfter = Corner.createEndAfterCorner(end, after, correctionFactor); Corner cornerAfterStart = Corner.createAfterStartCorner(after, start, correctionFactor); Corner cornerStartBefore = Corner.createStartBeforeCorner(start, before, correctionFactor); new PathPainter(startx + cornerStartBefore.radiusX, starty) .lineHorizTo(width - cornerStartBefore.radiusX - cornerBeforeEnd.radiusX) .drawCorner(cornerBeforeEnd) .lineVertTo(height - cornerBeforeEnd.radiusY - cornerEndAfter.radiusY) .drawCorner(cornerEndAfter) .lineHorizTo(cornerEndAfter.radiusX + cornerAfterStart.radiusX - width) .drawCorner(cornerAfterStart) .lineVertTo(cornerAfterStart.radiusY + cornerStartBefore.radiusY - height) .drawCorner(cornerStartBefore); clip(); } /** * The four corners * SB - Start-Before * BE - Before-End * EA - End-After * AS - After-Start * * 0 --> x * | * v * y * * SB BE * *----* * | | * | | * *----* * AS EA * */ private enum CornerAngles { /** The before-end angles */ BEFORE_END(Math.PI * 3 / 2, 0), /** The end-after angles */ END_AFTER(0, Math.PI / 2), /** The after-start angles*/ AFTER_START(Math.PI / 2, Math.PI), /** The start-before angles */ START_BEFORE(Math.PI, Math.PI * 3 / 2); /** Angle of the start of the corner arch relative to the x-axis in the counter-clockwise direction */ private final double start; /** Angle of the end of the corner arch relative to the x-axis in the counter-clockwise direction */ private final double end; CornerAngles(double start, double end) { this.start = start; this.end = end; } } private static final class Corner { private static final Corner SQUARE = new Corner(0, 0, null, 0, 0, 0, 0); /** The radius of the elliptic corner in the x direction */ private final int radiusX; /** The radius of the elliptic corner in the y direction */ private final int radiusY; /** The start and end angles of the corner ellipse */ private final CornerAngles angles; /** The offset in the x direction of the center of the ellipse relative to the starting point */ private final int centerX; /** The offset in the y direction of the center of the ellipse relative to the starting point */ private final int centerY; /** The value in the x direction that the corner extends relative to the starting point */ private final int incrementX; /** The value in the y direction that the corner extends relative to the starting point */ private final int incrementY; private Corner(int radiusX, int radiusY, CornerAngles angles, int ellipseOffsetX, int ellipseOffsetY, int incrementX, int incrementY) { this.radiusX = radiusX; this.radiusY = radiusY; this.angles = angles; this.centerX = ellipseOffsetX; this.centerY = ellipseOffsetY; this.incrementX = incrementX; this.incrementY = incrementY; } private static int extentFromRadiusStart(BorderSegment border, double correctionFactor) { return extentFromRadius(border.getRadiusStart(), border, correctionFactor); } private static int extentFromRadiusEnd(BorderSegment border, double correctionFactor) { return extentFromRadius(border.getRadiusEnd(), border, correctionFactor); } private static int extentFromRadius(int radius, BorderSegment border, double correctionFactor) { return Math.max((int) (radius * correctionFactor) - border.getWidth(), 0); } public static Corner createBeforeEndCorner(BorderSegment before, BorderSegment end, double correctionFactor) { int width = end.getRadiusStart(); int height = before.getRadiusEnd(); if (width == 0 || height == 0) { return SQUARE; } int x = extentFromRadiusStart(end, correctionFactor); int y = extentFromRadiusEnd(before, correctionFactor); return new Corner(x, y, CornerAngles.BEFORE_END, 0, y, x, y); } public static Corner createEndAfterCorner(BorderSegment end, BorderSegment after, double correctionFactor) { int width = end.getRadiusEnd(); int height = after.getRadiusStart(); if (width == 0 || height == 0) { return SQUARE; } int x = extentFromRadiusEnd(end, correctionFactor); int y = extentFromRadiusStart(after, correctionFactor); return new Corner(x, y, CornerAngles.END_AFTER, -x, 0, -x, y); } public static Corner createAfterStartCorner(BorderSegment after, BorderSegment start, double correctionFactor) { int width = start.getRadiusStart(); int height = after.getRadiusEnd(); if (width == 0 || height == 0) { return SQUARE; } int x = extentFromRadiusStart(start, correctionFactor); int y = extentFromRadiusEnd(after, correctionFactor); return new Corner(x, y, CornerAngles.AFTER_START, 0, -y, -x, -y); } public static Corner createStartBeforeCorner(BorderSegment start, BorderSegment before, double correctionFactor) { int width = start.getRadiusEnd(); int height = before.getRadiusStart(); if (width == 0 || height == 0) { return SQUARE; } int x = extentFromRadiusEnd(start, correctionFactor); int y = extentFromRadiusStart(before, correctionFactor); return new Corner(x, y, CornerAngles.START_BEFORE, x, 0, x, -y); } } /** * This is a helper class for constructing curves composed of move, line and arc operations. Coordinates * are relative to the terminal point of the previous operation */ private final class PathPainter { /** Current x position */ private int x; /** Current y position */ private int y; PathPainter(int x, int y) throws IOException { moveTo(x, y); } private void moveTo(int x, int y) throws IOException { this.x += x; this.y += y; BorderPainter.this.moveTo(this.x, this.y); } public PathPainter lineTo(int x, int y) throws IOException { this.x += x; this.y += y; BorderPainter.this.lineTo(this.x, this.y); return this; } public PathPainter lineHorizTo(int x) throws IOException { return lineTo(x, 0); } public PathPainter lineVertTo(int y) throws IOException { return lineTo(0, y); } PathPainter drawCorner(Corner corner) throws IOException { if (corner.radiusX == 0 && corner.radiusY == 0) { return this; } if (corner.radiusX == 0 || corner.radiusY == 0) { x += corner.incrementX; y += corner.incrementY; BorderPainter.this.lineTo(x, y); return this; } BorderPainter.this.arcTo(corner.angles.start, corner.angles.end, x + corner.centerX, y + corner.centerY, corner.radiusX, corner.radiusY); x += corner.incrementX; y += corner.incrementY; return this; } } /** * Calculate the correction factor to handle over-sized elliptic corner radii. * * @param width the border width * @param height the border height * @param before the before border properties * @param after the after border properties * @param start the start border properties * @param end the end border properties * */ protected static double calculateCornerCorrectionFactor(int width, int height, BorderProps before, BorderProps after, BorderProps start, BorderProps end) { return calculateCornerScaleCorrection(width, height, borderSegmentForBefore(before), borderSegmentForAfter(after), borderSegmentForStart(start), borderSegmentForEnd(end)); } /** * Calculate the scaling factor to handle over-sized elliptic corner radii. * * @param width the border width * @param height the border height * @param before the before border segment * @param after the after border segment * @param start the start border segment * @param end the end border segment */ protected static double calculateCornerScaleCorrection(int width, int height, BorderSegment before, BorderSegment after, BorderSegment start, BorderSegment end) { return CornerScaleCorrectionCalculator.calculate(width, height, before, after, start, end); } private static final class CornerScaleCorrectionCalculator { private double correctionFactor = 1; private CornerScaleCorrectionCalculator(int width, int height, BorderSegment before, BorderSegment after, BorderSegment start, BorderSegment end) { calculateForSegment(width, start, before, end); calculateForSegment(height, before, end, after); calculateForSegment(width, end, after, start); calculateForSegment(height, after, start, before); } public static double calculate(int width, int height, BorderSegment before, BorderSegment after, BorderSegment start, BorderSegment end) { return new CornerScaleCorrectionCalculator(width, height, before, after, start, end) .correctionFactor; } private void calculateForSegment(int width, BorderSegment bpsStart, BorderSegment bpsBefore, BorderSegment bpsEnd) { if (bpsBefore.isSpecified()) { double ellipseExtent = bpsStart.getRadiusEnd() + bpsEnd.getRadiusStart(); if (ellipseExtent > 0) { double thisCorrectionFactor = width / ellipseExtent; if (thisCorrectionFactor < correctionFactor) { correctionFactor = thisCorrectionFactor; } } } } } private void drawBorderLine(int x1, int y1, int x2, int y2, boolean horz, boolean startOrBefore, int style, Color color) throws IOException { graphicsPainter.drawBorderLine(x1, y1, x2, y2, horz, startOrBefore, style, color); } private void moveTo(int x, int y) throws IOException { graphicsPainter.moveTo(x, y); } private void lineTo(int x, int y) throws IOException { graphicsPainter.lineTo(x, y); } private void arcTo(final double startAngle, final double endAngle, final int cx, final int cy, final int width, final int height) throws IOException { graphicsPainter.arcTo(startAngle, endAngle, cx, cy, width, height); } private void rotateCoordinates(double angle) throws IOException { graphicsPainter.rotateCoordinates(angle); } private void translateCoordinates(int xTranslate, int yTranslate) throws IOException { graphicsPainter.translateCoordinates(xTranslate, yTranslate); } private void closePath() throws IOException { graphicsPainter.closePath(); } private void clip() throws IOException { graphicsPainter.clip(); } private void saveGraphicsState() throws IOException { graphicsPainter.saveGraphicsState(); } private void restoreGraphicsState() throws IOException { graphicsPainter.restoreGraphicsState(); } }
google/j2objc
36,964
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/concurrent/CompletionStage.java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; /** * A stage of a possibly asynchronous computation, that performs an * action or computes a value when another CompletionStage completes. * A stage completes upon termination of its computation, but this may * in turn trigger other dependent stages. The functionality defined * in this interface takes only a few basic forms, which expand out to * a larger set of methods to capture a range of usage styles: * * <ul> * * <li>The computation performed by a stage may be expressed as a * Function, Consumer, or Runnable (using methods with names including * <em>apply</em>, <em>accept</em>, or <em>run</em>, respectively) * depending on whether it requires arguments and/or produces results. * For example: * <pre> {@code * stage.thenApply(x -> square(x)) * .thenAccept(x -> System.out.print(x)) * .thenRun(() -> System.out.println());}</pre> * * An additional form (<em>compose</em>) allows the construction of * computation pipelines from functions returning completion stages. * * <p>Any argument to a stage's computation is the outcome of a * triggering stage's computation. * * <li>One stage's execution may be triggered by completion of a * single stage, or both of two stages, or either of two stages. * Dependencies on a single stage are arranged using methods with * prefix <em>then</em>. Those triggered by completion of * <em>both</em> of two stages may <em>combine</em> their results or * effects, using correspondingly named methods. Those triggered by * <em>either</em> of two stages make no guarantees about which of the * results or effects are used for the dependent stage's computation. * * <li>Dependencies among stages control the triggering of * computations, but do not otherwise guarantee any particular * ordering. Additionally, execution of a new stage's computations may * be arranged in any of three ways: default execution, default * asynchronous execution (using methods with suffix <em>async</em> * that employ the stage's default asynchronous execution facility), * or custom (via a supplied {@link Executor}). The execution * properties of default and async modes are specified by * CompletionStage implementations, not this interface. Methods with * explicit Executor arguments may have arbitrary execution * properties, and might not even support concurrent execution, but * are arranged for processing in a way that accommodates asynchrony. * * <li>Two method forms ({@link #handle handle} and {@link * #whenComplete whenComplete}) support unconditional computation * whether the triggering stage completed normally or exceptionally. * Method {@link #exceptionally exceptionally} supports computation * only when the triggering stage completes exceptionally, computing a * replacement result, similarly to the java {@code catch} keyword. * In all other cases, if a stage's computation terminates abruptly * with an (unchecked) exception or error, then all dependent stages * requiring its completion complete exceptionally as well, with a * {@link CompletionException} holding the exception as its cause. If * a stage is dependent on <em>both</em> of two stages, and both * complete exceptionally, then the CompletionException may correspond * to either one of these exceptions. If a stage is dependent on * <em>either</em> of two others, and only one of them completes * exceptionally, no guarantees are made about whether the dependent * stage completes normally or exceptionally. In the case of method * {@code whenComplete}, when the supplied action itself encounters an * exception, then the stage completes exceptionally with this * exception unless the source stage also completed exceptionally, in * which case the exceptional completion from the source stage is * given preference and propagated to the dependent stage. * * </ul> * * <p>All methods adhere to the above triggering, execution, and * exceptional completion specifications (which are not repeated in * individual method specifications). Additionally, while arguments * used to pass a completion result (that is, for parameters of type * {@code T}) for methods accepting them may be null, passing a null * value for any other parameter will result in a {@link * NullPointerException} being thrown. * * <p>Method form {@link #handle handle} is the most general way of * creating a continuation stage, unconditionally performing a * computation that is given both the result and exception (if any) of * the triggering CompletionStage, and computing an arbitrary result. * Method {@link #whenComplete whenComplete} is similar, but preserves * the result of the triggering stage instead of computing a new one. * Because a stage's normal result may be {@code null}, both methods * should have a computation structured thus: * * <pre>{@code (result, exception) -> { * if (exception == null) { * // triggering stage completed normally * } else { * // triggering stage completed exceptionally * } * }}</pre> * * <p>This interface does not define methods for initially creating, * forcibly completing normally or exceptionally, probing completion * status or results, or awaiting completion of a stage. * Implementations of CompletionStage may provide means of achieving * such effects, as appropriate. Method {@link #toCompletableFuture} * enables interoperability among different implementations of this * interface by providing a common conversion type. * * @author Doug Lea * @since 1.8 */ public interface CompletionStage<T> { /** * Returns a new CompletionStage that, when this stage completes * normally, is executed with this stage's result as the argument * to the supplied function. * * <p>This method is analogous to * {@link java.util.Optional#map Optional.map} and * {@link java.util.stream.Stream#map Stream.map}. * * <p>See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> thenApply(Function<? super T,? extends U> fn); /** * Returns a new CompletionStage that, when this stage completes * normally, is executed using this stage's default asynchronous * execution facility, with this stage's result as the argument to * the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> thenApplyAsync (Function<? super T,? extends U> fn); /** * Returns a new CompletionStage that, when this stage completes * normally, is executed using the supplied Executor, with this * stage's result as the argument to the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param fn the function to use to compute the value of the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> thenApplyAsync (Function<? super T,? extends U> fn, Executor executor); /** * Returns a new CompletionStage that, when this stage completes * normally, is executed with this stage's result as the argument * to the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> thenAccept(Consumer<? super T> action); /** * Returns a new CompletionStage that, when this stage completes * normally, is executed using this stage's default asynchronous * execution facility, with this stage's result as the argument to * the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action); /** * Returns a new CompletionStage that, when this stage completes * normally, is executed using the supplied Executor, with this * stage's result as the argument to the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param action the action to perform before completing the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @return the new CompletionStage */ public CompletionStage<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor); /** * Returns a new CompletionStage that, when this stage completes * normally, executes the given action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> thenRun(Runnable action); /** * Returns a new CompletionStage that, when this stage completes * normally, executes the given action using this stage's default * asynchronous execution facility. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> thenRunAsync(Runnable action); /** * Returns a new CompletionStage that, when this stage completes * normally, executes the given action using the supplied Executor. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param action the action to perform before completing the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @return the new CompletionStage */ public CompletionStage<Void> thenRunAsync(Runnable action, Executor executor); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, is executed with the two * results as arguments to the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the type of the other CompletionStage's result * @param <V> the function's return type * @return the new CompletionStage */ public <U,V> CompletionStage<V> thenCombine (CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, is executed using this * stage's default asynchronous execution facility, with the two * results as arguments to the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the type of the other CompletionStage's result * @param <V> the function's return type * @return the new CompletionStage */ public <U,V> CompletionStage<V> thenCombineAsync (CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, is executed using the * supplied executor, with the two results as arguments to the * supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param fn the function to use to compute the value of the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @param <U> the type of the other CompletionStage's result * @param <V> the function's return type * @return the new CompletionStage */ public <U,V> CompletionStage<V> thenCombineAsync (CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn, Executor executor); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, is executed with the two * results as arguments to the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @param <U> the type of the other CompletionStage's result * @return the new CompletionStage */ public <U> CompletionStage<Void> thenAcceptBoth (CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, is executed using this * stage's default asynchronous execution facility, with the two * results as arguments to the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @param <U> the type of the other CompletionStage's result * @return the new CompletionStage */ public <U> CompletionStage<Void> thenAcceptBothAsync (CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, is executed using the * supplied executor, with the two results as arguments to the * supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @param <U> the type of the other CompletionStage's result * @return the new CompletionStage */ public <U> CompletionStage<Void> thenAcceptBothAsync (CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action, Executor executor); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, executes the given action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> runAfterBoth(CompletionStage<?> other, Runnable action); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, executes the given action * using this stage's default asynchronous execution facility. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action); /** * Returns a new CompletionStage that, when this and the other * given stage both complete normally, executes the given action * using the supplied executor. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @return the new CompletionStage */ public CompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, is executed with the * corresponding result as argument to the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> applyToEither (CompletionStage<? extends T> other, Function<? super T, U> fn); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, is executed using this * stage's default asynchronous execution facility, with the * corresponding result as argument to the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> applyToEitherAsync (CompletionStage<? extends T> other, Function<? super T, U> fn); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, is executed using the * supplied executor, with the corresponding result as argument to * the supplied function. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param fn the function to use to compute the value of the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> applyToEitherAsync (CompletionStage<? extends T> other, Function<? super T, U> fn, Executor executor); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, is executed with the * corresponding result as argument to the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> acceptEither (CompletionStage<? extends T> other, Consumer<? super T> action); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, is executed using this * stage's default asynchronous execution facility, with the * corresponding result as argument to the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> acceptEitherAsync (CompletionStage<? extends T> other, Consumer<? super T> action); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, is executed using the * supplied executor, with the corresponding result as argument to * the supplied action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @return the new CompletionStage */ public CompletionStage<Void> acceptEitherAsync (CompletionStage<? extends T> other, Consumer<? super T> action, Executor executor); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, executes the given action. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> runAfterEither(CompletionStage<?> other, Runnable action); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, executes the given action * using this stage's default asynchronous execution facility. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @return the new CompletionStage */ public CompletionStage<Void> runAfterEitherAsync (CompletionStage<?> other, Runnable action); /** * Returns a new CompletionStage that, when either this or the * other given stage complete normally, executes the given action * using the supplied executor. * * See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param other the other CompletionStage * @param action the action to perform before completing the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @return the new CompletionStage */ public CompletionStage<Void> runAfterEitherAsync (CompletionStage<?> other, Runnable action, Executor executor); /** * Returns a new CompletionStage that is completed with the same * value as the CompletionStage returned by the given function. * * <p>When this stage completes normally, the given function is * invoked with this stage's result as the argument, returning * another CompletionStage. When that stage completes normally, * the CompletionStage returned by this method is completed with * the same value. * * <p>To ensure progress, the supplied function must arrange * eventual completion of its result. * * <p>This method is analogous to * {@link java.util.Optional#flatMap Optional.flatMap} and * {@link java.util.stream.Stream#flatMap Stream.flatMap}. * * <p>See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param fn the function to use to compute another CompletionStage * @param <U> the type of the returned CompletionStage's result * @return the new CompletionStage */ public <U> CompletionStage<U> thenCompose (Function<? super T, ? extends CompletionStage<U>> fn); /** * Returns a new CompletionStage that is completed with the same * value as the CompletionStage returned by the given function, * executed using this stage's default asynchronous execution * facility. * * <p>When this stage completes normally, the given function is * invoked with this stage's result as the argument, returning * another CompletionStage. When that stage completes normally, * the CompletionStage returned by this method is completed with * the same value. * * <p>To ensure progress, the supplied function must arrange * eventual completion of its result. * * <p>See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param fn the function to use to compute another CompletionStage * @param <U> the type of the returned CompletionStage's result * @return the new CompletionStage */ public <U> CompletionStage<U> thenComposeAsync (Function<? super T, ? extends CompletionStage<U>> fn); /** * Returns a new CompletionStage that is completed with the same * value as the CompletionStage returned by the given function, * executed using the supplied Executor. * * <p>When this stage completes normally, the given function is * invoked with this stage's result as the argument, returning * another CompletionStage. When that stage completes normally, * the CompletionStage returned by this method is completed with * the same value. * * <p>To ensure progress, the supplied function must arrange * eventual completion of its result. * * <p>See the {@link CompletionStage} documentation for rules * covering exceptional completion. * * @param fn the function to use to compute another CompletionStage * @param executor the executor to use for asynchronous execution * @param <U> the type of the returned CompletionStage's result * @return the new CompletionStage */ public <U> CompletionStage<U> thenComposeAsync (Function<? super T, ? extends CompletionStage<U>> fn, Executor executor); /** * Returns a new CompletionStage that, when this stage completes * either normally or exceptionally, is executed with this stage's * result and exception as arguments to the supplied function. * * <p>When this stage is complete, the given function is invoked * with the result (or {@code null} if none) and the exception (or * {@code null} if none) of this stage as arguments, and the * function's result is used to complete the returned stage. * * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> handle (BiFunction<? super T, Throwable, ? extends U> fn); /** * Returns a new CompletionStage that, when this stage completes * either normally or exceptionally, is executed using this stage's * default asynchronous execution facility, with this stage's * result and exception as arguments to the supplied function. * * <p>When this stage is complete, the given function is invoked * with the result (or {@code null} if none) and the exception (or * {@code null} if none) of this stage as arguments, and the * function's result is used to complete the returned stage. * * @param fn the function to use to compute the value of the * returned CompletionStage * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> handleAsync (BiFunction<? super T, Throwable, ? extends U> fn); /** * Returns a new CompletionStage that, when this stage completes * either normally or exceptionally, is executed using the * supplied executor, with this stage's result and exception as * arguments to the supplied function. * * <p>When this stage is complete, the given function is invoked * with the result (or {@code null} if none) and the exception (or * {@code null} if none) of this stage as arguments, and the * function's result is used to complete the returned stage. * * @param fn the function to use to compute the value of the * returned CompletionStage * @param executor the executor to use for asynchronous execution * @param <U> the function's return type * @return the new CompletionStage */ public <U> CompletionStage<U> handleAsync (BiFunction<? super T, Throwable, ? extends U> fn, Executor executor); /** * Returns a new CompletionStage with the same result or exception as * this stage, that executes the given action when this stage completes. * * <p>When this stage is complete, the given action is invoked * with the result (or {@code null} if none) and the exception (or * {@code null} if none) of this stage as arguments. The returned * stage is completed when the action returns. * * <p>Unlike method {@link #handle handle}, * this method is not designed to translate completion outcomes, * so the supplied action should not throw an exception. However, * if it does, the following rules apply: if this stage completed * normally but the supplied action throws an exception, then the * returned stage completes exceptionally with the supplied * action's exception. Or, if this stage completed exceptionally * and the supplied action throws an exception, then the returned * stage completes exceptionally with this stage's exception. * * @param action the action to perform * @return the new CompletionStage */ public CompletionStage<T> whenComplete (BiConsumer<? super T, ? super Throwable> action); /** * Returns a new CompletionStage with the same result or exception as * this stage, that executes the given action using this stage's * default asynchronous execution facility when this stage completes. * * <p>When this stage is complete, the given action is invoked with the * result (or {@code null} if none) and the exception (or {@code null} * if none) of this stage as arguments. The returned stage is completed * when the action returns. * * <p>Unlike method {@link #handleAsync(BiFunction) handleAsync}, * this method is not designed to translate completion outcomes, * so the supplied action should not throw an exception. However, * if it does, the following rules apply: If this stage completed * normally but the supplied action throws an exception, then the * returned stage completes exceptionally with the supplied * action's exception. Or, if this stage completed exceptionally * and the supplied action throws an exception, then the returned * stage completes exceptionally with this stage's exception. * * @param action the action to perform * @return the new CompletionStage */ public CompletionStage<T> whenCompleteAsync (BiConsumer<? super T, ? super Throwable> action); /** * Returns a new CompletionStage with the same result or exception as * this stage, that executes the given action using the supplied * Executor when this stage completes. * * <p>When this stage is complete, the given action is invoked with the * result (or {@code null} if none) and the exception (or {@code null} * if none) of this stage as arguments. The returned stage is completed * when the action returns. * * <p>Unlike method {@link #handleAsync(BiFunction,Executor) handleAsync}, * this method is not designed to translate completion outcomes, * so the supplied action should not throw an exception. However, * if it does, the following rules apply: If this stage completed * normally but the supplied action throws an exception, then the * returned stage completes exceptionally with the supplied * action's exception. Or, if this stage completed exceptionally * and the supplied action throws an exception, then the returned * stage completes exceptionally with this stage's exception. * * @param action the action to perform * @param executor the executor to use for asynchronous execution * @return the new CompletionStage */ public CompletionStage<T> whenCompleteAsync (BiConsumer<? super T, ? super Throwable> action, Executor executor); /** * Returns a new CompletionStage that, when this stage completes * exceptionally, is executed with this stage's exception as the * argument to the supplied function. Otherwise, if this stage * completes normally, then the returned stage also completes * normally with the same value. * * @param fn the function to use to compute the value of the * returned CompletionStage if this CompletionStage completed * exceptionally * @return the new CompletionStage */ public CompletionStage<T> exceptionally (Function<Throwable, ? extends T> fn); /** * Returns a {@link CompletableFuture} maintaining the same * completion properties as this stage. If this stage is already a * CompletableFuture, this method may return this stage itself. * Otherwise, invocation of this method may be equivalent in * effect to {@code thenApply(x -> x)}, but returning an instance * of type {@code CompletableFuture}. * * @return the CompletableFuture */ public CompletableFuture<T> toCompletableFuture(); }
googleapis/google-cloud-java
36,670
java-beyondcorp-appconnections/proto-google-cloud-beyondcorp-appconnections-v1/src/main/java/com/google/cloud/beyondcorp/appconnections/v1/DeleteAppConnectionRequest.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/beyondcorp/appconnections/v1/app_connections_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.beyondcorp.appconnections.v1; /** * * * <pre> * Request message for BeyondCorp.DeleteAppConnection. * </pre> * * Protobuf type {@code google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest} */ public final class DeleteAppConnectionRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) DeleteAppConnectionRequestOrBuilder { private static final long serialVersionUID = 0L; // Use DeleteAppConnectionRequest.newBuilder() to construct. private DeleteAppConnectionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeleteAppConnectionRequest() { name_ = ""; requestId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeleteAppConnectionRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceProto .internal_static_google_cloud_beyondcorp_appconnections_v1_DeleteAppConnectionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceProto .internal_static_google_cloud_beyondcorp_appconnections_v1_DeleteAppConnectionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest.class, com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object name_ = ""; /** * * * <pre> * Required. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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 REQUEST_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object requestId_ = ""; /** * * * <pre> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</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; } } public static final int VALIDATE_ONLY_FIELD_NUMBER = 3; private boolean validateOnly_ = false; /** * * * <pre> * Optional. If set, validates request by executing a dry-run which would not * alter the resource in any way. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, requestId_); } if (validateOnly_ != false) { output.writeBool(3, validateOnly_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, requestId_); } if (validateOnly_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, 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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest)) { return super.equals(obj); } com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest other = (com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) obj; if (!getName().equals(other.getName())) return false; if (!getRequestId().equals(other.getRequestId())) return false; if (getValidateOnly() != other.getValidateOnly()) return false; if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest 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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest 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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest 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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest 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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest 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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest 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 BeyondCorp.DeleteAppConnection. * </pre> * * Protobuf type {@code google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceProto .internal_static_google_cloud_beyondcorp_appconnections_v1_DeleteAppConnectionRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceProto .internal_static_google_cloud_beyondcorp_appconnections_v1_DeleteAppConnectionRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest.class, com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest.Builder .class); } // Construct using // com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; name_ = ""; requestId_ = ""; validateOnly_ = false; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.beyondcorp.appconnections.v1.AppConnectionsServiceProto .internal_static_google_cloud_beyondcorp_appconnections_v1_DeleteAppConnectionRequest_descriptor; } @java.lang.Override public com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest getDefaultInstanceForType() { return com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest build() { com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest buildPartial() { com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest result = new com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0( com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.name_ = name_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.requestId_ = requestId_; } if (((from_bitField0_ & 0x00000004) != 0)) { result.validateOnly_ = validateOnly_; } } @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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) { return mergeFrom( (com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest other) { if (other == com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest .getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getRequestId().isEmpty()) { requestId_ = other.requestId_; bitField0_ |= 0x00000002; onChanged(); } 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: { name_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; break; } // case 10 case 18: { requestId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 24: { validateOnly_ = input.readBool(); bitField0_ |= 0x00000004; break; } // case 24 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * * * <pre> * Required. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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. BeyondCorp Connector name using the form: * `projects/{project_id}/locations/{location_id}/appConnections/{app_connection_id}` * </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 requestId_ = ""; /** * * * <pre> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</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> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</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_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearRequestId() { requestId_ = getDefaultInstance().getRequestId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Optional. 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. The server will * guarantee that for at least 60 minutes after the first request. * * For example, consider a situation where you make an initial request and t * he 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>string request_id = 2 [(.google.api.field_behavior) = OPTIONAL];</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_ |= 0x00000002; onChanged(); return this; } private boolean validateOnly_; /** * * * <pre> * Optional. If set, validates request by executing a dry-run which would not * alter the resource in any way. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The validateOnly. */ @java.lang.Override public boolean getValidateOnly() { return validateOnly_; } /** * * * <pre> * Optional. If set, validates request by executing a dry-run which would not * alter the resource in any way. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The validateOnly to set. * @return This builder for chaining. */ public Builder setValidateOnly(boolean value) { validateOnly_ = value; bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Optional. If set, validates request by executing a dry-run which would not * alter the resource in any way. * </pre> * * <code>bool validate_only = 3 [(.google.api.field_behavior) = OPTIONAL];</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.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) } // @@protoc_insertion_point(class_scope:google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest) private static final com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest(); } public static com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeleteAppConnectionRequest> PARSER = new com.google.protobuf.AbstractParser<DeleteAppConnectionRequest>() { @java.lang.Override public DeleteAppConnectionRequest 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<DeleteAppConnectionRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeleteAppConnectionRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.beyondcorp.appconnections.v1.DeleteAppConnectionRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/jdk8
36,818
jdk/src/share/classes/java/util/stream/DoubleStream.java
/* * Copyright (c) 2012, 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.util.stream; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collection; import java.util.DoubleSummaryStatistics; import java.util.Objects; import java.util.OptionalDouble; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleConsumer; import java.util.function.DoubleFunction; import java.util.function.DoublePredicate; import java.util.function.DoubleSupplier; import java.util.function.DoubleToIntFunction; import java.util.function.DoubleToLongFunction; import java.util.function.DoubleUnaryOperator; import java.util.function.Function; import java.util.function.ObjDoubleConsumer; import java.util.function.Supplier; /** * A sequence of primitive double-valued elements supporting sequential and parallel * aggregate operations. This is the {@code double} primitive specialization of * {@link Stream}. * * <p>The following example illustrates an aggregate operation using * {@link Stream} and {@link DoubleStream}, computing the sum of the weights of the * red widgets: * * <pre>{@code * double sum = widgets.stream() * .filter(w -> w.getColor() == RED) * .mapToDouble(w -> w.getWeight()) * .sum(); * }</pre> * * See the class documentation for {@link Stream} and the package documentation * for <a href="package-summary.html">java.util.stream</a> for additional * specification of streams, stream operations, stream pipelines, and * parallelism. * * @since 1.8 * @see Stream * @see <a href="package-summary.html">java.util.stream</a> */ public interface DoubleStream extends BaseStream<Double, DoubleStream> { /** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to each element to determine if it * should be included * @return the new stream */ DoubleStream filter(DoublePredicate predicate); /** * Returns a stream consisting of the results of applying the given * function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ DoubleStream map(DoubleUnaryOperator mapper); /** * Returns an object-valued {@code Stream} consisting of the results of * applying the given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps"> * intermediate operation</a>. * * @param <U> the element type of the new stream * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ <U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper); /** * Returns an {@code IntStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ IntStream mapToInt(DoubleToIntFunction mapper); /** * Returns a {@code LongStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ LongStream mapToLong(DoubleToLongFunction mapper); /** * Returns a stream consisting of the results of replacing each element of * this stream with the contents of a mapped stream produced by applying * the provided mapping function to each element. Each mapped stream is * {@link java.util.stream.BaseStream#close() closed} after its contents * have been placed into this stream. (If a mapped stream is {@code null} * an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces a * {@code DoubleStream} of new values * @return the new stream * @see Stream#flatMap(Function) */ DoubleStream flatMap(DoubleFunction<? extends DoubleStream> mapper); /** * Returns a stream consisting of the distinct elements of this stream. The * elements are compared for equality according to * {@link java.lang.Double#compare(double, double)}. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the result stream */ DoubleStream distinct(); /** * Returns a stream consisting of the elements of this stream in sorted * order. The elements are compared for equality according to * {@link java.lang.Double#compare(double, double)}. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the result stream */ DoubleStream sorted(); /** * Returns a stream consisting of the elements of this stream, additionally * performing the provided action on each element as elements are consumed * from the resulting stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * <p>For parallel stream pipelines, the action may be called at * whatever time and in whatever thread the element is made available by the * upstream operation. If the action modifies shared state, * it is responsible for providing the required synchronization. * * @apiNote This method exists mainly to support debugging, where you want * to see the elements as they flow past a certain point in a pipeline: * <pre>{@code * DoubleStream.of(1, 2, 3, 4) * .filter(e -> e > 2) * .peek(e -> System.out.println("Filtered value: " + e)) * .map(e -> e * e) * .peek(e -> System.out.println("Mapped value: " + e)) * .sum(); * }</pre> * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements as * they are consumed from the stream * @return the new stream */ DoubleStream peek(DoubleConsumer action); /** * Returns a stream consisting of the elements of this stream, truncated * to be no longer than {@code maxSize} in length. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * stateful intermediate operation</a>. * * @apiNote * While {@code limit()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code maxSize}, since {@code limit(n)} * is constrained to return not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(DoubleSupplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code limit()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code limit()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. * * @param maxSize the number of elements the stream should be limited to * @return the new stream * @throws IllegalArgumentException if {@code maxSize} is negative */ DoubleStream limit(long maxSize); /** * Returns a stream consisting of the remaining elements of this stream * after discarding the first {@code n} elements of the stream. * If this stream contains fewer than {@code n} elements then an * empty stream will be returned. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @apiNote * While {@code skip()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code n}, since {@code skip(n)} * is constrained to skip not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(DoubleSupplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code skip()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code skip()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. * * @param n the number of leading elements to skip * @return the new stream * @throws IllegalArgumentException if {@code n} is negative */ DoubleStream skip(long n); /** * Performs an action for each element of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * <p>For parallel stream pipelines, this operation does <em>not</em> * guarantee to respect the encounter order of the stream, as doing so * would sacrifice the benefit of parallelism. For any given element, the * action may be performed at whatever time and in whatever thread the * library chooses. If the action accesses shared state, it is * responsible for providing the required synchronization. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements */ void forEach(DoubleConsumer action); /** * Performs an action for each element of this stream, guaranteeing that * each element is processed in encounter order for streams that have a * defined encounter order. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements * @see #forEach(DoubleConsumer) */ void forEachOrdered(DoubleConsumer action); /** * Returns an array containing the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an array containing the elements of this stream */ double[] toArray(); /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using the provided identity value and an * <a href="package-summary.html#Associativity">associative</a> * accumulation function, and returns the reduced value. This is equivalent * to: * <pre>{@code * double result = identity; * for (double element : this stream) * result = accumulator.applyAsDouble(result, element) * return result; * }</pre> * * but is not constrained to execute sequentially. * * <p>The {@code identity} value must be an identity for the accumulator * function. This means that for all {@code x}, * {@code accumulator.apply(identity, x)} is equal to {@code x}. * The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @apiNote Sum, min, max, and average are all special cases of reduction. * Summing a stream of numbers can be expressed as: * <pre>{@code * double sum = numbers.reduce(0, (a, b) -> a+b); * }</pre> * * or more compactly: * * <pre>{@code * double sum = numbers.reduce(0, Double::sum); * }</pre> * * <p>While this may seem a more roundabout way to perform an aggregation * compared to simply mutating a running total in a loop, reduction * operations parallelize more gracefully, without needing additional * synchronization and with greatly reduced risk of data races. * * @param identity the identity value for the accumulating function * @param op an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * @return the result of the reduction * @see #sum() * @see #min() * @see #max() * @see #average() */ double reduce(double identity, DoubleBinaryOperator op); /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using an * <a href="package-summary.html#Associativity">associative</a> accumulation * function, and returns an {@code OptionalDouble} describing the reduced * value, if any. This is equivalent to: * <pre>{@code * boolean foundAny = false; * double result = null; * for (double element : this stream) { * if (!foundAny) { * foundAny = true; * result = element; * } * else * result = accumulator.applyAsDouble(result, element); * } * return foundAny ? OptionalDouble.of(result) : OptionalDouble.empty(); * }</pre> * * but is not constrained to execute sequentially. * * <p>The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param op an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * @return the result of the reduction * @see #reduce(double, DoubleBinaryOperator) */ OptionalDouble reduce(DoubleBinaryOperator op); /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream. A mutable * reduction is one in which the reduced value is a mutable result container, * such as an {@code ArrayList}, and elements are incorporated by updating * the state of the result rather than by replacing the result. This * produces a result equivalent to: * <pre>{@code * R result = supplier.get(); * for (double element : this stream) * accumulator.accept(result, element); * return result; * }</pre> * * <p>Like {@link #reduce(double, DoubleBinaryOperator)}, {@code collect} * operations can be parallelized without requiring additional * synchronization. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param <R> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for incorporating an additional element into a result * @param combiner an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values, which must be * compatible with the accumulator function * @return the result of the reduction * @see Stream#collect(Supplier, BiConsumer, BiConsumer) */ <R> R collect(Supplier<R> supplier, ObjDoubleConsumer<R> accumulator, BiConsumer<R, R> combiner); /** * Returns the sum of elements in this stream. * * Summation is a special case of a <a * href="package-summary.html#Reduction">reduction</a>. If * floating-point summation were exact, this method would be * equivalent to: * * <pre>{@code * return reduce(0, Double::sum); * }</pre> * * However, since floating-point summation is not exact, the above * code is not necessarily equivalent to the summation computation * done by this method. * * <p>If any stream element is a NaN or the sum is at any point a NaN * then the sum will be NaN. * * The value of a floating-point sum is a function both * of the input values as well as the order of addition * operations. The order of addition operations of this method is * intentionally not defined to allow for implementation * flexibility to improve the speed and accuracy of the computed * result. * * In particular, this method may be implemented using compensated * summation or other technique to reduce the error bound in the * numerical sum compared to a simple summation of {@code double} * values. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @apiNote Elements sorted by increasing absolute magnitude tend * to yield more accurate results. * * @return the sum of elements in this stream */ double sum(); /** * Returns an {@code OptionalDouble} describing the minimum element of this * stream, or an empty OptionalDouble if this stream is empty. The minimum * element will be {@code Double.NaN} if any stream element was NaN. Unlike * the numerical comparison operators, this method considers negative zero * to be strictly smaller than positive zero. This is a special case of a * <a href="package-summary.html#Reduction">reduction</a> and is * equivalent to: * <pre>{@code * return reduce(Double::min); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code OptionalDouble} containing the minimum element of this * stream, or an empty optional if the stream is empty */ OptionalDouble min(); /** * Returns an {@code OptionalDouble} describing the maximum element of this * stream, or an empty OptionalDouble if this stream is empty. The maximum * element will be {@code Double.NaN} if any stream element was NaN. Unlike * the numerical comparison operators, this method considers negative zero * to be strictly smaller than positive zero. This is a * special case of a * <a href="package-summary.html#Reduction">reduction</a> and is * equivalent to: * <pre>{@code * return reduce(Double::max); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code OptionalDouble} containing the maximum element of this * stream, or an empty optional if the stream is empty */ OptionalDouble max(); /** * Returns the count of elements in this stream. This is a special case of * a <a href="package-summary.html#Reduction">reduction</a> and is * equivalent to: * <pre>{@code * return mapToLong(e -> 1L).sum(); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @return the count of elements in this stream */ long count(); /** * Returns an {@code OptionalDouble} describing the arithmetic * mean of elements of this stream, or an empty optional if this * stream is empty. * * If any recorded value is a NaN or the sum is at any point a NaN * then the average will be NaN. * * <p>The average returned can vary depending upon the order in * which values are recorded. * * This method may be implemented using compensated summation or * other technique to reduce the error bound in the {@link #sum * numerical sum} used to compute the average. * * <p>The average is a special case of a <a * href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @apiNote Elements sorted by increasing absolute magnitude tend * to yield more accurate results. * * @return an {@code OptionalDouble} containing the average element of this * stream, or an empty optional if the stream is empty */ OptionalDouble average(); /** * Returns a {@code DoubleSummaryStatistics} describing various summary data * about the elements of this stream. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return a {@code DoubleSummaryStatistics} describing various summary data * about the elements of this stream */ DoubleSummaryStatistics summaryStatistics(); /** * Returns whether any elements of this stream match the provided * predicate. May not evaluate the predicate on all elements if not * necessary for determining the result. If the stream is empty then * {@code false} is returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>existential quantification</em> of the * predicate over the elements of the stream (for some x P(x)). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ boolean anyMatch(DoublePredicate predicate); /** * Returns whether all elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>universal quantification</em> of the * predicate over the elements of the stream (for all x P(x)). If the * stream is empty, the quantification is said to be <em>vacuously * satisfied</em> and is always {@code true} (regardless of P(x)). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ boolean allMatch(DoublePredicate predicate); /** * Returns whether no elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>universal quantification</em> of the * negated predicate over the elements of the stream (for all x ~P(x)). If * the stream is empty, the quantification is said to be vacuously satisfied * and is always {@code true}, regardless of P(x). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ boolean noneMatch(DoublePredicate predicate); /** * Returns an {@link OptionalDouble} describing the first element of this * stream, or an empty {@code OptionalDouble} if the stream is empty. If * the stream has no encounter order, then any element may be returned. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @return an {@code OptionalDouble} describing the first element of this * stream, or an empty {@code OptionalDouble} if the stream is empty */ OptionalDouble findFirst(); /** * Returns an {@link OptionalDouble} describing some element of the stream, * or an empty {@code OptionalDouble} if the stream is empty. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * <p>The behavior of this operation is explicitly nondeterministic; it is * free to select any element in the stream. This is to allow for maximal * performance in parallel operations; the cost is that multiple invocations * on the same source may not return the same result. (If a stable result * is desired, use {@link #findFirst()} instead.) * * @return an {@code OptionalDouble} describing some element of this stream, * or an empty {@code OptionalDouble} if the stream is empty * @see #findFirst() */ OptionalDouble findAny(); /** * Returns a {@code Stream} consisting of the elements of this stream, * boxed to {@code Double}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code Stream} consistent of the elements of this stream, * each boxed to a {@code Double} */ Stream<Double> boxed(); @Override DoubleStream sequential(); @Override DoubleStream parallel(); @Override PrimitiveIterator.OfDouble iterator(); @Override Spliterator.OfDouble spliterator(); // Static factories /** * Returns a builder for a {@code DoubleStream}. * * @return a stream builder */ public static Builder builder() { return new Streams.DoubleStreamBuilderImpl(); } /** * Returns an empty sequential {@code DoubleStream}. * * @return an empty sequential stream */ public static DoubleStream empty() { return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator(), false); } /** * Returns a sequential {@code DoubleStream} containing a single element. * * @param t the single element * @return a singleton sequential stream */ public static DoubleStream of(double t) { return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t), false); } /** * Returns a sequential ordered stream whose elements are the specified values. * * @param values the elements of the new stream * @return the new stream */ public static DoubleStream of(double... values) { return Arrays.stream(values); } /** * Returns an infinite sequential ordered {@code DoubleStream} produced by iterative * application of a function {@code f} to an initial element {@code seed}, * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, * {@code f(f(seed))}, etc. * * <p>The first element (position {@code 0}) in the {@code DoubleStream} * will be the provided {@code seed}. For {@code n > 0}, the element at * position {@code n}, will be the result of applying the function {@code f} * to the element at position {@code n - 1}. * * @param seed the initial element * @param f a function to be applied to to the previous element to produce * a new element * @return a new sequential {@code DoubleStream} */ public static DoubleStream iterate(final double seed, final DoubleUnaryOperator f) { Objects.requireNonNull(f); final PrimitiveIterator.OfDouble iterator = new PrimitiveIterator.OfDouble() { double t = seed; @Override public boolean hasNext() { return true; } @Override public double nextDouble() { double v = t; t = f.applyAsDouble(t); return v; } }; return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } /** * Returns an infinite sequential unordered stream where each element is * generated by the provided {@code DoubleSupplier}. This is suitable for * generating constant streams, streams of random elements, etc. * * @param s the {@code DoubleSupplier} for generated elements * @return a new infinite sequential unordered {@code DoubleStream} */ public static DoubleStream generate(DoubleSupplier s) { Objects.requireNonNull(s); return StreamSupport.doubleStream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s), false); } /** * Creates a lazily concatenated stream whose elements are all the * elements of the first stream followed by all the elements of the * second stream. The resulting stream is ordered if both * of the input streams are ordered, and parallel if either of the input * streams is parallel. When the resulting stream is closed, the close * handlers for both input streams are invoked. * * @implNote * Use caution when constructing streams from repeated concatenation. * Accessing an element of a deeply concatenated stream can result in deep * call chains, or even {@code StackOverflowException}. * * @param a the first stream * @param b the second stream * @return the concatenation of the two input streams */ public static DoubleStream concat(DoubleStream a, DoubleStream b) { Objects.requireNonNull(a); Objects.requireNonNull(b); Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble( a.spliterator(), b.spliterator()); DoubleStream stream = StreamSupport.doubleStream(split, a.isParallel() || b.isParallel()); return stream.onClose(Streams.composedClose(a, b)); } /** * A mutable builder for a {@code DoubleStream}. * * <p>A stream builder has a lifecycle, which starts in a building * phase, during which elements can be added, and then transitions to a built * phase, after which elements may not be added. The built phase * begins when the {@link #build()} method is called, which creates an * ordered stream whose elements are the elements that were added to the * stream builder, in the order they were added. * * @see DoubleStream#builder() * @since 1.8 */ public interface Builder extends DoubleConsumer { /** * Adds an element to the stream being built. * * @throws IllegalStateException if the builder has already transitioned * to the built state */ @Override void accept(double t); /** * Adds an element to the stream being built. * * @implSpec * The default implementation behaves as if: * <pre>{@code * accept(t) * return this; * }</pre> * * @param t the element to add * @return {@code this} builder * @throws IllegalStateException if the builder has already transitioned * to the built state */ default Builder add(double t) { accept(t); return this; } /** * Builds the stream, transitioning this builder to the built state. * An {@code IllegalStateException} is thrown if there are further * attempts to operate on the builder after it has entered the built * state. * * @return the built stream * @throws IllegalStateException if the builder has already transitioned * to the built state */ DoubleStream build(); } }
apache/phoenix
36,477
phoenix-core-client/src/main/java/org/apache/phoenix/util/QueryUtil.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.util; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ARRAY_SIZE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_FAMILY; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.COLUMN_SIZE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.DATA_TABLE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.DATA_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.GUIDE_POSTS_WIDTH; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.IMMUTABLE_ROWS; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.INDEX_STATE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.INDEX_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.IS_NAMESPACE_MAPPED; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.LINK_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.MULTI_TENANT; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.ORDINAL_POSITION; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.REF_GENERATION; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.REMARKS; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SALT_BUCKETS; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SELF_REFERENCING_COL_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SEQUENCE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SEQUENCE_SCHEMA; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SORT_ORDER; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SUPERTABLE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_ALIAS; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_SEQUENCE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_CAT; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_CATALOG; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_SCHEM; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TABLE_TYPE; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TENANT_ID; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TRANSACTIONAL; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TRANSACTION_PROVIDER; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_ID; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_NAME; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.VIEW_STATEMENT; import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.VIEW_TYPE; import static org.apache.phoenix.util.SchemaUtil.getEscapedFullColumnName; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CompareOperator; import org.apache.phoenix.expression.function.ExternalSqlTypeIdFunction; import org.apache.phoenix.expression.function.IndexStateNameFunction; import org.apache.phoenix.expression.function.SQLIndexTypeFunction; import org.apache.phoenix.expression.function.SQLTableTypeFunction; import org.apache.phoenix.expression.function.SQLViewTypeFunction; import org.apache.phoenix.expression.function.SqlTypeNameFunction; import org.apache.phoenix.expression.function.TransactionProviderNameFunction; import org.apache.phoenix.iterate.ResultIterator; import org.apache.phoenix.jdbc.ConnectionInfo; import org.apache.phoenix.jdbc.PhoenixConnection; import org.apache.phoenix.parse.HintNode; import org.apache.phoenix.parse.HintNode.Hint; import org.apache.phoenix.parse.TableName; import org.apache.phoenix.parse.WildcardParseNode; import org.apache.phoenix.query.QueryConstants; import org.apache.phoenix.query.QueryServices; import org.apache.phoenix.query.QueryServicesOptions; import org.apache.phoenix.schema.MetaDataClient; import org.apache.phoenix.schema.PName; import org.apache.phoenix.schema.PTable; import org.apache.phoenix.schema.PTableType; import org.apache.phoenix.schema.SortOrder; import org.apache.phoenix.schema.tool.SchemaExtractionProcessor; import org.apache.phoenix.schema.tool.SchemaProcessor; import org.apache.phoenix.schema.tuple.Tuple; import org.apache.phoenix.schema.types.PInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.phoenix.thirdparty.com.google.common.base.Function; import org.apache.phoenix.thirdparty.com.google.common.base.Joiner; import org.apache.phoenix.thirdparty.com.google.common.base.Preconditions; import org.apache.phoenix.thirdparty.com.google.common.collect.Iterables; import org.apache.phoenix.thirdparty.com.google.common.collect.Lists; public final class QueryUtil { private static final Logger LOGGER = LoggerFactory.getLogger(QueryUtil.class); /** * Column family name index within ResultSet resulting from * {@link DatabaseMetaData#getColumns(String, String, String, String)} */ public static final int COLUMN_FAMILY_POSITION = 25; /** * Column name index within ResultSet resulting from * {@link DatabaseMetaData#getColumns(String, String, String, String)} */ public static final int COLUMN_NAME_POSITION = 4; /** * Data type index within ResultSet resulting from * {@link DatabaseMetaData#getColumns(String, String, String, String)} */ public static final int DATA_TYPE_POSITION = 5; /** * Index of the column containing the datatype name within ResultSet resulting from * {@link DatabaseMetaData#getColumns(String, String, String, String)}. */ public static final int DATA_TYPE_NAME_POSITION = 6; public static final String IS_SERVER_CONNECTION = "IS_SERVER_CONNECTION"; public static final String REGIONS = "regions"; public static final String HOSTNAMES = "hostnames"; private static final String SELECT = "SELECT"; private static final String FROM = "FROM"; private static final String WHERE = "WHERE"; private static final String AND = "AND"; private static final String[] CompareOpString = new String[CompareOperator.values().length]; static { CompareOpString[CompareOperator.EQUAL.ordinal()] = "="; CompareOpString[CompareOperator.NOT_EQUAL.ordinal()] = "!="; CompareOpString[CompareOperator.GREATER.ordinal()] = ">"; CompareOpString[CompareOperator.LESS.ordinal()] = "<"; CompareOpString[CompareOperator.GREATER_OR_EQUAL.ordinal()] = ">="; CompareOpString[CompareOperator.LESS_OR_EQUAL.ordinal()] = "<="; } public static String toSQL(CompareOperator op) { return CompareOpString[op.ordinal()]; } /** * Private constructor */ private QueryUtil() { } /** * Generate an upsert statement based on a list of {@code ColumnInfo}s with parameter markers. The * list of {@code ColumnInfo}s must contain at least one element. * @param tableName name of the table for which the upsert statement is to be created * @param columnInfos list of column to be included in the upsert statement * @return the created {@code UPSERT} statement */ public static String constructUpsertStatement(String tableName, List<ColumnInfo> columnInfos) { if (columnInfos.isEmpty()) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } final List<String> columnNames = Lists.transform(columnInfos, new Function<ColumnInfo, String>() { @Override public String apply(ColumnInfo columnInfo) { return columnInfo.getColumnName(); } }); return constructUpsertStatement(tableName, columnNames, null); } /** * Generate an upsert statement based on a list of {@code ColumnInfo}s with parameter markers. The * list of {@code ColumnInfo}s must contain at least one element. * @param tableName name of the table for which the upsert statement is to be created * @param columns list of columns to be included in the upsert statement * @param hint hint to be added to the UPSERT statement. * @return the created {@code UPSERT} statement */ public static String constructUpsertStatement(String tableName, List<String> columns, Hint hint) { if (columns.isEmpty()) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } String hintStr = ""; if (hint != null) { final HintNode node = new HintNode(hint.name()); hintStr = node.toString(); } List<String> parameterList = Lists.newArrayList(); for (int i = 0; i < columns.size(); i++) { parameterList.add("?"); } return String.format("UPSERT %s INTO %s (%s) VALUES (%s)", hintStr, tableName, Joiner.on(", ").join(Iterables.transform(columns, new Function<String, String>() { @Nullable @Override public String apply(String columnName) { return getEscapedFullColumnName(columnName); } })), Joiner.on(", ").join(parameterList)); } /** * Generate a generic upsert statement based on a number of columns. The created upsert statement * will not include any named columns, but will include parameter markers for the given number of * columns. The number of columns must be greater than zero. * @param tableName name of the table for which the upsert statement is to be created * @param numColumns number of columns to be included in the upsert statement * @return the created {@code UPSERT} statement */ public static String constructGenericUpsertStatement(String tableName, int numColumns) { if (numColumns == 0) { throw new IllegalArgumentException("At least one column must be provided for upserts"); } List<String> parameterList = Lists.newArrayListWithCapacity(numColumns); for (int i = 0; i < numColumns; i++) { parameterList.add("?"); } return String.format("UPSERT INTO %s VALUES (%s)", tableName, Joiner.on(", ").join(parameterList)); } /** * @param fullTableName name of the table for which the select statement needs to be created. * @param columnInfos list of columns to be projected in the select statement. * @param conditions The condition clause to be added to the WHERE condition * @return Select Query */ public static String constructSelectStatement(String fullTableName, List<ColumnInfo> columnInfos, final String conditions) { List<String> columns = Lists.transform(columnInfos, new Function<ColumnInfo, String>() { @Override public String apply(ColumnInfo input) { return input.getColumnName(); } }); return constructSelectStatement(fullTableName, columns, conditions, null, false); } /** * @param fullTableName name of the table for which the select statement needs to be created. * @param columns list of columns to be projected in the select statement. * @param whereClause The condition clause to be added to the WHERE condition * @param hint hint to use * @param escapeCols whether to escape the projected columns * @return Select Query */ public static String constructSelectStatement(String fullTableName, List<String> columns, final String whereClause, Hint hint, boolean escapeCols) { return new QueryBuilder().setFullTableName(fullTableName).setSelectColumns(columns) .setWhereClause(whereClause).setHint(hint).setEscapeCols(escapeCols).build(); } /** * Constructs parameterized filter for an IN clause e.g. passing in numWhereCols=2, numBatches=3 * results in ((?,?),(?,?),(?,?)) * @param numWhereCols number of WHERE columns * @param numBatches number of column batches * @return paramterized IN filter */ public static String constructParameterizedInClause(int numWhereCols, int numBatches) { Preconditions.checkArgument(numWhereCols > 0); Preconditions.checkArgument(numBatches > 0); String batch = "(" + StringUtils.repeat("?", ",", numWhereCols) + ")"; return "(" + StringUtils.repeat(batch, ",", numBatches) + ")"; } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum) { return getUrlInternal(zkQuorum, null, null, null); } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum, int clientPort) { return getUrlInternal(zkQuorum, clientPort, null, null); } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum, String znodeParent) { return getUrlInternal(zkQuorum, null, znodeParent, null); } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum, int port, String znodeParent, String principal) { return getUrlInternal(zkQuorum, port, znodeParent, principal); } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum, int port, String znodeParent) { return getUrlInternal(zkQuorum, port, znodeParent, null); } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum, Integer port, String znodeParent) { return getUrlInternal(zkQuorum, port, znodeParent, null); } /** * Create the Phoenix JDBC connection URL from the provided cluster connection details. */ @Deprecated public static String getUrl(String zkQuorum, Integer port, String znodeParent, String principal) { return getUrlInternal(zkQuorum, port, znodeParent, principal); } @Deprecated private static String getUrlInternal(String zkQuorum, Integer port, String znodeParent, String principal) { return String.join(":", PhoenixRuntime.JDBC_PROTOCOL, zkQuorum, port == null ? "" : port.toString(), znodeParent == null ? "" : znodeParent, principal == null ? "" : principal) + Character.toString(PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR); } public static String getExplainPlan(ResultSet rs) throws SQLException { StringBuilder buf = new StringBuilder(); while (rs.next()) { buf.append(rs.getString(1)); buf.append('\n'); } if (buf.length() > 0) { buf.setLength(buf.length() - 1); } return buf.toString(); } public static String getExplainPlan(ResultIterator iterator) throws SQLException { List<String> steps = Lists.newArrayList(); iterator.explain(steps); StringBuilder buf = new StringBuilder(); for (String step : steps) { buf.append(step); buf.append('\n'); } if (buf.length() > 0) { buf.setLength(buf.length() - 1); } return buf.toString(); } /** * @return {@link PhoenixConnection} with {@value UpgradeUtil#DO_NOT_UPGRADE} set so that we don't * initiate metadata upgrade */ public static Connection getConnectionOnServer(Configuration conf) throws SQLException { return getConnectionOnServer(new Properties(), conf); } public static void setServerConnection(Properties props) { UpgradeUtil.doNotUpgradeOnFirstConnection(props); props.setProperty(IS_SERVER_CONNECTION, Boolean.TRUE.toString()); } public static boolean isServerConnection(ReadOnlyProps props) { return props.getBoolean(IS_SERVER_CONNECTION, false); } /** * @return {@link PhoenixConnection} with {@value UpgradeUtil#DO_NOT_UPGRADE} set and with the * upgrade-required flag cleared so that we don't initiate metadata upgrade. */ public static Connection getConnectionOnServer(Properties props, Configuration conf) throws SQLException { setServerConnection(props); Connection conn = getConnection(props, conf); conn.unwrap(PhoenixConnection.class).getQueryServices().clearUpgradeRequired(); return conn; } public static Connection getConnectionOnServerWithCustomUrl(Properties props, String principal) throws SQLException { setServerConnection(props); String url = getConnectionUrl(props, null, principal); LOGGER.info("Creating connection with the jdbc url: " + url); return DriverManager.getConnection(url, props); } public static Connection getConnection(Configuration conf) throws SQLException { return getConnection(new Properties(), conf); } public static Connection getConnection(Properties props, Configuration conf) throws SQLException { String url = getConnectionUrl(props, conf); LOGGER.info(String.format("Creating connection with the jdbc url: %s, isServerSide = %s", url, props.getProperty(IS_SERVER_CONNECTION))); props = PropertiesUtil.combineProperties(props, conf); return DriverManager.getConnection(url, props); } public static String getConnectionUrl(Properties props, Configuration conf) throws SQLException { return getConnectionUrl(props, conf, null); } /** Returns connection url using the various properties set in props and conf. */ public static String getConnectionUrl(Properties props, Configuration conf, String principal) throws SQLException { ReadOnlyProps propsWithPrincipal; if (principal != null) { Map<String, String> principalProp = new HashMap<>(); principalProp.put(QueryServices.HBASE_CLIENT_PRINCIPAL, principal); propsWithPrincipal = new ReadOnlyProps(principalProp.entrySet().iterator()); } else { propsWithPrincipal = ReadOnlyProps.EMPTY_PROPS; } ConnectionInfo info = ConnectionInfo.createNoLogin(PhoenixRuntime.JDBC_PROTOCOL, conf, propsWithPrincipal, props); String url = info.toUrl(); if (url.endsWith(PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR + "")) { url = url.substring(0, url.length() - 1); } // Mainly for testing to tack on the test=true part to ensure driver is found on server String defaultExtraArgs = conf != null ? conf.get(QueryServices.EXTRA_JDBC_ARGUMENTS_ATTRIB, QueryServicesOptions.DEFAULT_EXTRA_JDBC_ARGUMENTS) : QueryServicesOptions.DEFAULT_EXTRA_JDBC_ARGUMENTS; // If props doesn't have a default for extra args then use the extra args in conf as default String extraArgs = props.getProperty(QueryServices.EXTRA_JDBC_ARGUMENTS_ATTRIB, defaultExtraArgs); if (extraArgs.length() > 0) { url += PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR + extraArgs + PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR; } else { url += PhoenixRuntime.JDBC_PROTOCOL_TERMINATOR; } return url; } private static int getInt(String key, int defaultValue, Properties props, Configuration conf) { if (conf == null) { Preconditions.checkNotNull(props); return Integer.parseInt(props.getProperty(key, String.valueOf(defaultValue))); } return conf.getInt(key, defaultValue); } private static String getString(String key, String defaultValue, Properties props, Configuration conf) { if (conf == null) { Preconditions.checkNotNull(props); return props.getProperty(key, defaultValue); } return conf.get(key, defaultValue); } public static String getViewStatement(String schemaName, String tableName, String where) { // Only form we currently support for VIEWs: SELECT * FROM t WHERE ... return SELECT + " " + WildcardParseNode.NAME + " " + FROM + " " + (schemaName == null || schemaName.length() == 0 ? "" : ("\"" + schemaName + "\".")) + ("\"" + tableName + "\" ") + (WHERE + " " + where); } public static Integer getOffsetLimit(Integer limit, Integer offset) { if (limit == null) { return null; } else if (offset == null) { return limit; } else { return limit + offset; } } public static Integer getRemainingOffset(Tuple offsetTuple) { if (offsetTuple != null) { Cell cell = offsetTuple.getValue(QueryConstants.OFFSET_FAMILY, QueryConstants.OFFSET_COLUMN); if (cell != null) { return PInteger.INSTANCE.toObject(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength(), PInteger.INSTANCE, SortOrder.ASC, null, null); } } return null; } public static String getViewPartitionClause(String partitionColumnName, long autoPartitionNum) { return partitionColumnName + " " + toSQL(CompareOperator.EQUAL) + " " + autoPartitionNum; } public static Connection getConnectionForQueryLog(Configuration config) throws SQLException { // we don't need this connection to upgrade anything or start dispatcher return getConnectionOnServer(config); } public static PreparedStatement getCatalogsStmt(PhoenixConnection connection) throws SQLException { List<String> parameterValues = new ArrayList<String>(4); StringBuilder buf = new StringBuilder("select \n" + " DISTINCT " + TENANT_ID + " " + TABLE_CAT + " from " + SYSTEM_CATALOG + " " + SYSTEM_CATALOG_ALIAS + " where " + COLUMN_NAME + " is null" + " and " + COLUMN_FAMILY + " is null" + " and " + TENANT_ID + " is not null"); addTenantIdFilter(connection, buf, null, parameterValues); buf.append(" order by " + TENANT_ID); PreparedStatement stmt = connection.prepareStatement(buf.toString()); for (int i = 0; i < parameterValues.size(); i++) { stmt.setString(i + 1, parameterValues.get(i)); } return stmt; } /** * Util that generates a PreparedStatement against syscat to fetch schema listings. */ public static PreparedStatement getSchemasStmt(PhoenixConnection connection, String catalog, String schemaPattern) throws SQLException { List<String> parameterValues = new ArrayList<String>(4); StringBuilder buf = new StringBuilder( "select distinct \n" + TABLE_SCHEM + "," + TENANT_ID + " " + TABLE_CATALOG + " from " + SYSTEM_CATALOG + " " + SYSTEM_CATALOG_ALIAS + " where " + COLUMN_NAME + " is null"); addTenantIdFilter(connection, buf, catalog, parameterValues); if (schemaPattern != null) { buf.append(" and " + TABLE_SCHEM + (schemaPattern.length() == 0 ? " is null" : " like ?")); if (schemaPattern.length() > 0) { parameterValues.add(schemaPattern); } } if (SchemaUtil.isNamespaceMappingEnabled(null, connection.getQueryServices().getProps())) { buf.append(" and " + TABLE_NAME + " = '" + MetaDataClient.EMPTY_TABLE + "'"); } // TODO: we should union this with SYSTEM.SEQUENCE too, but we only have support for // UNION ALL and we really need UNION so that it dedups. PreparedStatement stmt = connection.prepareStatement(buf.toString()); for (int i = 0; i < parameterValues.size(); i++) { stmt.setString(i + 1, parameterValues.get(i)); } return stmt; } public static PreparedStatement getSuperTablesStmt(PhoenixConnection connection, String catalog, String schemaPattern, String tableNamePattern) throws SQLException { List<String> parameterValues = new ArrayList<String>(4); StringBuilder buf = new StringBuilder("select \n" + TENANT_ID + " " + TABLE_CAT + "," + // Use // tenantId // for // catalog TABLE_SCHEM + "," + TABLE_NAME + "," + COLUMN_FAMILY + " " + SUPERTABLE_NAME + " from " + SYSTEM_CATALOG + " " + SYSTEM_CATALOG_ALIAS + " where " + COLUMN_NAME + " is null" + " and " + LINK_TYPE + " = " + PTable.LinkType.PHYSICAL_TABLE.getSerializedValue()); addTenantIdFilter(connection, buf, catalog, parameterValues); if (schemaPattern != null) { buf.append(" and " + TABLE_SCHEM + (schemaPattern.length() == 0 ? " is null" : " like ?")); if (schemaPattern.length() > 0) { parameterValues.add(schemaPattern); } } if (tableNamePattern != null) { buf.append(" and " + TABLE_NAME + " like ?"); parameterValues.add(tableNamePattern); } buf.append( " order by " + TENANT_ID + "," + TABLE_SCHEM + "," + TABLE_NAME + "," + SUPERTABLE_NAME); PreparedStatement stmt = connection.prepareStatement(buf.toString()); for (int i = 0; i < parameterValues.size(); i++) { stmt.setString(i + 1, parameterValues.get(i)); } return stmt; } public static PreparedStatement getIndexInfoStmt(PhoenixConnection connection, String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { if (unique) { // No unique indexes return null; } List<String> parameterValues = new ArrayList<String>(4); StringBuilder buf = new StringBuilder("select \n" + TENANT_ID + " " + TABLE_CAT + ",\n" + // use // this // column // for // column // family // name TABLE_SCHEM + ",\n" + DATA_TABLE_NAME + " " + TABLE_NAME + ",\n" + "true NON_UNIQUE,\n" + "null INDEX_QUALIFIER,\n" + TABLE_NAME + " INDEX_NAME,\n" + DatabaseMetaData.tableIndexOther + " TYPE,\n" + ORDINAL_POSITION + ",\n" + COLUMN_NAME + ",\n" + "CASE WHEN " + COLUMN_FAMILY + " IS NOT NULL THEN null WHEN " + SORT_ORDER + " = " + (SortOrder.DESC.getSystemValue()) + " THEN 'D' ELSE 'A' END ASC_OR_DESC,\n" + "null CARDINALITY,\n" + "null PAGES,\n" + "null FILTER_CONDITION,\n" + // Include data type info, though not in spec ExternalSqlTypeIdFunction.NAME + "(" + DATA_TYPE + ") AS " + DATA_TYPE + ",\n" + SqlTypeNameFunction.NAME + "(" + DATA_TYPE + ") AS " + TYPE_NAME + ",\n" + DATA_TYPE + " " + TYPE_ID + ",\n" + COLUMN_FAMILY + ",\n" + COLUMN_SIZE + ",\n" + ARRAY_SIZE + "\nfrom " + SYSTEM_CATALOG + "\nwhere "); buf.append(TABLE_SCHEM + (schema == null || schema.length() == 0 ? " is null" : " = ?")); if (schema != null && schema.length() > 0) { parameterValues.add(schema); } buf.append("\nand " + DATA_TABLE_NAME + " = ?"); parameterValues.add(table); buf.append("\nand " + COLUMN_NAME + " is not null"); addTenantIdFilter(connection, buf, catalog, parameterValues); buf.append("\norder by INDEX_NAME," + ORDINAL_POSITION); PreparedStatement stmt = connection.prepareStatement(buf.toString()); for (int i = 0; i < parameterValues.size(); i++) { stmt.setString(i + 1, parameterValues.get(i)); } return stmt; } /** * Util that generates a PreparedStatement against syscat to get the table listing in a given * schema. */ public static PreparedStatement getTablesStmt(PhoenixConnection connection, String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { boolean isSequence = false; boolean hasTableTypes = types != null && types.length > 0; StringBuilder typeClauseBuf = new StringBuilder(); List<String> parameterValues = new ArrayList<String>(4); if (hasTableTypes) { List<String> tableTypes = Lists.newArrayList(types); isSequence = tableTypes.remove(SEQUENCE_TABLE_TYPE); StringBuilder typeBuf = new StringBuilder(); for (String type : tableTypes) { try { PTableType tableType = PTableType.fromValue(type); typeBuf.append('\''); typeBuf.append(tableType.getSerializedValue()); typeBuf.append('\''); typeBuf.append(','); } catch (IllegalArgumentException e) { // Ignore and continue } } if (typeBuf.length() > 0) { typeClauseBuf.append(" and " + TABLE_TYPE + " IN ("); typeClauseBuf.append(typeBuf); typeClauseBuf.setCharAt(typeClauseBuf.length() - 1, ')'); } } StringBuilder buf = new StringBuilder("select \n"); // If there were table types specified and they were all filtered out // and we're not querying for sequences, return an empty result set. if (hasTableTypes && typeClauseBuf.length() == 0 && !isSequence) { return null; } if (typeClauseBuf.length() > 0 || !isSequence) { buf.append(TENANT_ID + " " + TABLE_CAT + "," + // tenant_id is the catalog TABLE_SCHEM + "," + TABLE_NAME + " ," + SQLTableTypeFunction.NAME + "(" + TABLE_TYPE + ") AS " + TABLE_TYPE + "," + REMARKS + " ," + TYPE_NAME + "," + SELF_REFERENCING_COL_NAME + "," + REF_GENERATION + "," + IndexStateNameFunction.NAME + "(" + INDEX_STATE + ") AS " + INDEX_STATE + "," + IMMUTABLE_ROWS + "," + SALT_BUCKETS + "," + MULTI_TENANT + "," + VIEW_STATEMENT + "," + SQLViewTypeFunction.NAME + "(" + VIEW_TYPE + ") AS " + VIEW_TYPE + "," + SQLIndexTypeFunction.NAME + "(" + INDEX_TYPE + ") AS " + INDEX_TYPE + "," + TRANSACTION_PROVIDER + " IS NOT NULL AS " + TRANSACTIONAL + "," + IS_NAMESPACE_MAPPED + "," + GUIDE_POSTS_WIDTH + "," + TransactionProviderNameFunction.NAME + "(" + TRANSACTION_PROVIDER + ") AS TRANSACTION_PROVIDER" + " from " + SYSTEM_CATALOG + " " + SYSTEM_CATALOG_ALIAS + " where " + COLUMN_NAME + " is null" + " and " + COLUMN_FAMILY + " is null" + " and " + TABLE_NAME + " != '" + MetaDataClient.EMPTY_TABLE + "'"); addTenantIdFilter(connection, buf, catalog, parameterValues); if (schemaPattern != null) { buf.append(" and " + TABLE_SCHEM + (schemaPattern.length() == 0 ? " is null" : " like ?")); if (schemaPattern.length() > 0) { parameterValues.add(schemaPattern); } } if (tableNamePattern != null) { buf.append(" and " + TABLE_NAME + " like ?"); parameterValues.add(tableNamePattern); } if (typeClauseBuf.length() > 0) { buf.append(typeClauseBuf); } } if (isSequence) { // Union the SYSTEM.CATALOG entries with the SYSTEM.SEQUENCE entries if (typeClauseBuf.length() > 0) { buf.append(" UNION ALL\n"); buf.append(" select\n"); } buf.append(TENANT_ID + " " + TABLE_CAT + "," + // tenant_id is the catalog SEQUENCE_SCHEMA + " " + TABLE_SCHEM + "," + SEQUENCE_NAME + " " + TABLE_NAME + " ," + "'" + SEQUENCE_TABLE_TYPE + "' " + TABLE_TYPE + "," + "'' " + REMARKS + " ," + "'' " + TYPE_NAME + "," + "'' " + SELF_REFERENCING_COL_NAME + "," + "'' " + REF_GENERATION + "," + "CAST(null AS CHAR(1)) " + INDEX_STATE + "," + "CAST(null AS BOOLEAN) " + IMMUTABLE_ROWS + "," + "CAST(null AS INTEGER) " + SALT_BUCKETS + "," + "CAST(null AS BOOLEAN) " + MULTI_TENANT + "," + "'' " + VIEW_STATEMENT + "," + "'' " + VIEW_TYPE + "," + "'' " + INDEX_TYPE + "," + "CAST(null AS BOOLEAN) " + TRANSACTIONAL + "," + "CAST(null AS BOOLEAN) " + IS_NAMESPACE_MAPPED + "," + "CAST(null AS BIGINT) " + GUIDE_POSTS_WIDTH + "," + "CAST(null AS VARCHAR) " + TRANSACTION_PROVIDER + "\n"); buf.append(" from " + SYSTEM_SEQUENCE + "\n"); StringBuilder whereClause = new StringBuilder(); addTenantIdFilter(connection, whereClause, catalog, parameterValues); if (schemaPattern != null) { appendConjunction(whereClause); whereClause .append(SEQUENCE_SCHEMA + (schemaPattern.length() == 0 ? " is null" : " like ?\n")); if (schemaPattern.length() > 0) { parameterValues.add(schemaPattern); } } if (tableNamePattern != null) { appendConjunction(whereClause); whereClause.append(SEQUENCE_NAME + " like ?\n"); parameterValues.add(tableNamePattern); } if (whereClause.length() > 0) { buf.append(" where\n"); buf.append(whereClause); } } buf.append(" order by 4, 1, 2, 3\n"); PreparedStatement stmt = connection.prepareStatement(buf.toString()); for (int i = 0; i < parameterValues.size(); i++) { stmt.setString(i + 1, parameterValues.get(i)); } return stmt; } /** * Util that generates a PreparedStatement against syscat to get the table listing in a given * schema. */ public static PreparedStatement getShowCreateTableStmt(PhoenixConnection connection, String catalog, TableName tn) throws SQLException { String output; SchemaProcessor processor = new SchemaExtractionProcessor(null, connection.unwrap(PhoenixConnection.class).getQueryServices().getConfiguration(), tn.getSchemaName() == null ? null : "\"" + tn.getSchemaName() + "\"", "\"" + tn.getTableName() + "\""); try { output = processor.process(); } catch (Exception e) { LOGGER.error(e.getStackTrace().toString()); throw new SQLException(e.getMessage()); } StringBuilder buf = new StringBuilder("select \n" + " ? as \"CREATE STATEMENT\""); PreparedStatement stmt = connection.prepareStatement(buf.toString()); stmt.setString(1, output); return stmt; } public static void addTenantIdFilter(PhoenixConnection connection, StringBuilder buf, String tenantIdPattern, List<String> parameterValues) { PName tenantId = connection.getTenantId(); if (tenantIdPattern == null) { if (tenantId != null) { appendConjunction(buf); buf.append(" (" + TENANT_ID + " IS NULL " + " OR " + TENANT_ID + " = ?) "); parameterValues.add(tenantId.getString()); } } else if (tenantIdPattern.length() == 0) { appendConjunction(buf); buf.append(TENANT_ID + " IS NULL "); } else { appendConjunction(buf); buf.append(" TENANT_ID LIKE ? "); parameterValues.add(tenantIdPattern); if (tenantId != null) { buf.append(" and TENANT_ID = ? "); parameterValues.add(tenantId.getString()); } } } private static void appendConjunction(StringBuilder buf) { buf.append(buf.length() == 0 ? "" : " and "); } public static String generateInListParams(int nParams) { List<String> paramList = Lists.newArrayList(); for (int i = 0; i < nParams; i++) { paramList.add("?"); } return Joiner.on(", ").join(paramList); } public static void setQuoteInListElements(PreparedStatement ps, List<String> unQuotedString, int index) throws SQLException { for (int i = 0; i < unQuotedString.size(); i++) { ps.setString(++index, "'" + unQuotedString + "'"); } } }
googleapis/google-cloud-java
35,420
java-memcache/proto-google-cloud-memcache-v1/src/main/java/com/google/cloud/memcache/v1/CloudMemcacheProto.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/memcache/v1/cloud_memcache.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.memcache.v1; public final class CloudMemcacheProto { private CloudMemcacheProto() {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_Instance_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_Instance_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_Instance_NodeConfig_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_Instance_NodeConfig_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_Instance_Node_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_Instance_Node_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_Instance_InstanceMessage_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_Instance_InstanceMessage_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_Instance_LabelsEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_Instance_LabelsEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_MaintenancePolicy_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_MaintenancePolicy_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_WeeklyMaintenanceWindow_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_WeeklyMaintenanceWindow_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_MaintenanceSchedule_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_MaintenanceSchedule_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_RescheduleMaintenanceRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_RescheduleMaintenanceRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_ListInstancesRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_ListInstancesRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_ListInstancesResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_ListInstancesResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_GetInstanceRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_GetInstanceRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_CreateInstanceRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_CreateInstanceRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_UpdateInstanceRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_UpdateInstanceRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_DeleteInstanceRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_DeleteInstanceRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_ApplyParametersRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_ApplyParametersRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_UpdateParametersRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_UpdateParametersRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_MemcacheParameters_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_MemcacheParameters_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_MemcacheParameters_ParamsEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_MemcacheParameters_ParamsEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_OperationMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_OperationMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_LocationMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_LocationMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_LocationMetadata_AvailableZonesEntry_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_LocationMetadata_AvailableZonesEntry_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_memcache_v1_ZoneMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_memcache_v1_ZoneMetadata_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n" + "-google/cloud/memcache/v1/cloud_memcach" + "e.proto\022\030google.cloud.memcache.v1\032\034googl" + "e/api/annotations.proto\032\027google/api/clie" + "nt.proto\032\037google/api/field_behavior.prot" + "o\032\031google/api/resource.proto\032#google/lon" + "grunning/operations.proto\032\036google/protobuf/duration.proto\032" + " google/protobuf/field_mask.proto\032\037google/protobuf/timestamp.p" + "roto\032\033google/type/dayofweek.proto\032\033google/type/timeofday.proto\"\314\r\n" + "\010Instance\022\021\n" + "\004name\030\001 \001(\tB\003\340A\002\022\024\n" + "\014display_name\030\002 \001(\t\022>\n" + "\006labels\030\003 \003(\0132..google.cloud.memcache.v1.Instance.LabelsEntry\022\032\n" + "\022authorized_network\030\004 \001(\t\022\r\n" + "\005zones\030\005 \003(\t\022\027\n\n" + "node_count\030\006 \001(\005B\003\340A\002\022G\n" + "\013node_config\030\007 \001(\0132-.google.c" + "loud.memcache.v1.Instance.NodeConfigB\003\340A\002\022C\n" + "\020memcache_version\030\t" + " \001(\0162).google.cloud.memcache.v1.MemcacheVersion\022@\n\n" + "parameters\030\013 \001(\0132,.google.cloud.memcache.v1.MemcacheParameters\022D\n" + "\016memcache_nodes\030\014 \003(\013" + "2\'.google.cloud.memcache.v1.Instance.NodeB\003\340A\003\0224\n" + "\013create_time\030\r" + " \001(\0132\032.google.protobuf.TimestampB\003\340A\003\0224\n" + "\013update_time\030\016 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\022<\n" + "\005state\030\017" + " \001(\0162(.google.cloud.memcache.v1.Instance.StateB\003\340A\003\022\"\n" + "\025memcache_full_version\030\022 \001(\tB\003\340A\003\022M\n" + "\021instance_messages\030\023 \003(\0132" + "2.google.cloud.memcache.v1.Instance.InstanceMessage\022\037\n" + "\022discovery_endpoint\030\024 \001(\tB\003\340A\003\022G\n" + "\022maintenance_policy\030\025" + " \001(\0132+.google.cloud.memcache.v1.MaintenancePolicy\022P\n" + "\024maintenance_schedule\030\026 \001(\0132-.google.clo" + "ud.memcache.v1.MaintenanceScheduleB\003\340A\003\032A\n\n" + "NodeConfig\022\026\n" + "\tcpu_count\030\001 \001(\005B\003\340A\002\022\033\n" + "\016memory_size_mb\030\002 \001(\005B\003\340A\002\032\257\002\n" + "\004Node\022\024\n" + "\007node_id\030\001 \001(\tB\003\340A\003\022\021\n" + "\004zone\030\002 \001(\tB\003\340A\003\022A\n" + "\005state\030\003" + " \001(\0162-.google.cloud.memcache.v1.Instance.Node.StateB\003\340A\003\022\021\n" + "\004host\030\004 \001(\tB\003\340A\003\022\021\n" + "\004port\030\005 \001(\005B\003\340A\003\022@\n\n" + "parameters\030\006 \001(\0132,.google.cloud.memcache.v1.MemcacheParameters\"S\n" + "\005State\022\025\n" + "\021STATE_UNSPECIFIED\020\000\022\014\n" + "\010CREATING\020\001\022\t\n" + "\005READY\020\002\022\014\n" + "\010DELETING\020\003\022\014\n" + "\010UPDATING\020\004\032\251\001\n" + "\017InstanceMessage\022E\n" + "\004code\030\001" + " \001(\01627.google.cloud.memcache.v1.Instance.InstanceMessage.Code\022\017\n" + "\007message\030\002 \001(\t\">\n" + "\004Code\022\024\n" + "\020CODE_UNSPECIFIED\020\000\022 \n" + "\034ZONE_DISTRIBUTION_UNBALANCED\020\001\032-\n" + "\013LabelsEntry\022\013\n" + "\003key\030\001 \001(\t\022\r\n" + "\005value\030\002 \001(\t:\0028\001\"o\n" + "\005State\022\025\n" + "\021STATE_UNSPECIFIED\020\000\022\014\n" + "\010CREATING\020\001\022\t\n" + "\005READY\020\002\022\014\n" + "\010UPDATING\020\003\022\014\n" + "\010DELETING\020\004\022\032\n" + "\026PERFORMING_MAINTENANCE\020\005:c\352A`\n" + " memcache.googleapis.com/Instance\022<projects/{proje" + "ct}/locations/{location}/instances/{instance}\"\357\001\n" + "\021MaintenancePolicy\0224\n" + "\013create_time\030\001 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\0224\n" + "\013update_time\030\002" + " \001(\0132\032.google.protobuf.TimestampB\003\340A\003\022\023\n" + "\013description\030\003 \001(\t\022Y\n" + "\031weekly_maintenance_window\030\004 \003(\01321.google" + ".cloud.memcache.v1.WeeklyMaintenanceWindowB\003\340A\002\"\246\001\n" + "\027WeeklyMaintenanceWindow\022(\n" + "\003day\030\001 \001(\0162\026.google.type.DayOfWeekB\003\340A\002\022/\n" + "\n" + "start_time\030\002 \001(\0132\026.google.type.TimeOfDayB\003\340A\002\0220\n" + "\010duration\030\003 \001(\0132\031.google.protobuf.DurationB\003\340A\002\"\276\001\n" + "\023MaintenanceSchedule\0223\n\n" + "start_time\030\001 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\0221\n" + "\010end_time\030\002 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\022?\n" + "\026schedule_deadline_time\030\004" + " \001(\0132\032.google.protobuf.TimestampB\003\340A\003\"\342\002\n" + "\034RescheduleMaintenanceRequest\022:\n" + "\010instance\030\001 \001(\tB(\340A\002\372A\"\n" + " memcache.googleapis.com/Instance\022c\n" + "\017reschedule_type\030\002 \001(\0162E.google.cloud.memcache.v1.Resch" + "eduleMaintenanceRequest.RescheduleTypeB\003\340A\002\0221\n\r" + "schedule_time\030\003 \001(\0132\032.google.protobuf.Timestamp\"n\n" + "\016RescheduleType\022\037\n" + "\033RESCHEDULE_TYPE_UNSPECIFIED\020\000\022\r\n" + "\tIMMEDIATE\020\001\022\031\n" + "\025NEXT_AVAILABLE_WINDOW\020\002\022\021\n\r" + "SPECIFIC_TIME\020\003\"\232\001\n" + "\024ListInstancesRequest\0229\n" + "\006parent\030\001 \001(\tB)\340A\002\372A#\n" + "!locations.googleapis.com/Location\022\021\n" + "\tpage_size\030\002 \001(\005\022\022\n\n" + "page_token\030\003 \001(\t\022\016\n" + "\006filter\030\004 \001(\t\022\020\n" + "\010order_by\030\005 \001(\t\"|\n" + "\025ListInstancesResponse\0225\n" + "\tinstances\030\001 \003(\0132\".google.cloud.memcache.v1.Instance\022\027\n" + "\017next_page_token\030\002 \001(\t\022\023\n" + "\013unreachable\030\003 \003(\t\"L\n" + "\022GetInstanceRequest\0226\n" + "\004name\030\001 \001(\tB(\340A\002\372A\"\n" + " memcache.googleapis.com/Instance\"\247\001\n" + "\025CreateInstanceRequest\0229\n" + "\006parent\030\001 \001(\tB)\340A\002\372A#\n" + "!locations.googleapis.com/Location\022\030\n" + "\013instance_id\030\002 \001(\tB\003\340A\002\0229\n" + "\010instance\030\003" + " \001(\0132\".google.cloud.memcache.v1.InstanceB\003\340A\002\"\210\001\n" + "\025UpdateInstanceRequest\0224\n" + "\013update_mask\030\001 \001(\0132\032.google.protobuf.FieldMaskB\003\340A\002\0229\n" + "\010instance\030\002 \001(\0132\".google.cloud.memcache.v1.InstanceB\003\340A\002\"O\n" + "\025DeleteInstanceRequest\0226\n" + "\004name\030\001 \001(\tB(\340A\002\372A\"\n" + " memcache.googleapis.com/Instance\"u\n" + "\026ApplyParametersRequest\0226\n" + "\004name\030\001 \001(\tB(\340A\002\372A\"\n" + " memcache.googleapis.com/Instance\022\020\n" + "\010node_ids\030\002 \003(\t\022\021\n" + "\tapply_all\030\003 \001(\010\"\311\001\n" + "\027UpdateParametersRequest\0226\n" + "\004name\030\001 \001(\tB(\340A\002\372A\"\n" + " memcache.googleapis.com/Instance\0224\n" + "\013update_mask\030\002" + " \001(\0132\032.google.protobuf.FieldMaskB\003\340A\002\022@\n\n" + "parameters\030\003 \001(\0132,.google.cloud.memcache.v1.MemcacheParameters\"\236\001\n" + "\022MemcacheParameters\022\017\n" + "\002id\030\001 \001(\tB\003\340A\003\022H\n" + "\006params\030\003" + " \003(\01328.google.cloud.memcache.v1.MemcacheParameters.ParamsEntry\032-\n" + "\013ParamsEntry\022\013\n" + "\003key\030\001 \001(\t\022\r\n" + "\005value\030\002 \001(\t:\0028\001\"\371\001\n" + "\021OperationMetadata\0224\n" + "\013create_time\030\001 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\0221\n" + "\010end_time\030\002 \001(\0132\032.google.protobuf.TimestampB\003\340A\003\022\023\n" + "\006target\030\003 \001(\tB\003\340A\003\022\021\n" + "\004verb\030\004 \001(\tB\003\340A\003\022\032\n\r" + "status_detail\030\005 \001(\tB\003\340A\003\022\035\n" + "\020cancel_requested\030\006 \001(\010B\003\340A\003\022\030\n" + "\013api_version\030\007 \001(\tB\003\340A\003\"\317\001\n" + "\020LocationMetadata\022\\\n" + "\017available_zones\030\001 \003(\0132>.google.cloud.memca" + "che.v1.LocationMetadata.AvailableZonesEntryB\003\340A\003\032]\n" + "\023AvailableZonesEntry\022\013\n" + "\003key\030\001 \001(\t\0225\n" + "\005value\030\002 \001(\0132&.google.cloud.memcache.v1.ZoneMetadata:\0028\001\"\016\n" + "\014ZoneMetadata*E\n" + "\017MemcacheVersion\022 \n" + "\034MEMCACHE_VERSION_UNSPECIFIED\020\000\022\020\n" + "\014MEMCACHE_1_5\020\0012\305\020\n\r" + "CloudMemcache\022\260\001\n\r" + "ListInstances\022..google.cloud.memcache.v1.ListInstancesRequest\032/.goo" + "gle.cloud.memcache.v1.ListInstancesRespo" + "nse\">\332A\006parent\202\323\344\223\002/\022-/v1/{parent=projects/*/locations/*}/instances\022\235\001\n" + "\013GetInstance\022,.google.cloud.memcache.v1.GetInstan" + "ceRequest\032\".google.cloud.memcache.v1.Ins" + "tance\"<\332A\004name\202\323\344\223\002/\022-/v1/{name=projects/*/locations/*/instances/*}\022\222\002\n" + "\016CreateInstance\022/.google.cloud.memcache.v1.Create" + "InstanceRequest\032\035.google.longrunning.Operation\"\257\001\312AO\n" + "!google.cloud.memcache.v1.Instance\022*google.cloud.memcache.v1.Operat" + "ionMetadata\332A\033parent,instance,instance_i" + "d\202\323\344\223\0029\"-/v1/{parent=projects/*/locations/*}/instances:\010instance\022\224\002\n" + "\016UpdateInstance\022/.google.cloud.memcache.v1.UpdateIns" + "tanceRequest\032\035.google.longrunning.Operation\"\261\001\312AO\n" + "!google.cloud.memcache.v1.Instance\022*google.cloud.memcache.v1.Operation" + "Metadata\332A\024instance,update_mask\202\323\344\223\002B26/" + "v1/{instance.name=projects/*/locations/*/instances/*}:\010instance\022\240\002\n" + "\020UpdateParameters\0221.google.cloud.memcache.v1.UpdatePa" + "rametersRequest\032\035.google.longrunning.Operation\"\271\001\312AO\n" + "!google.cloud.memcache.v1.Instance\022*google.cloud.memcache.v1.Operat" + "ionMetadata\332A\033name,update_mask,parameter" + "s\202\323\344\223\002C2>/v1/{name=projects/*/locations/*/instances/*}:updateParameters:\001*\022\345\001\n" + "\016DeleteInstance\022/.google.cloud.memcache.v1" + ".DeleteInstanceRequest\032\035.google.longrunning.Operation\"\202\001\312AC\n" + "\025google.protobuf.Empty\022*google.cloud.memcache.v1.OperationMe" + "tadata\332A\004name\202\323\344\223\002/*-/v1/{name=projects/*/locations/*/instances/*}\022\231\002\n" + "\017ApplyParameters\0220.google.cloud.memcache.v1.ApplyP" + "arametersRequest\032\035.google.longrunning.Operation\"\264\001\312AO\n" + "!google.cloud.memcache.v1.Instance\022*google.cloud.memcache.v1.Opera" + "tionMetadata\332A\027name,node_ids,apply_all\202\323" + "\344\223\002B\"=/v1/{name=projects/*/locations/*/instances/*}:applyParameters:\001*\022\300\002\n" + "\025RescheduleMaintenance\0226.google.cloud.memcache" + ".v1.RescheduleMaintenanceRequest\032\035.google.longrunning.Operation\"\317\001\312AO\n" + "!google.cloud.memcache.v1.Instance\022*google.cloud.m" + "emcache.v1.OperationMetadata\332A(instance, reschedule_type," + " schedule_time\202\323\344\223\002L\"G/v1/{instance=projects/*/locations/*/inst" + "ances/*}:rescheduleMaintenance:\001*\032K\312A\027me" + "mcache.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platformBn\n" + "\034com.google.cloud.memcache.v1B\022CloudMemcachePro" + "toP\001Z8cloud.google.com/go/memcache/apiv1/memcachepb;memcachepbb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), com.google.api.ClientProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.longrunning.OperationsProto.getDescriptor(), com.google.protobuf.DurationProto.getDescriptor(), com.google.protobuf.FieldMaskProto.getDescriptor(), com.google.protobuf.TimestampProto.getDescriptor(), com.google.type.DayOfWeekProto.getDescriptor(), com.google.type.TimeOfDayProto.getDescriptor(), }); internal_static_google_cloud_memcache_v1_Instance_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_memcache_v1_Instance_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_Instance_descriptor, new java.lang.String[] { "Name", "DisplayName", "Labels", "AuthorizedNetwork", "Zones", "NodeCount", "NodeConfig", "MemcacheVersion", "Parameters", "MemcacheNodes", "CreateTime", "UpdateTime", "State", "MemcacheFullVersion", "InstanceMessages", "DiscoveryEndpoint", "MaintenancePolicy", "MaintenanceSchedule", }); internal_static_google_cloud_memcache_v1_Instance_NodeConfig_descriptor = internal_static_google_cloud_memcache_v1_Instance_descriptor.getNestedTypes().get(0); internal_static_google_cloud_memcache_v1_Instance_NodeConfig_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_Instance_NodeConfig_descriptor, new java.lang.String[] { "CpuCount", "MemorySizeMb", }); internal_static_google_cloud_memcache_v1_Instance_Node_descriptor = internal_static_google_cloud_memcache_v1_Instance_descriptor.getNestedTypes().get(1); internal_static_google_cloud_memcache_v1_Instance_Node_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_Instance_Node_descriptor, new java.lang.String[] { "NodeId", "Zone", "State", "Host", "Port", "Parameters", }); internal_static_google_cloud_memcache_v1_Instance_InstanceMessage_descriptor = internal_static_google_cloud_memcache_v1_Instance_descriptor.getNestedTypes().get(2); internal_static_google_cloud_memcache_v1_Instance_InstanceMessage_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_Instance_InstanceMessage_descriptor, new java.lang.String[] { "Code", "Message", }); internal_static_google_cloud_memcache_v1_Instance_LabelsEntry_descriptor = internal_static_google_cloud_memcache_v1_Instance_descriptor.getNestedTypes().get(3); internal_static_google_cloud_memcache_v1_Instance_LabelsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_Instance_LabelsEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_google_cloud_memcache_v1_MaintenancePolicy_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_memcache_v1_MaintenancePolicy_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_MaintenancePolicy_descriptor, new java.lang.String[] { "CreateTime", "UpdateTime", "Description", "WeeklyMaintenanceWindow", }); internal_static_google_cloud_memcache_v1_WeeklyMaintenanceWindow_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_memcache_v1_WeeklyMaintenanceWindow_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_WeeklyMaintenanceWindow_descriptor, new java.lang.String[] { "Day", "StartTime", "Duration", }); internal_static_google_cloud_memcache_v1_MaintenanceSchedule_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_memcache_v1_MaintenanceSchedule_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_MaintenanceSchedule_descriptor, new java.lang.String[] { "StartTime", "EndTime", "ScheduleDeadlineTime", }); internal_static_google_cloud_memcache_v1_RescheduleMaintenanceRequest_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_cloud_memcache_v1_RescheduleMaintenanceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_RescheduleMaintenanceRequest_descriptor, new java.lang.String[] { "Instance", "RescheduleType", "ScheduleTime", }); internal_static_google_cloud_memcache_v1_ListInstancesRequest_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_cloud_memcache_v1_ListInstancesRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_ListInstancesRequest_descriptor, new java.lang.String[] { "Parent", "PageSize", "PageToken", "Filter", "OrderBy", }); internal_static_google_cloud_memcache_v1_ListInstancesResponse_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_cloud_memcache_v1_ListInstancesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_ListInstancesResponse_descriptor, new java.lang.String[] { "Instances", "NextPageToken", "Unreachable", }); internal_static_google_cloud_memcache_v1_GetInstanceRequest_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_cloud_memcache_v1_GetInstanceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_GetInstanceRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_memcache_v1_CreateInstanceRequest_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_cloud_memcache_v1_CreateInstanceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_CreateInstanceRequest_descriptor, new java.lang.String[] { "Parent", "InstanceId", "Instance", }); internal_static_google_cloud_memcache_v1_UpdateInstanceRequest_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_cloud_memcache_v1_UpdateInstanceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_UpdateInstanceRequest_descriptor, new java.lang.String[] { "UpdateMask", "Instance", }); internal_static_google_cloud_memcache_v1_DeleteInstanceRequest_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_cloud_memcache_v1_DeleteInstanceRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_DeleteInstanceRequest_descriptor, new java.lang.String[] { "Name", }); internal_static_google_cloud_memcache_v1_ApplyParametersRequest_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_cloud_memcache_v1_ApplyParametersRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_ApplyParametersRequest_descriptor, new java.lang.String[] { "Name", "NodeIds", "ApplyAll", }); internal_static_google_cloud_memcache_v1_UpdateParametersRequest_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_cloud_memcache_v1_UpdateParametersRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_UpdateParametersRequest_descriptor, new java.lang.String[] { "Name", "UpdateMask", "Parameters", }); internal_static_google_cloud_memcache_v1_MemcacheParameters_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_cloud_memcache_v1_MemcacheParameters_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_MemcacheParameters_descriptor, new java.lang.String[] { "Id", "Params", }); internal_static_google_cloud_memcache_v1_MemcacheParameters_ParamsEntry_descriptor = internal_static_google_cloud_memcache_v1_MemcacheParameters_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_memcache_v1_MemcacheParameters_ParamsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_MemcacheParameters_ParamsEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_google_cloud_memcache_v1_OperationMetadata_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_google_cloud_memcache_v1_OperationMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_OperationMetadata_descriptor, new java.lang.String[] { "CreateTime", "EndTime", "Target", "Verb", "StatusDetail", "CancelRequested", "ApiVersion", }); internal_static_google_cloud_memcache_v1_LocationMetadata_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_google_cloud_memcache_v1_LocationMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_LocationMetadata_descriptor, new java.lang.String[] { "AvailableZones", }); internal_static_google_cloud_memcache_v1_LocationMetadata_AvailableZonesEntry_descriptor = internal_static_google_cloud_memcache_v1_LocationMetadata_descriptor .getNestedTypes() .get(0); internal_static_google_cloud_memcache_v1_LocationMetadata_AvailableZonesEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_LocationMetadata_AvailableZonesEntry_descriptor, new java.lang.String[] { "Key", "Value", }); internal_static_google_cloud_memcache_v1_ZoneMetadata_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_google_cloud_memcache_v1_ZoneMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_memcache_v1_ZoneMetadata_descriptor, new java.lang.String[] {}); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.ClientProto.defaultHost); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.AnnotationsProto.http); registry.add(com.google.api.ClientProto.methodSignature); registry.add(com.google.api.ClientProto.oauthScopes); registry.add(com.google.api.ResourceProto.resource); registry.add(com.google.api.ResourceProto.resourceReference); registry.add(com.google.longrunning.OperationsProto.operationInfo); com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor( descriptor, registry); com.google.api.AnnotationsProto.getDescriptor(); com.google.api.ClientProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.longrunning.OperationsProto.getDescriptor(); com.google.protobuf.DurationProto.getDescriptor(); com.google.protobuf.FieldMaskProto.getDescriptor(); com.google.protobuf.TimestampProto.getDescriptor(); com.google.type.DayOfWeekProto.getDescriptor(); com.google.type.TimeOfDayProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
googleapis/google-cloud-java
36,609
java-vertexai/proto-google-cloud-vertexai-v1/src/main/java/com/google/cloud/vertexai/api/ListEndpointsResponse.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/endpoint_service.proto // Protobuf Java Version: 3.25.3 package com.google.cloud.vertexai.api; /** * * * <pre> * Response message for * [EndpointService.ListEndpoints][google.cloud.aiplatform.v1.EndpointService.ListEndpoints]. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.ListEndpointsResponse} */ public final class ListEndpointsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.vertexai.v1.ListEndpointsResponse) ListEndpointsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListEndpointsResponse.newBuilder() to construct. private ListEndpointsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListEndpointsResponse() { endpoints_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListEndpointsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.EndpointServiceProto .internal_static_google_cloud_vertexai_v1_ListEndpointsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.EndpointServiceProto .internal_static_google_cloud_vertexai_v1_ListEndpointsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.ListEndpointsResponse.class, com.google.cloud.vertexai.api.ListEndpointsResponse.Builder.class); } public static final int ENDPOINTS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.vertexai.api.Endpoint> endpoints_; /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.vertexai.api.Endpoint> getEndpointsList() { return endpoints_; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.vertexai.api.EndpointOrBuilder> getEndpointsOrBuilderList() { return endpoints_; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ @java.lang.Override public int getEndpointsCount() { return endpoints_.size(); } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ @java.lang.Override public com.google.cloud.vertexai.api.Endpoint getEndpoints(int index) { return endpoints_.get(index); } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ @java.lang.Override public com.google.cloud.vertexai.api.EndpointOrBuilder getEndpointsOrBuilder(int index) { return endpoints_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ @java.lang.Override public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } } /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ @java.lang.Override public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (int i = 0; i < endpoints_.size(); i++) { output.writeMessage(1, endpoints_.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 < endpoints_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, endpoints_.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.vertexai.api.ListEndpointsResponse)) { return super.equals(obj); } com.google.cloud.vertexai.api.ListEndpointsResponse other = (com.google.cloud.vertexai.api.ListEndpointsResponse) obj; if (!getEndpointsList().equals(other.getEndpointsList())) 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 (getEndpointsCount() > 0) { hash = (37 * hash) + ENDPOINTS_FIELD_NUMBER; hash = (53 * hash) + getEndpointsList().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.vertexai.api.ListEndpointsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.ListEndpointsResponse 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.ListEndpointsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.ListEndpointsResponse 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.ListEndpointsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.vertexai.api.ListEndpointsResponse 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.ListEndpointsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.ListEndpointsResponse 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.ListEndpointsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.vertexai.api.ListEndpointsResponse 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.ListEndpointsResponse 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.ListEndpointsResponse 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.ListEndpointsResponse 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 * [EndpointService.ListEndpoints][google.cloud.aiplatform.v1.EndpointService.ListEndpoints]. * </pre> * * Protobuf type {@code google.cloud.vertexai.v1.ListEndpointsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.vertexai.v1.ListEndpointsResponse) com.google.cloud.vertexai.api.ListEndpointsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.vertexai.api.EndpointServiceProto .internal_static_google_cloud_vertexai_v1_ListEndpointsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.vertexai.api.EndpointServiceProto .internal_static_google_cloud_vertexai_v1_ListEndpointsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.vertexai.api.ListEndpointsResponse.class, com.google.cloud.vertexai.api.ListEndpointsResponse.Builder.class); } // Construct using com.google.cloud.vertexai.api.ListEndpointsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (endpointsBuilder_ == null) { endpoints_ = java.util.Collections.emptyList(); } else { endpoints_ = null; endpointsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.vertexai.api.EndpointServiceProto .internal_static_google_cloud_vertexai_v1_ListEndpointsResponse_descriptor; } @java.lang.Override public com.google.cloud.vertexai.api.ListEndpointsResponse getDefaultInstanceForType() { return com.google.cloud.vertexai.api.ListEndpointsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.vertexai.api.ListEndpointsResponse build() { com.google.cloud.vertexai.api.ListEndpointsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.vertexai.api.ListEndpointsResponse buildPartial() { com.google.cloud.vertexai.api.ListEndpointsResponse result = new com.google.cloud.vertexai.api.ListEndpointsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.vertexai.api.ListEndpointsResponse result) { if (endpointsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { endpoints_ = java.util.Collections.unmodifiableList(endpoints_); bitField0_ = (bitField0_ & ~0x00000001); } result.endpoints_ = endpoints_; } else { result.endpoints_ = endpointsBuilder_.build(); } } private void buildPartial0(com.google.cloud.vertexai.api.ListEndpointsResponse 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.vertexai.api.ListEndpointsResponse) { return mergeFrom((com.google.cloud.vertexai.api.ListEndpointsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.vertexai.api.ListEndpointsResponse other) { if (other == com.google.cloud.vertexai.api.ListEndpointsResponse.getDefaultInstance()) return this; if (endpointsBuilder_ == null) { if (!other.endpoints_.isEmpty()) { if (endpoints_.isEmpty()) { endpoints_ = other.endpoints_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureEndpointsIsMutable(); endpoints_.addAll(other.endpoints_); } onChanged(); } } else { if (!other.endpoints_.isEmpty()) { if (endpointsBuilder_.isEmpty()) { endpointsBuilder_.dispose(); endpointsBuilder_ = null; endpoints_ = other.endpoints_; bitField0_ = (bitField0_ & ~0x00000001); endpointsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getEndpointsFieldBuilder() : null; } else { endpointsBuilder_.addAllMessages(other.endpoints_); } } } 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.vertexai.api.Endpoint m = input.readMessage( com.google.cloud.vertexai.api.Endpoint.parser(), extensionRegistry); if (endpointsBuilder_ == null) { ensureEndpointsIsMutable(); endpoints_.add(m); } else { endpointsBuilder_.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.vertexai.api.Endpoint> endpoints_ = java.util.Collections.emptyList(); private void ensureEndpointsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { endpoints_ = new java.util.ArrayList<com.google.cloud.vertexai.api.Endpoint>(endpoints_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vertexai.api.Endpoint, com.google.cloud.vertexai.api.Endpoint.Builder, com.google.cloud.vertexai.api.EndpointOrBuilder> endpointsBuilder_; /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public java.util.List<com.google.cloud.vertexai.api.Endpoint> getEndpointsList() { if (endpointsBuilder_ == null) { return java.util.Collections.unmodifiableList(endpoints_); } else { return endpointsBuilder_.getMessageList(); } } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public int getEndpointsCount() { if (endpointsBuilder_ == null) { return endpoints_.size(); } else { return endpointsBuilder_.getCount(); } } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public com.google.cloud.vertexai.api.Endpoint getEndpoints(int index) { if (endpointsBuilder_ == null) { return endpoints_.get(index); } else { return endpointsBuilder_.getMessage(index); } } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder setEndpoints(int index, com.google.cloud.vertexai.api.Endpoint value) { if (endpointsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEndpointsIsMutable(); endpoints_.set(index, value); onChanged(); } else { endpointsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder setEndpoints( int index, com.google.cloud.vertexai.api.Endpoint.Builder builderForValue) { if (endpointsBuilder_ == null) { ensureEndpointsIsMutable(); endpoints_.set(index, builderForValue.build()); onChanged(); } else { endpointsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder addEndpoints(com.google.cloud.vertexai.api.Endpoint value) { if (endpointsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEndpointsIsMutable(); endpoints_.add(value); onChanged(); } else { endpointsBuilder_.addMessage(value); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder addEndpoints(int index, com.google.cloud.vertexai.api.Endpoint value) { if (endpointsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureEndpointsIsMutable(); endpoints_.add(index, value); onChanged(); } else { endpointsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder addEndpoints(com.google.cloud.vertexai.api.Endpoint.Builder builderForValue) { if (endpointsBuilder_ == null) { ensureEndpointsIsMutable(); endpoints_.add(builderForValue.build()); onChanged(); } else { endpointsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder addEndpoints( int index, com.google.cloud.vertexai.api.Endpoint.Builder builderForValue) { if (endpointsBuilder_ == null) { ensureEndpointsIsMutable(); endpoints_.add(index, builderForValue.build()); onChanged(); } else { endpointsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder addAllEndpoints( java.lang.Iterable<? extends com.google.cloud.vertexai.api.Endpoint> values) { if (endpointsBuilder_ == null) { ensureEndpointsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, endpoints_); onChanged(); } else { endpointsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder clearEndpoints() { if (endpointsBuilder_ == null) { endpoints_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { endpointsBuilder_.clear(); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public Builder removeEndpoints(int index) { if (endpointsBuilder_ == null) { ensureEndpointsIsMutable(); endpoints_.remove(index); onChanged(); } else { endpointsBuilder_.remove(index); } return this; } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public com.google.cloud.vertexai.api.Endpoint.Builder getEndpointsBuilder(int index) { return getEndpointsFieldBuilder().getBuilder(index); } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public com.google.cloud.vertexai.api.EndpointOrBuilder getEndpointsOrBuilder(int index) { if (endpointsBuilder_ == null) { return endpoints_.get(index); } else { return endpointsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public java.util.List<? extends com.google.cloud.vertexai.api.EndpointOrBuilder> getEndpointsOrBuilderList() { if (endpointsBuilder_ != null) { return endpointsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(endpoints_); } } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public com.google.cloud.vertexai.api.Endpoint.Builder addEndpointsBuilder() { return getEndpointsFieldBuilder() .addBuilder(com.google.cloud.vertexai.api.Endpoint.getDefaultInstance()); } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public com.google.cloud.vertexai.api.Endpoint.Builder addEndpointsBuilder(int index) { return getEndpointsFieldBuilder() .addBuilder(index, com.google.cloud.vertexai.api.Endpoint.getDefaultInstance()); } /** * * * <pre> * List of Endpoints in the requested page. * </pre> * * <code>repeated .google.cloud.vertexai.v1.Endpoint endpoints = 1;</code> */ public java.util.List<com.google.cloud.vertexai.api.Endpoint.Builder> getEndpointsBuilderList() { return getEndpointsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vertexai.api.Endpoint, com.google.cloud.vertexai.api.Endpoint.Builder, com.google.cloud.vertexai.api.EndpointOrBuilder> getEndpointsFieldBuilder() { if (endpointsBuilder_ == null) { endpointsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.vertexai.api.Endpoint, com.google.cloud.vertexai.api.Endpoint.Builder, com.google.cloud.vertexai.api.EndpointOrBuilder>( endpoints_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); endpoints_ = null; } return endpointsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The nextPageToken. */ public java.lang.String getNextPageToken() { java.lang.Object ref = nextPageToken_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextPageToken_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return The bytes for nextPageToken. */ public com.google.protobuf.ByteString getNextPageTokenBytes() { java.lang.Object ref = nextPageToken_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextPageToken_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageToken(java.lang.String value) { if (value == null) { throw new NullPointerException(); } nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @return This builder for chaining. */ public Builder clearNextPageToken() { nextPageToken_ = getDefaultInstance().getNextPageToken(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * A token to retrieve the next page of results. * Pass to * [ListEndpointsRequest.page_token][google.cloud.aiplatform.v1.ListEndpointsRequest.page_token] * to obtain that page. * </pre> * * <code>string next_page_token = 2;</code> * * @param value The bytes for nextPageToken to set. * @return This builder for chaining. */ public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); nextPageToken_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.vertexai.v1.ListEndpointsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.vertexai.v1.ListEndpointsResponse) private static final com.google.cloud.vertexai.api.ListEndpointsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.vertexai.api.ListEndpointsResponse(); } public static com.google.cloud.vertexai.api.ListEndpointsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListEndpointsResponse> PARSER = new com.google.protobuf.AbstractParser<ListEndpointsResponse>() { @java.lang.Override public ListEndpointsResponse 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<ListEndpointsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListEndpointsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.vertexai.api.ListEndpointsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/impala
36,978
fe/src/main/java/org/apache/impala/authorization/ranger/RangerAuthorizationChecker.java
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.impala.authorization.ranger; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.impala.analysis.AnalysisContext.AnalysisResult; import org.apache.impala.authorization.Authorizable; import org.apache.impala.authorization.Authorizable.Type; import org.apache.impala.authorization.AuthorizableTable; import org.apache.impala.authorization.AuthorizationChecker; import org.apache.impala.authorization.AuthorizationConfig; import org.apache.impala.authorization.AuthorizationContext; import org.apache.impala.authorization.AuthorizationException; import org.apache.impala.authorization.BaseAuthorizationChecker; import org.apache.impala.authorization.DefaultAuthorizableFactory; import org.apache.impala.authorization.Privilege; import org.apache.impala.authorization.PrivilegeRequest; import org.apache.impala.authorization.User; import org.apache.impala.catalog.FeCatalog; import org.apache.impala.common.InternalException; import org.apache.impala.common.RuntimeEnv; import org.apache.impala.service.BackendConfig; import org.apache.impala.thrift.TSessionState; import org.apache.impala.util.EventSequence; import org.apache.ranger.audit.model.AuthzAuditEvent; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerServiceDef; import org.apache.ranger.plugin.policyengine.RangerAccessRequest; import org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl; import org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl; import org.apache.ranger.plugin.policyengine.RangerAccessResult; import org.apache.ranger.plugin.policyengine.RangerPolicyEngine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; /** * An implementation of {@link AuthorizationChecker} that uses Ranger. * * The Ranger implementation does not use catalog to cache the authorization policy. * Ranger plugin uses its own cache. */ public class RangerAuthorizationChecker extends BaseAuthorizationChecker { private static final Logger LOG = LoggerFactory.getLogger( RangerAuthorizationChecker.class); // These are Ranger access types (privileges). public static final String UPDATE_ACCESS_TYPE = "update"; public static final String SELECT_ACCESS_TYPE = "select"; private final RangerImpalaPlugin plugin_; public RangerAuthorizationChecker(AuthorizationConfig authzConfig) { super(authzConfig); Preconditions.checkArgument(authzConfig instanceof RangerAuthorizationConfig); RangerAuthorizationConfig rangerConfig = (RangerAuthorizationConfig) authzConfig; plugin_ = RangerImpalaPlugin.getInstance(rangerConfig.getServiceType(), rangerConfig.getAppId()); } @Override protected boolean authorizeResource(AuthorizationContext authzCtx, User user, PrivilegeRequest request) throws InternalException { Preconditions.checkArgument(authzCtx instanceof RangerAuthorizationContext); Preconditions.checkNotNull(user); Preconditions.checkNotNull(request); RangerAuthorizationContext rangerAuthzCtx = (RangerAuthorizationContext) authzCtx; List<RangerAccessResourceImpl> resources = new ArrayList<>(); Authorizable authorizable = request.getAuthorizable(); Privilege privilege = request.getPrivilege(); switch (authorizable.getType()) { case SERVER: // Hive service definition does not have a concept of server. So we define // server to mean all access to all resource sets. resources.add(new RangerImpalaResourceBuilder() .database("*").table("*").column("*").build()); resources.add(new RangerImpalaResourceBuilder() .database("*").function("*").build()); resources.add(new RangerImpalaResourceBuilder().uri("*").build()); if (privilege == Privilege.ALL || privilege == Privilege.OWNER || privilege == Privilege.RWSTORAGE) { resources.add(new RangerImpalaResourceBuilder() .storageType("*").storageUri("*").build()); } break; case DB: resources.add(new RangerImpalaResourceBuilder() .database(authorizable.getDbName()) .owner(authorizable.getOwnerUser()) .build()); break; case TABLE: resources.add(new RangerImpalaResourceBuilder() .database(authorizable.getDbName()) .table(authorizable.getTableName()) .owner(authorizable.getOwnerUser()) .build()); break; case COLUMN: RangerImpalaResourceBuilder builder = new RangerImpalaResourceBuilder(); builder.database(authorizable.getDbName()); // * in Ranger means "all". For example, to check access for all columns, we need // to create a request, such as: // [server=server1, database=foo, table=bar, column=*] // // "Any" column access is special in Ranger. For example if we want to check if // we have access to "any" column on a particular table, we need to build a // request without the column defined in the resource and use a special // ANY_ACCESS access type. // // For example any column in foo.bar table: // access type: RangerPolicyEngine.ANY_ACCESS // resources: [server=server1, database=foo, table=bar] if (privilege != Privilege.ANY || !DefaultAuthorizableFactory.ALL.equals(authorizable.getTableName())) { builder.table(authorizable.getTableName()); } if (privilege != Privilege.ANY || !DefaultAuthorizableFactory.ALL.equals(authorizable.getColumnName())) { builder.column(authorizable.getColumnName()); } builder.owner(authorizable.getOwnerUser()); resources.add(builder.build()); break; case FUNCTION: resources.add(new RangerImpalaResourceBuilder() .database(authorizable.getDbName()) .function(authorizable.getFnName()) .build()); break; case URI: resources.add(new RangerImpalaResourceBuilder() .uri(authorizable.getName()) .build()); break; case STORAGEHANDLER_URI: resources.add(new RangerImpalaResourceBuilder() .storageType(authorizable.getStorageType()) .storageUri(authorizable.getStorageUri()) .build()); break; default: throw new IllegalArgumentException(String.format("Invalid authorizable type: %s", authorizable.getType())); } for (RangerAccessResourceImpl resource: resources) { if (privilege == Privilege.ANY) { if (!authorizeResource(rangerAuthzCtx, user, resource, authorizable, privilege, rangerAuthzCtx.getAuditHandler())) { return false; } } else { boolean authorized = privilege.hasAnyOf() ? authorizeAny(rangerAuthzCtx, resource, authorizable, user, privilege) : authorizeAll(rangerAuthzCtx, resource, authorizable, user, privilege); if (!authorized) { return false; } } } return true; } @Override public void postAuthorize(AuthorizationContext authzCtx, boolean authzOk, boolean analysisOk) { Preconditions.checkArgument(authzCtx instanceof RangerAuthorizationContext); super.postAuthorize(authzCtx, authzOk, analysisOk); // Consolidate the audit log entries and apply the deduplicated column masking events // to update the List of all AuthzAuditEvent's only if the authorization is // successful. if (authzOk) { // We consolidate the audit log entries before invoking // applyDeduplicatedAuthzEvents() where we add the deduplicated table // masking-related log entries to 'auditHandler' because currently a Ranger column // masking policy can be applied to only one single column in a table. Thus, we do // not need to combine log entries produced due to column masking policies. ((RangerAuthorizationContext) authzCtx).consolidateAuthzEvents(); ((RangerAuthorizationContext) authzCtx).applyDeduplicatedAuthzEvents(); } RangerBufferAuditHandler auditHandler = ((RangerAuthorizationContext) authzCtx).getAuditHandler(); if (authzOk && !analysisOk) { // When the query was authorized, we do not send any audit log entry to the Ranger // server if there was an AnalysisException during query analysis. // We still have to call clear() to remove audit log entries in this case because // the current test framework checks the contents in auditHandler.getAuthzEvents() // to determine whether the correct audit events are collected. auditHandler.getAuthzEvents().clear(); } else { // We send audit log entries to the Ranger server only if authorization failed or // analysis succeeded. auditHandler.flush(); } } @Override protected void authorizeRowFilterAndColumnMask(User user, List<PrivilegeRequest> privilegeRequests) throws AuthorizationException, InternalException { boolean isColumnMaskingEnabled = BackendConfig.INSTANCE.isColumnMaskingEnabled(); boolean isRowFilteringEnabled = BackendConfig.INSTANCE.isRowFilteringEnabled(); if (isColumnMaskingEnabled && isRowFilteringEnabled) return; for (PrivilegeRequest request : privilegeRequests) { if (!isColumnMaskingEnabled && request.getAuthorizable().getType() == Type.COLUMN) { throwIfColumnMaskingRequired(user, request.getAuthorizable().getDbName(), request.getAuthorizable().getTableName(), request.getAuthorizable().getColumnName()); } else if (!isRowFilteringEnabled && request.getAuthorizable().getType() == Type.TABLE) { throwIfRowFilteringRequired(user, request.getAuthorizable().getDbName(), request.getAuthorizable().getTableName()); } } } @Override public void invalidateAuthorizationCache() { long startTime = System.currentTimeMillis(); try { plugin_.refreshPoliciesAndTags(); } finally { LOG.debug("Refreshing Ranger policies took {} ms", (System.currentTimeMillis() - startTime)); } } @Override public AuthorizationContext createAuthorizationContext(boolean doAudits, String sqlStmt, TSessionState sessionState, Optional<EventSequence> timeline) { RangerAuthorizationContext authzCtx = new RangerAuthorizationContext(sessionState, timeline); if (doAudits) { // Any statement that goes through {@link authorize} will need to have audit logs. if (sqlStmt != null) { authzCtx.setAuditHandler(new RangerBufferAuditHandler( sqlStmt, plugin_.getClusterName(), sessionState.getNetwork_address().getHostname())); } else { authzCtx.setAuditHandler(new RangerBufferAuditHandler()); } } return authzCtx; } @Override protected void authorizeTableAccess(AuthorizationContext authzCtx, AnalysisResult analysisResult, FeCatalog catalog, List<PrivilegeRequest> requests) throws AuthorizationException, InternalException { RangerAuthorizationContext originalCtx = (RangerAuthorizationContext) authzCtx; RangerBufferAuditHandler originalAuditHandler = originalCtx.getAuditHandler(); // case 1: table (select) OK, columns (select) OK --> add the table event, // add the column events // case 2: table (non-select) ERROR --> add the table event // case 3: table (select) ERROR, columns (select) OK -> only add the column events // case 4: table (select) ERROR, columns (select) ERROR --> add the table event // case 5: table (select) ERROR --> add the table event // This could happen when the select request for a non-existing table fails // the authorization. // case 6: table (select) OK, columns (select) ERROR --> add the first column event // This could happen when the requesting user is granted the select privilege // on the table but is denied access to a column in the same table in Ranger. RangerAuthorizationContext tmpCtx = new RangerAuthorizationContext( originalCtx.getSessionState(), originalCtx.getTimeline()); tmpCtx.setAuditHandler(new RangerBufferAuditHandler(originalAuditHandler)); AuthorizationException authorizationException = null; try { super.authorizeTableAccess(tmpCtx, analysisResult, catalog, requests); } catch (AuthorizationException e) { authorizationException = e; tmpCtx.getAuditHandler().getAuthzEvents().stream() .filter(evt -> // case 2: get the first failing non-select table (!"select".equalsIgnoreCase(evt.getAccessType()) && "@table".equals(evt.getResourceType())) || // case 4 & 5 & 6: get the table or a column event (("@table".equals(evt.getResourceType()) || "@column".equals(evt.getResourceType())) && evt.getAccessResult() == 0)) .findFirst() .ifPresent(evt -> originalCtx.getAuditHandler().getAuthzEvents().add(evt)); throw e; } finally { // We should not add successful events when there was an AuthorizationException. // Specifically, we should not add the successful table event in case 6. if (authorizationException == null) { // case 1 & 3: we only add the successful events. // TODO(IMPALA-11381): Consider whether we should keep the table-level event which // corresponds to a check only for short-circuiting authorization. List<AuthzAuditEvent> events = tmpCtx.getAuditHandler().getAuthzEvents().stream() .filter(evt -> evt.getAccessResult() != 0) .collect(Collectors.toList()); originalCtx.getAuditHandler().getAuthzEvents().addAll(events); } } } /** * This method throws an {@link AuthorizationException} if column mask is enabled on the * given column. This is used to prevent data leak when Hive has column mask enabled but * it's disabled in Impala. */ private void throwIfColumnMaskingRequired(User user, String dbName, String tableName, String columnName) throws InternalException, AuthorizationException { if (evalColumnMask(user, dbName, tableName, columnName, null).isMaskEnabled()) { throw new AuthorizationException(String.format( "Column masking is disabled by --enable_column_masking flag. Can't access " + "column %s.%s.%s that has column masking policy.", dbName, tableName, columnName)); } } @Override public boolean needsMaskingOrFiltering(User user, String dbName, String tableName, List<String> requiredColumns) throws InternalException { for (String column: requiredColumns) { if (evalColumnMask(user, dbName, tableName, column, null) .isMaskEnabled()) { return true; } } return needsRowFiltering(user, dbName, tableName); } @Override public boolean needsRowFiltering(User user, String dbName, String tableName) throws InternalException { return evalRowFilter(user, dbName, tableName, null).isRowFilterEnabled(); } /** * Util method for removing stale audit events of column masking and row filtering * policies. See comments below for cases we need this. * * TODO: Revisit RangerBufferAuditHandler and compare it to * org.apache.ranger.authorization.hive.authorizer.RangerHiveAuditHandler to see * whether we can avoid generating stale audit events there. * TODO: Do we really need this for row-filtering? */ private void removeStaleAudits(RangerBufferAuditHandler auditHandler, int numAuthzAuditEventsBefore) { // When a user adds an "Unmasked" policy for 'columnName' that retains the original // value, accessResult.getMaskType() would be "MASK_NONE". We do not need to log such // an event. Removing such an event also makes the logged audits consistent when // there is at least one "Unmasked" policy. Recall that this method is the only place // evalColumnMask() is called with a non-null RangerBufferAuditHandler to produce // AuthzAuditEvent's. When an "Unmasked" policy is the only column masking policy // involved in this query, this method would not be invoked because isMaskEnabled() // of the corresponding RangerAccessResult is false in needsMaskingOrFiltering(), // whereas this method will be called when there are policies of other types. If we // do not remove the event of the "Unmasked" policy, we will have one more logged // event in the latter case where there are policies other than "Unmasked". // Moreover, notice that there will be an AuthzAuditEvent added to // 'auditHandler.getAuthzEvents()' as long as there exists a column masking policy // associated with 'dbName', 'tableName', and 'columnName', even though the policy // does NOT apply to 'user'. In this case, accessResult.isMaskEnabled() would be // false, and accessResult.getPolicyId() would be -1. In addition, the field of // 'accessResult' would be 0 for that AuthzAuditEvent. An AuthzAuditEvent with // 'accessResult' equal to 0 will be considered as an indication of a failed access // request in RangerBufferAuditHandler#flush() even though there is no failed access // request at all for the current query and thus we need to filter out this // AuthzAuditEvent. If we did not filter it out, other AuthzAuditEvent's // corresponding to successful/allowed access requests in the same query will not be // logged since only the first AuthzAuditEvent with 'accessResult' equal to 0 is // logged in RangerBufferAuditHandler#flush(). List<AuthzAuditEvent> auditEvents = auditHandler.getAuthzEvents(); Preconditions.checkState(auditEvents.size() - numAuthzAuditEventsBefore <= 1); if (auditEvents.size() > numAuthzAuditEventsBefore) { // Recall that the same instance of RangerAuthorizationContext is passed to // createColumnMask() every time this method is called. Thus the same instance of // RangerBufferAuditHandler is provided for evalColumnMask() to log the event. // Since there will be exactly one event added to 'auditEvents' when there is a // corresponding column masking policy, i.e., accessResult.isMaskEnabled() // evaluates to true, we only need to process the last event on 'auditEvents'. auditHandler.getAuthzEvents().remove(auditEvents.size() - 1); } } @Override public String createColumnMask(User user, String dbName, String tableName, String columnName, AuthorizationContext rangerCtx) throws InternalException { RangerBufferAuditHandler auditHandler = (rangerCtx == null) ? null: ((RangerAuthorizationContext) rangerCtx).getAuditHandler(); int numAuthzAuditEventsBefore = (auditHandler == null) ? 0 : auditHandler.getAuthzEvents().size(); RangerAccessResult accessResult = evalColumnMask(user, dbName, tableName, columnName, auditHandler); if (!accessResult.isMaskEnabled() && auditHandler != null) { // No column masking policies, remove any possible stale audit events and // return the original column. removeStaleAudits(auditHandler, numAuthzAuditEventsBefore); return columnName; } String maskType = accessResult.getMaskType(); RangerServiceDef.RangerDataMaskTypeDef maskTypeDef = accessResult.getMaskTypeDef(); // The expression used to replace the original column. String maskedColumn = columnName; // The expression of the mask type. Column names are referenced by "{col}". // Transformer examples for the builtin mask types: // mask type transformer // MASK mask({col}) // MASK_SHOW_LAST_4 mask_show_last_n({col}, 4, 'x', 'x', 'x', -1, '1') // MASK_SHOW_FIRST_4 mask_show_first_n({col}, 4, 'x', 'x', 'x', -1, '1') // MASK_HASH mask_hash({col}) // MASK_DATE_SHOW_YEAR mask({col}, 'x', 'x', 'x', -1, '1', 1, 0, -1) String transformer = null; if (maskTypeDef != null) { transformer = maskTypeDef.getTransformer(); } if (StringUtils.equalsIgnoreCase(maskType, RangerPolicy.MASK_TYPE_NULL)) { maskedColumn = "NULL"; } else if (StringUtils.equalsIgnoreCase(maskType, RangerPolicy.MASK_TYPE_CUSTOM)) { String maskedValue = accessResult.getMaskedValue(); if (maskedValue == null) { maskedColumn = "NULL"; } else { maskedColumn = maskedValue.replace("{col}", columnName); } } else if (StringUtils.isNotEmpty(transformer)) { maskedColumn = transformer.replace("{col}", columnName); } LOG.trace( "dbName: {}, tableName: {}, column: {}, maskType: {}, columnTransformer: {}", dbName, tableName, columnName, maskType, maskedColumn); return maskedColumn; } @Override public String createRowFilter(User user, String dbName, String tableName, AuthorizationContext rangerCtx) throws InternalException { RangerBufferAuditHandler auditHandler = (rangerCtx == null) ? null : ((RangerAuthorizationContext) rangerCtx).getAuditHandler(); int numAuthzAuditEventsBefore = (auditHandler == null) ? 0 : auditHandler.getAuthzEvents().size(); RangerAccessResult accessResult = evalRowFilter(user, dbName, tableName, auditHandler); if (!accessResult.isRowFilterEnabled() && auditHandler != null) { // No row filtering policies, remove any possible stale audit events. removeStaleAudits(auditHandler, numAuthzAuditEventsBefore); return null; } String filter = accessResult.getFilterExpr(); LOG.trace("dbName: {}, tableName: {}, rowFilter: {}", dbName, tableName, filter); return filter; } @Override public void postAnalyze(AuthorizationContext authzCtx) { Preconditions.checkArgument(authzCtx instanceof RangerAuthorizationContext); ((RangerAuthorizationContext) authzCtx).stashTableMaskingAuditEvents(plugin_); } /** * Evaluate column masking policies on the given column and returns the result, * a RangerAccessResult contains the matched policy details and the masked column. * Note that Ranger will add an AuthzAuditEvent to auditHandler.getAuthzEvents() as * long as there exists a policy for the given column even though the policy does not * apply to 'user'. */ private RangerAccessResult evalColumnMask(User user, String dbName, String tableName, String columnName, RangerBufferAuditHandler auditHandler) throws InternalException { Preconditions.checkNotNull(user); RangerAccessResourceImpl resource = new RangerImpalaResourceBuilder() .database(dbName) .table(tableName) .column(columnName) .build(); RangerAccessRequestImpl req = new RangerAccessRequestImpl(); req.setResource(resource); req.setAccessType(SELECT_ACCESS_TYPE); req.setUser(user.getShortName()); req.setUserGroups(getUserGroups(user)); // The method evalDataMaskPolicies() only checks whether there is a corresponding // column masking policy on the Ranger server and thus does not check whether the // requesting user/group is granted the necessary privilege on the specified // resource. No AnalysisException or AuthorizationException will be thrown if the // requesting user/group does not possess the necessary privilege. return plugin_.evalDataMaskPolicies(req, auditHandler); } /** * Evaluate row filtering policies on the given table and returns the result, * a RangerAccessResult contains the matched policy details and the filter string. */ private RangerAccessResult evalRowFilter(User user, String dbName, String tableName, RangerBufferAuditHandler auditHandler) throws InternalException { Preconditions.checkNotNull(user); RangerAccessResourceImpl resource = new RangerImpalaResourceBuilder() .database(dbName) .table(tableName) .build(); RangerAccessRequestImpl req = new RangerAccessRequestImpl(); req.setResource(resource); req.setAccessType(SELECT_ACCESS_TYPE); req.setUser(user.getShortName()); req.setUserGroups(getUserGroups(user)); return plugin_.evalRowFilterPolicies(req, auditHandler); } /** * This method throws an {@link AuthorizationException} if row filter is enabled on the * given tables. This is used to prevent data leak when Hive has row filter enabled but * it's disabled in Impala. */ private void throwIfRowFilteringRequired(User user, String dbName, String tableName) throws InternalException, AuthorizationException { if (evalRowFilter(user, dbName, tableName, null).isRowFilterEnabled()) { throw new AuthorizationException(String.format( "Row filtering is disabled by --enable_row_filtering flag. Can't access " + "table %s.%s that has row filtering policy.", dbName, tableName)); } } @Override public Set<String> getUserGroups(User user) throws InternalException { Preconditions.checkNotNull(user); UserGroupInformation ugi; if (RuntimeEnv.INSTANCE.isTestEnv() || BackendConfig.INSTANCE.useCustomizedUserGroupsMapperForRanger()) { ugi = UserGroupInformation.createUserForTesting(user.getShortName(), new String[]{user.getShortName()}); } else { ugi = UserGroupInformation.createRemoteUser(user.getShortName()); } return new HashSet<>(ugi.getGroups()); } private boolean authorizeAny(RangerAuthorizationContext authzCtx, RangerAccessResourceImpl resource, Authorizable authorizable, User user, Privilege privilege) throws InternalException { boolean authorized = false; RangerBufferAuditHandler originalAuditHandler = authzCtx.getAuditHandler(); // Use a temporary audit handler instead of the original audit handler // so that we know all the audit events generated by the temporary audit // handler are contained to the given resource. // Recall that in some case, e.g., the DESCRIBE statement, 'originalAuditHandler' // could be null, resulting in 'tmpAuditHandler' being null as well. RangerBufferAuditHandler tmpAuditHandler = (originalAuditHandler == null || !authzCtx.getRetainAudits()) ? null : new RangerBufferAuditHandler(originalAuditHandler); for (Privilege impliedPrivilege: privilege.getImpliedPrivileges()) { if (authorizeResource(authzCtx, user, resource, authorizable, impliedPrivilege, tmpAuditHandler)) { authorized = true; break; } } // 'tmpAuditHandler' could be null if 'originalAuditHandler' is null or // authzCtx.getRetainAudits() is false. if (originalAuditHandler != null && tmpAuditHandler != null) { updateAuditEvents(tmpAuditHandler, originalAuditHandler, true /*any*/, privilege); } return authorized; } private boolean authorizeAll(RangerAuthorizationContext authzCtx, RangerAccessResourceImpl resource, Authorizable authorizable, User user, Privilege privilege) throws InternalException { boolean authorized = true; RangerBufferAuditHandler originalAuditHandler = authzCtx.getAuditHandler(); // Use a temporary audit handler instead of the original audit handler // so that we know all the audit events generated by the temporary audit // handler are contained to the given resource. // Recall that if 'min_privilege_set_for_show_stmts' is specified when the impalad's // are started, this method will be called with the RangerBufferAuditHandler in // 'authzCtx' being null for the SHOW DATABASES and SHOW TABLES statements. Refer to // BaseAuthorizationChecker#hasAccess(User user, PrivilegeRequest request) for // further details. RangerBufferAuditHandler tmpAuditHandler = (originalAuditHandler == null || !authzCtx.getRetainAudits()) ? null : new RangerBufferAuditHandler(originalAuditHandler); for (Privilege impliedPrivilege: privilege.getImpliedPrivileges()) { if (!authorizeResource(authzCtx, user, resource, authorizable, impliedPrivilege, tmpAuditHandler)) { authorized = false; break; } } // 'tmpAuditHandler' could be null if 'originalAuditHandler' is null or // authzCtx.getRetainAudits() is false. // Moreover, when 'resource' is associated with a storage handler URI, we pass // Privilege.RWSTORAGE to updateAuditEvents() since RWSTORAGE is the only valid // access type on a storage handler URI. Otherwise, we may update // 'originalAuditHandler' incorrectly since the audit log entries produced by Ranger // corresponding to a command like REFRESH/INVALIDATE METADATA has a entry with // access type being RWSTORAGE instead of REFRESH. if (originalAuditHandler != null && tmpAuditHandler != null) { updateAuditEvents(tmpAuditHandler, originalAuditHandler, false /*not any*/, resource.getKeys().contains(RangerImpalaResourceBuilder.STORAGE_TYPE) ? Privilege.RWSTORAGE : privilege); } return authorized; } /** * Updates the {@link AuthzAuditEvent} from the source to the destination * {@link RangerBufferAuditHandler} with the given privilege. * * For example we want to log: * VIEW_METADATA - Allowed * vs * INSERT - Denied, INSERT - Allowed. */ private static void updateAuditEvents(RangerBufferAuditHandler source, RangerBufferAuditHandler dest, boolean isAny, Privilege privilege) { // A custom audit event to log the actual privilege instead of the implied // privileges. AuthzAuditEvent newAuditEvent = null; for (AuthzAuditEvent auditEvent : source.getAuthzEvents()) { if (auditEvent.getAccessResult() == (isAny ? 1 : 0)) { newAuditEvent = auditEvent; break; // break if at least one is a success. } else { newAuditEvent = auditEvent; } } if (newAuditEvent != null) { newAuditEvent.setAccessType(privilege.name().toLowerCase()); dest.getAuthzEvents().add(newAuditEvent); } } private boolean authorizeResource(RangerAuthorizationContext authzCtx, User user, RangerAccessResourceImpl resource, Authorizable authorizable, Privilege privilege, RangerBufferAuditHandler auditHandler) throws InternalException { String accessType; // If 'resource' is associated with a storage handler URI, then 'accessType' can only // be RWSTORAGE since RWSTORAGE is the only valid privilege that could be applied on // a storage handler URI. if (resource.getKeys().contains(RangerImpalaResourceBuilder.STORAGE_TYPE)) { accessType = Privilege.RWSTORAGE.name().toLowerCase(); } else { if (privilege == Privilege.ANY) { accessType = RangerPolicyEngine.ANY_ACCESS; } else if (privilege == Privilege.INSERT) { // Ranger plugin for Hive considers INSERT to be UPDATE. accessType = UPDATE_ACCESS_TYPE; } else { accessType = privilege.name().toLowerCase(); } } RangerAccessRequestImpl request = new RangerAccessRequestImpl(); request.setResource(resource); request.setAccessType(accessType); request.setUser(user.getShortName()); request.setUserGroups(getUserGroups(user)); request.setClusterName(plugin_.getClusterName()); if (authzCtx.getSessionState() != null) { request.setClientIPAddress( authzCtx.getSessionState().getNetwork_address().getHostname()); } RangerAccessResult authorized = plugin_.isAccessAllowed(request, auditHandler); if (authorized == null || !authorized.getIsAllowed()) return false; // We are done if don't need to block updates on tables that have column-masking or // row-filtering policies. if (!plugin_.blockUpdateIfTableMaskSpecified() || !privilege.impliesUpdate() || (authorizable.getType() != Type.TABLE && authorizable.getType() != Type.COLUMN)) { return true; } return authorizeByTableMasking(request, user, authorizable, authorized, privilege, auditHandler); } /** * Blocks the update request if any row-filtering or column masking policy exists on the * resource(table/column). Appends a deny audit if any exists. * Returns true if the request is authorized. */ private boolean authorizeByTableMasking(RangerAccessRequestImpl request, User user, Authorizable authorizable, RangerAccessResult accessResult, Privilege privilege, RangerBufferAuditHandler auditHandler) throws InternalException { Preconditions.checkNotNull(accessResult, "accessResult is null!"); Preconditions.checkState(accessResult.getIsAllowed(), "update should be allowed before checking this"); String originalAccessType = request.getAccessType(); // Row-filtering/Column-masking policies are defined only for SELECT requests. request.setAccessType(SELECT_ACCESS_TYPE); // Check if row filtering is enabled for the table/view. if (authorizable.getType() == Type.TABLE) { RangerAccessResult rowFilterResult = plugin_.evalRowFilterPolicies( request, /*resultProcessor*/null); if (rowFilterResult != null && rowFilterResult.isRowFilterEnabled()) { LOG.trace("Deny {} on {} due to row filtering policy {}", privilege, authorizable.getName(), rowFilterResult.getPolicyId()); accessResult.setIsAllowed(false); accessResult.setPolicyId(rowFilterResult.getPolicyId()); accessResult.setReason("User does not have access to all rows of the table"); } else { LOG.trace("No row filtering policy found on {}.", authorizable.getName()); } } // Check if masking is enabled for any column in the table/view. if (accessResult.getIsAllowed()) { List<String> columns; if (authorizable.getType() == Type.TABLE) { // Check all columns. columns = ((AuthorizableTable) authorizable).getColumns(); LOG.trace("Checking mask policies on {} columns of table {}", columns.size(), authorizable.getFullTableName()); } else { columns = Lists.newArrayList(authorizable.getColumnName()); } for (String column : columns) { RangerAccessResult columnMaskResult = evalColumnMask(user, authorizable.getDbName(), authorizable.getTableName(), column, /*auditHandler*/null); if (columnMaskResult != null && columnMaskResult.isMaskEnabled()) { LOG.trace("Deny {} on {} due to column masking policy {}", privilege, authorizable.getName(), columnMaskResult.getPolicyId()); accessResult.setIsAllowed(false); accessResult.setPolicyId(columnMaskResult.getPolicyId()); accessResult.setReason("User does not have access to unmasked column values"); break; } else { LOG.trace("No column masking policy found on column {} of {}.", column, authorizable.getFullTableName()); } } } // Set back the original access type. The request object is still referenced by the // access result. request.setAccessType(originalAccessType); // Only add deny audits. if (!accessResult.getIsAllowed() && auditHandler != null) { auditHandler.processResult(accessResult); } return accessResult.getIsAllowed(); } @VisibleForTesting public RangerImpalaPlugin getRangerImpalaPlugin() { return plugin_; } @Override public boolean roleExists(String roleName) { return RangerUtil.roleExists(plugin_, roleName); } }
googleapis/google-cloud-java
36,592
java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/CreateGrpcRouteRequest.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/networkservices/v1/grpc_route.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.networkservices.v1; /** * * * <pre> * Request used by the CreateGrpcRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateGrpcRouteRequest} */ public final class CreateGrpcRouteRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.CreateGrpcRouteRequest) CreateGrpcRouteRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateGrpcRouteRequest.newBuilder() to construct. private CreateGrpcRouteRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateGrpcRouteRequest() { parent_ = ""; grpcRouteId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateGrpcRouteRequest(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.GrpcRouteProto .internal_static_google_cloud_networkservices_v1_CreateGrpcRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.GrpcRouteProto .internal_static_google_cloud_networkservices_v1_CreateGrpcRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.class, com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.Builder.class); } private int bitField0_; public static final int PARENT_FIELD_NUMBER = 1; @SuppressWarnings("serial") private volatile java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GRPC_ROUTE_ID_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object grpcRouteId_ = ""; /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The grpcRouteId. */ @java.lang.Override public java.lang.String getGrpcRouteId() { java.lang.Object ref = grpcRouteId_; 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(); grpcRouteId_ = s; return s; } } /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for grpcRouteId. */ @java.lang.Override public com.google.protobuf.ByteString getGrpcRouteIdBytes() { java.lang.Object ref = grpcRouteId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); grpcRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GRPC_ROUTE_FIELD_NUMBER = 3; private com.google.cloud.networkservices.v1.GrpcRoute grpcRoute_; /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the grpcRoute field is set. */ @java.lang.Override public boolean hasGrpcRoute() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The grpcRoute. */ @java.lang.Override public com.google.cloud.networkservices.v1.GrpcRoute getGrpcRoute() { return grpcRoute_ == null ? com.google.cloud.networkservices.v1.GrpcRoute.getDefaultInstance() : grpcRoute_; } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.cloud.networkservices.v1.GrpcRouteOrBuilder getGrpcRouteOrBuilder() { return grpcRoute_ == null ? com.google.cloud.networkservices.v1.GrpcRoute.getDefaultInstance() : grpcRoute_; } 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(grpcRouteId_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, grpcRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { output.writeMessage(3, getGrpcRoute()); } 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(grpcRouteId_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, grpcRouteId_); } if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getGrpcRoute()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.networkservices.v1.CreateGrpcRouteRequest)) { return super.equals(obj); } com.google.cloud.networkservices.v1.CreateGrpcRouteRequest other = (com.google.cloud.networkservices.v1.CreateGrpcRouteRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getGrpcRouteId().equals(other.getGrpcRouteId())) return false; if (hasGrpcRoute() != other.hasGrpcRoute()) return false; if (hasGrpcRoute()) { if (!getGrpcRoute().equals(other.getGrpcRoute())) 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) + GRPC_ROUTE_ID_FIELD_NUMBER; hash = (53 * hash) + getGrpcRouteId().hashCode(); if (hasGrpcRoute()) { hash = (37 * hash) + GRPC_ROUTE_FIELD_NUMBER; hash = (53 * hash) + getGrpcRoute().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.networkservices.v1.CreateGrpcRouteRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request used by the CreateGrpcRoute method. * </pre> * * Protobuf type {@code google.cloud.networkservices.v1.CreateGrpcRouteRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.CreateGrpcRouteRequest) com.google.cloud.networkservices.v1.CreateGrpcRouteRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.networkservices.v1.GrpcRouteProto .internal_static_google_cloud_networkservices_v1_CreateGrpcRouteRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.networkservices.v1.GrpcRouteProto .internal_static_google_cloud_networkservices_v1_CreateGrpcRouteRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.class, com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.Builder.class); } // Construct using com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { getGrpcRouteFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; parent_ = ""; grpcRouteId_ = ""; grpcRoute_ = null; if (grpcRouteBuilder_ != null) { grpcRouteBuilder_.dispose(); grpcRouteBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.networkservices.v1.GrpcRouteProto .internal_static_google_cloud_networkservices_v1_CreateGrpcRouteRequest_descriptor; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateGrpcRouteRequest getDefaultInstanceForType() { return com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.getDefaultInstance(); } @java.lang.Override public com.google.cloud.networkservices.v1.CreateGrpcRouteRequest build() { com.google.cloud.networkservices.v1.CreateGrpcRouteRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateGrpcRouteRequest buildPartial() { com.google.cloud.networkservices.v1.CreateGrpcRouteRequest result = new com.google.cloud.networkservices.v1.CreateGrpcRouteRequest(this); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartial0(com.google.cloud.networkservices.v1.CreateGrpcRouteRequest result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000001) != 0)) { result.parent_ = parent_; } if (((from_bitField0_ & 0x00000002) != 0)) { result.grpcRouteId_ = grpcRouteId_; } int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000004) != 0)) { result.grpcRoute_ = grpcRouteBuilder_ == null ? grpcRoute_ : grpcRouteBuilder_.build(); to_bitField0_ |= 0x00000001; } result.bitField0_ |= to_bitField0_; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.networkservices.v1.CreateGrpcRouteRequest) { return mergeFrom((com.google.cloud.networkservices.v1.CreateGrpcRouteRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.networkservices.v1.CreateGrpcRouteRequest other) { if (other == com.google.cloud.networkservices.v1.CreateGrpcRouteRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; bitField0_ |= 0x00000001; onChanged(); } if (!other.getGrpcRouteId().isEmpty()) { grpcRouteId_ = other.grpcRouteId_; bitField0_ |= 0x00000002; onChanged(); } if (other.hasGrpcRoute()) { mergeGrpcRoute(other.getGrpcRoute()); } 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: { grpcRouteId_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 case 26: { input.readMessage(getGrpcRouteFieldBuilder().getBuilder(), extensionRegistry); bitField0_ |= 0x00000004; break; } // case 26 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.lang.Object parent_ = ""; /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Required. The parent resource of the GrpcRoute. Must be in the * format `projects/&#42;&#47;locations/global`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; bitField0_ |= 0x00000001; onChanged(); return this; } private java.lang.Object grpcRouteId_ = ""; /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The grpcRouteId. */ public java.lang.String getGrpcRouteId() { java.lang.Object ref = grpcRouteId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); grpcRouteId_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for grpcRouteId. */ public com.google.protobuf.ByteString getGrpcRouteIdBytes() { java.lang.Object ref = grpcRouteId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); grpcRouteId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The grpcRouteId to set. * @return This builder for chaining. */ public Builder setGrpcRouteId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } grpcRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearGrpcRouteId() { grpcRouteId_ = getDefaultInstance().getGrpcRouteId(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); return this; } /** * * * <pre> * Required. Short name of the GrpcRoute resource to be created. * </pre> * * <code>string grpc_route_id = 2 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for grpcRouteId to set. * @return This builder for chaining. */ public Builder setGrpcRouteIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); grpcRouteId_ = value; bitField0_ |= 0x00000002; onChanged(); return this; } private com.google.cloud.networkservices.v1.GrpcRoute grpcRoute_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.GrpcRoute, com.google.cloud.networkservices.v1.GrpcRoute.Builder, com.google.cloud.networkservices.v1.GrpcRouteOrBuilder> grpcRouteBuilder_; /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the grpcRoute field is set. */ public boolean hasGrpcRoute() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The grpcRoute. */ public com.google.cloud.networkservices.v1.GrpcRoute getGrpcRoute() { if (grpcRouteBuilder_ == null) { return grpcRoute_ == null ? com.google.cloud.networkservices.v1.GrpcRoute.getDefaultInstance() : grpcRoute_; } else { return grpcRouteBuilder_.getMessage(); } } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setGrpcRoute(com.google.cloud.networkservices.v1.GrpcRoute value) { if (grpcRouteBuilder_ == null) { if (value == null) { throw new NullPointerException(); } grpcRoute_ = value; } else { grpcRouteBuilder_.setMessage(value); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setGrpcRoute( com.google.cloud.networkservices.v1.GrpcRoute.Builder builderForValue) { if (grpcRouteBuilder_ == null) { grpcRoute_ = builderForValue.build(); } else { grpcRouteBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; onChanged(); return this; } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeGrpcRoute(com.google.cloud.networkservices.v1.GrpcRoute value) { if (grpcRouteBuilder_ == null) { if (((bitField0_ & 0x00000004) != 0) && grpcRoute_ != null && grpcRoute_ != com.google.cloud.networkservices.v1.GrpcRoute.getDefaultInstance()) { getGrpcRouteBuilder().mergeFrom(value); } else { grpcRoute_ = value; } } else { grpcRouteBuilder_.mergeFrom(value); } if (grpcRoute_ != null) { bitField0_ |= 0x00000004; onChanged(); } return this; } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearGrpcRoute() { bitField0_ = (bitField0_ & ~0x00000004); grpcRoute_ = null; if (grpcRouteBuilder_ != null) { grpcRouteBuilder_.dispose(); grpcRouteBuilder_ = null; } onChanged(); return this; } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.GrpcRoute.Builder getGrpcRouteBuilder() { bitField0_ |= 0x00000004; onChanged(); return getGrpcRouteFieldBuilder().getBuilder(); } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.cloud.networkservices.v1.GrpcRouteOrBuilder getGrpcRouteOrBuilder() { if (grpcRouteBuilder_ != null) { return grpcRouteBuilder_.getMessageOrBuilder(); } else { return grpcRoute_ == null ? com.google.cloud.networkservices.v1.GrpcRoute.getDefaultInstance() : grpcRoute_; } } /** * * * <pre> * Required. GrpcRoute resource to be created. * </pre> * * <code> * .google.cloud.networkservices.v1.GrpcRoute grpc_route = 3 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.GrpcRoute, com.google.cloud.networkservices.v1.GrpcRoute.Builder, com.google.cloud.networkservices.v1.GrpcRouteOrBuilder> getGrpcRouteFieldBuilder() { if (grpcRouteBuilder_ == null) { grpcRouteBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.networkservices.v1.GrpcRoute, com.google.cloud.networkservices.v1.GrpcRoute.Builder, com.google.cloud.networkservices.v1.GrpcRouteOrBuilder>( getGrpcRoute(), getParentForChildren(), isClean()); grpcRoute_ = null; } return grpcRouteBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.networkservices.v1.CreateGrpcRouteRequest) } // @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.CreateGrpcRouteRequest) private static final com.google.cloud.networkservices.v1.CreateGrpcRouteRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.CreateGrpcRouteRequest(); } public static com.google.cloud.networkservices.v1.CreateGrpcRouteRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateGrpcRouteRequest> PARSER = new com.google.protobuf.AbstractParser<CreateGrpcRouteRequest>() { @java.lang.Override public CreateGrpcRouteRequest 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<CreateGrpcRouteRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateGrpcRouteRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.networkservices.v1.CreateGrpcRouteRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
openjdk/skara
36,847
bots/pr/src/test/java/org/openjdk/skara/bots/pr/ReviewersTests.java
/* * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.openjdk.skara.bots.pr; import org.openjdk.skara.forge.Review; import org.openjdk.skara.test.*; import org.junit.jupiter.api.*; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import static org.junit.jupiter.api.Assertions.*; import static org.openjdk.skara.bots.pr.PullRequestAsserts.assertLastCommentContains; import static org.openjdk.skara.jcheck.ReviewersConfiguration.BYLAWS_URL; public class ReviewersTests { private static final String REVIEWERS_COMMENT_TEMPLATE = "The total number of required reviews for this PR " + "(including the jcheck configuration and the last /reviewers command) is now set to %d (with at least %s)."; private static final String ZERO_REVIEWER_COMMENT = "The total number of required reviews for this PR " + "(including the jcheck configuration and the last /reviewers command) is now set to 0."; private static final String REVIEW_PROGRESS_TEMPLATE = "Change must be properly reviewed (%d review%s required, with at least %s)"; private static final String ZERO_REVIEW_PROGRESS = "Change must be properly reviewed (no review required)"; @Test void simple(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var integrator = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(integrator.forge().currentUser().id()) .addCommitter(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var reviewerPr = (TestPullRequest)integrator.pullRequest(pr.id()); // No arguments reviewerPr.addComment("/reviewers"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a help message assertLastCommentContains(reviewerPr,"is the number of required reviewers"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Invalid syntax reviewerPr.addComment("/reviewers two"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a help message assertLastCommentContains(reviewerPr,"is the number of required reviewers"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Too many reviewerPr.addComment("/reviewers 7001"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"Cannot increase the required number of reviewers above 10 (requested: 7001)"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Too few reviewerPr.addComment("/reviewers -3"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"Cannot decrease the required number of reviewers below 0 (requested: -3)"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Unknown role reviewerPr.addComment("/reviewers 2 penguins"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"Unknown role `penguins` specified"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Set the number reviewerPr.addComment("/reviewers 2"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a success message assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 0, 1, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // Set 2 of role committers reviewerPr.addComment("/reviewers 2 committer"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a success message assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 1, 0, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 1, 0, 0))); // Set 2 of role reviewers reviewerPr.addComment("/reviewers 2 reviewer"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a success message assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 2, 0, 0, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 2, 0, 0, 0))); // Approve it as another user reviewerPr.addReview(Review.Verdict.APPROVED, "Approved"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The PR should not yet be considered as ready for review var updatedPr = author.pullRequest(pr.id()); assertFalse(updatedPr.labelNames().contains("ready")); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 2, 0, 0, 0))); // Now reduce the number of required reviewers reviewerPr.addComment("/reviewers 1"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The PR should now be considered as ready for review updatedPr = author.pullRequest(pr.id()); assertTrue(updatedPr.labelNames().contains("ready")); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Now request that the lead reviews reviewerPr.addComment("/reviewers 1 lead"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr, getReviewersExpectedComment(1, 0, 0, 0, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(1, 0, 0, 0, 0))); // The PR should no longer be considered as ready for review updatedPr = author.pullRequest(pr.id()); assertFalse(updatedPr.labelNames().contains("ready")); // Drop the extra requirement that it should be the lead reviewerPr.addComment("/reviewers 1"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 0, 0, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // The PR should now be considered as ready for review yet again updatedPr = author.pullRequest(pr.id()); assertTrue(updatedPr.labelNames().contains("ready")); } } @Test void noIntegration(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var integrator = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(integrator.forge().currentUser().id()) .addCommitter(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var reviewerPr = (TestPullRequest) integrator.pullRequest(pr.id()); // Set the number reviewerPr.addComment("/reviewers 2"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a success message assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 0, 1, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // Approve it as another user reviewerPr.addReview(Review.Verdict.APPROVED, "Approved"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // It should not be possible to integrate yet pr.addComment("/integrate"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"pull request has not yet been marked as ready for integration"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // Relax the requirement reviewerPr.addComment("/reviewers 1"); TestBotRunner.runPeriodicItems(prBot); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // It should now work fine pr.addComment("/integrate"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"Pushed as commit"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); } } @Test void noSponsoring(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var integrator = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(integrator.forge().currentUser().id()) .addAuthor(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var reviewerPr = (TestPullRequest)integrator.pullRequest(pr.id()); // Approve it as another user reviewerPr.addReview(Review.Verdict.APPROVED, "Approved"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Flag it as ready for integration pr.addComment("/integrate"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"now ready to be sponsored"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Set the number reviewerPr.addComment("/reviewers 2"); TestBotRunner.runPeriodicItems(prBot); // The bot should reply with a success message assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 0, 1, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // It should not be possible to sponsor reviewerPr.addComment("/sponsor"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"PR has not yet been marked as ready for integration"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // Relax the requirement reviewerPr.addComment("/reviewers 1"); TestBotRunner.runPeriodicItems(prBot); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // It should now work fine reviewerPr.addComment("/sponsor"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr,"Pushed as commit"); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); } } @Test void prAuthorShouldBeAllowedToExecute(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addCommitter(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var authorPR = (TestPullRequest)author.pullRequest(pr.id()); // The author deems that two reviewers are required authorPR.addComment("/reviewers 2"); // The bot should reply with a success message TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(authorPR, getReviewersExpectedComment(0, 1, 0, 1, 0)); assertTrue(authorPR.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); } } @Test void prAuthorShouldNotBeAllowedToDecrease(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var integrator = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(integrator.forge().currentUser().id()) .addAuthor(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var authorPR = (TestPullRequest)author.pullRequest(pr.id()); // The author deems that two reviewers are required authorPR.addComment("/reviewers 2"); // The bot should reply with a success message TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(authorPR, getReviewersExpectedComment(0, 1, 0, 1, 0)); assertTrue(authorPR.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // The author should not be allowed to decrease even its own /reviewers command authorPR.addComment("/reviewers 1"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(authorPR, "Only [Reviewers](https://openjdk.org/bylaws#reviewer) " + "are allowed to decrease the number of required reviewers."); assertTrue(authorPR.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); // Reviewer should be allowed to decrease var reviewerPr = (TestPullRequest)integrator.pullRequest(pr.id()); reviewerPr.addComment("/reviewers 1"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 0, 0, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // The author should not be allowed to lower the role of the reviewers authorPR.addComment("/reviewers 1 contributors"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(authorPR, "Only [Reviewers](https://openjdk.org/bylaws#reviewer) " + "are allowed to lower the role for additional reviewers."); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); // Reviewer should be allowed to lower the role of the reviewers reviewerPr.addComment("/reviewers 1 contributors"); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr, getReviewersExpectedComment(0, 1, 0, 0, 0)); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 0, 0))); } } @Test void commandInPRBody(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addCommitter(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request", List.of("/reviewers 2")); TestBotRunner.runPeriodicItems(prBot); var authorPR = (TestPullRequest)author.pullRequest(pr.id()); assertLastCommentContains(authorPR, getReviewersExpectedComment(0, 1, 0, 1, 0)); assertTrue(authorPR.store().body().contains(getReviewersExpectedProgress(0, 1, 0, 1, 0))); } } @Test void complexCombinedConfigAndCommand(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var integrator = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(integrator.forge().currentUser().id()) .addCommitter(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Change the jcheck configuration var confPath = localRepo.root().resolve(".jcheck/conf"); var defaultConf = Files.readString(confPath); var newConf = defaultConf.replace("reviewers=1", """ lead=1 reviewers=1 committers=1 authors=1 contributors=1 ignore=duke """); Files.writeString(confPath, newConf); localRepo.add(confPath); var confHash = localRepo.commit("Change conf", "duke", "duke@openjdk.org"); localRepo.push(confHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var reviewerPr = (TestPullRequest)integrator.pullRequest(pr.id()); // test role contributor for (int i = 1; i <= 10; i++) { var contributorNum = (i < 6) ? 1 : i - 4; verifyReviewersCommentAndProgress(reviewerPr, prBot, "/reviewers " + i + " contributor", getReviewersExpectedComment(1, 1, 1, 1, contributorNum), getReviewersExpectedProgress(1, 1, 1, 1, contributorNum)); } // test role author for (int i = 1; i <= 10; i++) { var contributorNum = (i < 5) ? 1 : 0; var authorNum = (i < 5) ? 1 : i - 3; verifyReviewersCommentAndProgress(reviewerPr, prBot, "/reviewers " + i + " author", getReviewersExpectedComment(1, 1, 1, authorNum, contributorNum), getReviewersExpectedProgress(1, 1, 1, authorNum, contributorNum)); } // test role committer for (int i = 1; i <= 10; i++) { var contributorNum = (i < 4) ? 1 : 0; var authorNum = (i < 5) ? 1 : 0; var committerNum = (i < 4) ? 1 : i - 2; verifyReviewersCommentAndProgress(reviewerPr, prBot, "/reviewers " + i + " committer", getReviewersExpectedComment(1, 1, committerNum, authorNum, contributorNum), getReviewersExpectedProgress(1, 1, committerNum, authorNum, contributorNum)); } // test role reviewer for (int i = 1; i <= 10; i++) { var contributorNum = (i < 3) ? 1 : 0; var authorNum = (i < 4) ? 1 : 0; var committerNum = (i < 5) ? 1 : 0; var reviewerNum = (i < 3) ? 1 : i - 1; verifyReviewersCommentAndProgress(reviewerPr, prBot, "/reviewers " + i + " reviewer", getReviewersExpectedComment(1, reviewerNum, committerNum, authorNum, contributorNum), getReviewersExpectedProgress(1, reviewerNum, committerNum, authorNum, contributorNum)); } // test role lead verifyReviewersCommentAndProgress(reviewerPr, prBot, "/reviewers 1 lead", getReviewersExpectedComment(1, 1, 1, 1, 1), getReviewersExpectedProgress(1, 1, 1, 1, 1)); } } private void verifyReviewersCommentAndProgress(TestPullRequest reviewerPr, PullRequestBot prBot, String command, String expectedComment, String expectedProgress) throws IOException { reviewerPr.addComment(command); TestBotRunner.runPeriodicItems(prBot); assertLastCommentContains(reviewerPr, expectedComment); assertTrue(reviewerPr.store().body().contains(expectedProgress)); } private String getReviewersExpectedComment(int leadNum, int reviewerNum, int committerNum, int authorNum, int contributorNum) { return constructFromTemplate(REVIEWERS_COMMENT_TEMPLATE, ZERO_REVIEWER_COMMENT, leadNum, reviewerNum, committerNum, authorNum, contributorNum); } private String getReviewersExpectedProgress(int leadNum, int reviewerNum, int committerNum, int authorNum, int contributorNum) { return constructFromTemplate(REVIEW_PROGRESS_TEMPLATE, ZERO_REVIEW_PROGRESS, leadNum, reviewerNum, committerNum, authorNum, contributorNum); } private String constructFromTemplate(String template, String zeroTemplate, int leadNum, int reviewerNum, int committerNum, int authorNum, int contributorNum) { var totalNum = leadNum + reviewerNum + committerNum + authorNum + contributorNum; if (totalNum == 0) { return zeroTemplate; } var requireList = new ArrayList<String>(); var reviewRequirementMap = new LinkedHashMap<String, Integer>(); reviewRequirementMap.put("[Lead%s](%s#project-lead)", leadNum); reviewRequirementMap.put("[Reviewer%s](%s#reviewer)", reviewerNum); reviewRequirementMap.put("[Committer%s](%s#committer)", committerNum); reviewRequirementMap.put("[Author%s](%s#author)", authorNum); reviewRequirementMap.put("[Contributor%s](%s#contributor)", contributorNum); for (var reviewRequirement : reviewRequirementMap.entrySet()) { var requirementNum = reviewRequirement.getValue(); if (requirementNum > 0) { requireList.add(requirementNum + " " + String.format(reviewRequirement.getKey(), requirementNum > 1 ? "s" : "", BYLAWS_URL)); } } if (template.equals(REVIEW_PROGRESS_TEMPLATE)) { return String.format(template, totalNum, totalNum > 1 ? "s" : "", String.join(", ", requireList)); } else { return String.format(template, totalNum, String.join(", ", requireList)); } } @Test void testZeroReviewer(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var reviewer = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(reviewer.forge().currentUser().id()) .addCommitter(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Change the jcheck configuration var confPath = localRepo.root().resolve(".jcheck/conf"); var defaultConf = Files.readString(confPath); var newConf = defaultConf.replace("reviewers=1", """ lead=0 reviewers=0 committers=0 authors=0 contributors=0 ignore=duke """); Files.writeString(confPath, newConf); localRepo.add(confPath); var confHash = localRepo.commit("Change conf", "duke", "duke@openjdk.org"); localRepo.push(confHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request", List.of("")); var reviewerPr = (TestPullRequest)reviewer.pullRequest(pr.id()); TestBotRunner.runPeriodicItems(prBot); var authorPR = author.pullRequest(pr.id()); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 0, 0, 0, 0))); authorPR.addComment("/reviewers 2 reviewer"); TestBotRunner.runPeriodicItems(prBot); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 2, 0, 0, 0))); reviewerPr.addComment("/reviewers 0"); TestBotRunner.runPeriodicItems(prBot); assertTrue(reviewerPr.store().body().contains(getReviewersExpectedProgress(0, 0, 0, 0, 0))); } } @Test void testReviewCommentsAfterApprovedReview(TestInfo testInfo) throws IOException { try (var credentials = new HostCredentials(testInfo); var tempFolder = new TemporaryDirectory()) { var author = credentials.getHostedRepository(); var integrator = credentials.getHostedRepository(); var bot = credentials.getHostedRepository(); var censusBuilder = credentials.getCensusBuilder() .addReviewer(integrator.forge().currentUser().id()) .addAuthor(author.forge().currentUser().id()); var prBot = PullRequestBot.newBuilder().repo(bot).censusRepo(censusBuilder.build()).build(); // Populate the projects repository var localRepoFolder = tempFolder.path().resolve("localrepo"); var localRepo = CheckableRepository.init(localRepoFolder, author.repositoryType()); var masterHash = localRepo.resolve("master").orElseThrow(); assertFalse(CheckableRepository.hasBeenEdited(localRepo)); localRepo.push(masterHash, author.authenticatedUrl(), "master", true); // Make a change with a corresponding PR var editHash = CheckableRepository.appendAndCommit(localRepo); localRepo.push(editHash, author.authenticatedUrl(), "edit", true); var pr = credentials.createPullRequest(author, "master", "edit", "123: This is a pull request"); var reviewerPr = integrator.pullRequest(pr.id()); // Approve it as another user reviewerPr.addReview(Review.Verdict.APPROVED, "Approved"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The pr should contain 'Ready' label assertTrue(pr.store().labelNames().contains("ready")); // Add a review comment reviewerPr.addReview(Review.Verdict.NONE, "Just a comment1"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The pr should still contain 'Ready' label assertTrue(pr.store().labelNames().contains("ready")); // Add a review comment reviewerPr.addReview(Review.Verdict.NONE, "Just a comment2"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The pr should still contain 'Ready' label assertTrue(pr.store().labelNames().contains("ready")); // Disapprove this pr reviewerPr.addReview(Review.Verdict.DISAPPROVED, "Disapproved"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The pr should not contain 'Ready' label assertFalse(pr.store().labelNames().contains("ready")); // Add a review comment reviewerPr.addReview(Review.Verdict.NONE, "Just a comment3"); TestBotRunner.runPeriodicItems(prBot); TestBotRunner.runPeriodicItems(prBot); // The pr should still not contain 'Ready' label assertFalse(pr.store().labelNames().contains("ready")); } } }
google/j2objc
36,769
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/stream/IntStream.java
/* * Copyright (c) 2012, 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.util.stream; import java.util.Arrays; import java.util.IntSummaryStatistics; import java.util.Objects; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.function.IntBinaryOperator; import java.util.function.IntConsumer; import java.util.function.IntFunction; import java.util.function.IntPredicate; import java.util.function.IntSupplier; import java.util.function.IntToDoubleFunction; import java.util.function.IntToLongFunction; import java.util.function.IntUnaryOperator; import java.util.function.ObjIntConsumer; import java.util.function.Supplier; /** * A sequence of primitive int-valued elements supporting sequential and parallel * aggregate operations. This is the {@code int} primitive specialization of * {@link Stream}. * * <p>The following example illustrates an aggregate operation using * {@link Stream} and {@link IntStream}, computing the sum of the weights of the * red widgets: * * <pre>{@code * int sum = widgets.stream() * .filter(w -> w.getColor() == RED) * .mapToInt(w -> w.getWeight()) * .sum(); * }</pre> * * See the class documentation for {@link Stream} and the package documentation * for <a href="package-summary.html">java.util.stream</a> for additional * specification of streams, stream operations, stream pipelines, and * parallelism. * * @since 1.8 * @see Stream * @see <a href="package-summary.html">java.util.stream</a> */ public interface IntStream extends BaseStream<Integer, IntStream> { /** * Returns a stream consisting of the elements of this stream that match * the given predicate. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to each element to determine if it * should be included * @return the new stream */ IntStream filter(IntPredicate predicate); /** * Returns a stream consisting of the results of applying the given * function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ IntStream map(IntUnaryOperator mapper); /** * Returns an object-valued {@code Stream} consisting of the results of * applying the given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps"> * intermediate operation</a>. * * @param <U> the element type of the new stream * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ <U> Stream<U> mapToObj(IntFunction<? extends U> mapper); /** * Returns a {@code LongStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ LongStream mapToLong(IntToLongFunction mapper); /** * Returns a {@code DoubleStream} consisting of the results of applying the * given function to the elements of this stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element * @return the new stream */ DoubleStream mapToDouble(IntToDoubleFunction mapper); /** * Returns a stream consisting of the results of replacing each element of * this stream with the contents of a mapped stream produced by applying * the provided mapping function to each element. Each mapped stream is * {@link java.util.stream.BaseStream#close() closed} after its contents * have been placed into this stream. (If a mapped stream is {@code null} * an empty stream is used, instead.) * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function to apply to each element which produces an * {@code IntStream} of new values * @return the new stream * @see Stream#flatMap(Function) */ IntStream flatMap(IntFunction<? extends IntStream> mapper); /** * Returns a stream consisting of the distinct elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the new stream */ IntStream distinct(); /** * Returns a stream consisting of the elements of this stream in sorted * order. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @return the new stream */ IntStream sorted(); /** * Returns a stream consisting of the elements of this stream, additionally * performing the provided action on each element as elements are consumed * from the resulting stream. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * <p>For parallel stream pipelines, the action may be called at * whatever time and in whatever thread the element is made available by the * upstream operation. If the action modifies shared state, * it is responsible for providing the required synchronization. * * @apiNote This method exists mainly to support debugging, where you want * to see the elements as they flow past a certain point in a pipeline: * <pre>{@code * IntStream.of(1, 2, 3, 4) * .filter(e -> e > 2) * .peek(e -> System.out.println("Filtered value: " + e)) * .map(e -> e * e) * .peek(e -> System.out.println("Mapped value: " + e)) * .sum(); * }</pre> * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements as * they are consumed from the stream * @return the new stream */ IntStream peek(IntConsumer action); /** * Returns a stream consisting of the elements of this stream, truncated * to be no longer than {@code maxSize} in length. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * stateful intermediate operation</a>. * * @apiNote * While {@code limit()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code maxSize}, since {@code limit(n)} * is constrained to return not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(IntSupplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code limit()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code limit()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. * * @param maxSize the number of elements the stream should be limited to * @return the new stream * @throws IllegalArgumentException if {@code maxSize} is negative */ IntStream limit(long maxSize); /** * Returns a stream consisting of the remaining elements of this stream * after discarding the first {@code n} elements of the stream. * If this stream contains fewer than {@code n} elements then an * empty stream will be returned. * * <p>This is a <a href="package-summary.html#StreamOps">stateful * intermediate operation</a>. * * @apiNote * While {@code skip()} is generally a cheap operation on sequential * stream pipelines, it can be quite expensive on ordered parallel pipelines, * especially for large values of {@code n}, since {@code skip(n)} * is constrained to skip not just any <em>n</em> elements, but the * <em>first n</em> elements in the encounter order. Using an unordered * stream source (such as {@link #generate(IntSupplier)}) or removing the * ordering constraint with {@link #unordered()} may result in significant * speedups of {@code skip()} in parallel pipelines, if the semantics of * your situation permit. If consistency with encounter order is required, * and you are experiencing poor performance or memory utilization with * {@code skip()} in parallel pipelines, switching to sequential execution * with {@link #sequential()} may improve performance. * * @param n the number of leading elements to skip * @return the new stream * @throws IllegalArgumentException if {@code n} is negative */ IntStream skip(long n); /** * Performs an action for each element of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * <p>For parallel stream pipelines, this operation does <em>not</em> * guarantee to respect the encounter order of the stream, as doing so * would sacrifice the benefit of parallelism. For any given element, the * action may be performed at whatever time and in whatever thread the * library chooses. If the action accesses shared state, it is * responsible for providing the required synchronization. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements */ void forEach(IntConsumer action); /** * Performs an action for each element of this stream, guaranteeing that * each element is processed in encounter order for streams that have a * defined encounter order. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param action a <a href="package-summary.html#NonInterference"> * non-interfering</a> action to perform on the elements * @see #forEach(IntConsumer) */ void forEachOrdered(IntConsumer action); /** * Returns an array containing the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an array containing the elements of this stream */ int[] toArray(); /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using the provided identity value and an * <a href="package-summary.html#Associativity">associative</a> * accumulation function, and returns the reduced value. This is equivalent * to: * <pre>{@code * int result = identity; * for (int element : this stream) * result = accumulator.applyAsInt(result, element) * return result; * }</pre> * * but is not constrained to execute sequentially. * * <p>The {@code identity} value must be an identity for the accumulator * function. This means that for all {@code x}, * {@code accumulator.apply(identity, x)} is equal to {@code x}. * The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @apiNote Sum, min, max, and average are all special cases of reduction. * Summing a stream of numbers can be expressed as: * * <pre>{@code * int sum = integers.reduce(0, (a, b) -> a+b); * }</pre> * * or more compactly: * * <pre>{@code * int sum = integers.reduce(0, Integer::sum); * }</pre> * * <p>While this may seem a more roundabout way to perform an aggregation * compared to simply mutating a running total in a loop, reduction * operations parallelize more gracefully, without needing additional * synchronization and with greatly reduced risk of data races. * * @param identity the identity value for the accumulating function * @param op an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * @return the result of the reduction * @see #sum() * @see #min() * @see #max() * @see #average() */ int reduce(int identity, IntBinaryOperator op); /** * Performs a <a href="package-summary.html#Reduction">reduction</a> on the * elements of this stream, using an * <a href="package-summary.html#Associativity">associative</a> accumulation * function, and returns an {@code OptionalInt} describing the reduced value, * if any. This is equivalent to: * <pre>{@code * boolean foundAny = false; * int result = null; * for (int element : this stream) { * if (!foundAny) { * foundAny = true; * result = element; * } * else * result = accumulator.applyAsInt(result, element); * } * return foundAny ? OptionalInt.of(result) : OptionalInt.empty(); * }</pre> * * but is not constrained to execute sequentially. * * <p>The {@code accumulator} function must be an * <a href="package-summary.html#Associativity">associative</a> function. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param op an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values * @return the result of the reduction * @see #reduce(int, IntBinaryOperator) */ OptionalInt reduce(IntBinaryOperator op); /** * Performs a <a href="package-summary.html#MutableReduction">mutable * reduction</a> operation on the elements of this stream. A mutable * reduction is one in which the reduced value is a mutable result container, * such as an {@code ArrayList}, and elements are incorporated by updating * the state of the result rather than by replacing the result. This * produces a result equivalent to: * <pre>{@code * R result = supplier.get(); * for (int element : this stream) * accumulator.accept(result, element); * return result; * }</pre> * * <p>Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations * can be parallelized without requiring additional synchronization. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @param <R> type of the result * @param supplier a function that creates a new result container. For a * parallel execution, this function may be called * multiple times and must return a fresh value each time. * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for incorporating an additional element into a result * @param combiner an <a href="package-summary.html#Associativity">associative</a>, * <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * function for combining two values, which must be * compatible with the accumulator function * @return the result of the reduction * @see Stream#collect(Supplier, BiConsumer, BiConsumer) */ <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner); /** * Returns the sum of elements in this stream. This is a special case * of a <a href="package-summary.html#Reduction">reduction</a> * and is equivalent to: * <pre>{@code * return reduce(0, Integer::sum); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return the sum of elements in this stream */ int sum(); /** * Returns an {@code OptionalInt} describing the minimum element of this * stream, or an empty optional if this stream is empty. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a> * and is equivalent to: * <pre>{@code * return reduce(Integer::min); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @return an {@code OptionalInt} containing the minimum element of this * stream, or an empty {@code OptionalInt} if the stream is empty */ OptionalInt min(); /** * Returns an {@code OptionalInt} describing the maximum element of this * stream, or an empty optional if this stream is empty. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a> * and is equivalent to: * <pre>{@code * return reduce(Integer::max); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code OptionalInt} containing the maximum element of this * stream, or an empty {@code OptionalInt} if the stream is empty */ OptionalInt max(); /** * Returns the count of elements in this stream. This is a special case of * a <a href="package-summary.html#Reduction">reduction</a> and is * equivalent to: * <pre>{@code * return mapToLong(e -> 1L).sum(); * }</pre> * * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. * * @return the count of elements in this stream */ long count(); /** * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of * this stream, or an empty optional if this stream is empty. This is a * special case of a * <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code OptionalDouble} containing the average element of this * stream, or an empty optional if the stream is empty */ OptionalDouble average(); /** * Returns an {@code IntSummaryStatistics} describing various * summary data about the elements of this stream. This is a special * case of a <a href="package-summary.html#Reduction">reduction</a>. * * <p>This is a <a href="package-summary.html#StreamOps">terminal * operation</a>. * * @return an {@code IntSummaryStatistics} describing various summary data * about the elements of this stream */ IntSummaryStatistics summaryStatistics(); /** * Returns whether any elements of this stream match the provided * predicate. May not evaluate the predicate on all elements if not * necessary for determining the result. If the stream is empty then * {@code false} is returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>existential quantification</em> of the * predicate over the elements of the stream (for some x P(x)). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if any elements of the stream match the provided * predicate, otherwise {@code false} */ boolean anyMatch(IntPredicate predicate); /** * Returns whether all elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>universal quantification</em> of the * predicate over the elements of the stream (for all x P(x)). If the * stream is empty, the quantification is said to be <em>vacuously * satisfied</em> and is always {@code true} (regardless of P(x)). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if either all elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ boolean allMatch(IntPredicate predicate); /** * Returns whether no elements of this stream match the provided predicate. * May not evaluate the predicate on all elements if not necessary for * determining the result. If the stream is empty then {@code true} is * returned and the predicate is not evaluated. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @apiNote * This method evaluates the <em>universal quantification</em> of the * negated predicate over the elements of the stream (for all x ~P(x)). If * the stream is empty, the quantification is said to be vacuously satisfied * and is always {@code true}, regardless of P(x). * * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, * <a href="package-summary.html#Statelessness">stateless</a> * predicate to apply to elements of this stream * @return {@code true} if either no elements of the stream match the * provided predicate or the stream is empty, otherwise {@code false} */ boolean noneMatch(IntPredicate predicate); /** * Returns an {@link OptionalInt} describing the first element of this * stream, or an empty {@code OptionalInt} if the stream is empty. If the * stream has no encounter order, then any element may be returned. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * @return an {@code OptionalInt} describing the first element of this stream, * or an empty {@code OptionalInt} if the stream is empty */ OptionalInt findFirst(); /** * Returns an {@link OptionalInt} describing some element of the stream, or * an empty {@code OptionalInt} if the stream is empty. * * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting * terminal operation</a>. * * <p>The behavior of this operation is explicitly nondeterministic; it is * free to select any element in the stream. This is to allow for maximal * performance in parallel operations; the cost is that multiple invocations * on the same source may not return the same result. (If a stable result * is desired, use {@link #findFirst()} instead.) * * @return an {@code OptionalInt} describing some element of this stream, or * an empty {@code OptionalInt} if the stream is empty * @see #findFirst() */ OptionalInt findAny(); /** * Returns a {@code LongStream} consisting of the elements of this stream, * converted to {@code long}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code LongStream} consisting of the elements of this stream, * converted to {@code long} */ LongStream asLongStream(); /** * Returns a {@code DoubleStream} consisting of the elements of this stream, * converted to {@code double}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code DoubleStream} consisting of the elements of this stream, * converted to {@code double} */ DoubleStream asDoubleStream(); /** * Returns a {@code Stream} consisting of the elements of this stream, * each boxed to an {@code Integer}. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate * operation</a>. * * @return a {@code Stream} consistent of the elements of this stream, * each boxed to an {@code Integer} */ Stream<Integer> boxed(); @Override IntStream sequential(); @Override IntStream parallel(); @Override PrimitiveIterator.OfInt iterator(); @Override Spliterator.OfInt spliterator(); // Static factories /** * Returns a builder for an {@code IntStream}. * * @return a stream builder */ public static Builder builder() { return new Streams.IntStreamBuilderImpl(); } /** * Returns an empty sequential {@code IntStream}. * * @return an empty sequential stream */ public static IntStream empty() { return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false); } /** * Returns a sequential {@code IntStream} containing a single element. * * @param t the single element * @return a singleton sequential stream */ public static IntStream of(int t) { return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false); } /** * Returns a sequential ordered stream whose elements are the specified values. * * @param values the elements of the new stream * @return the new stream */ public static IntStream of(int... values) { return Arrays.stream(values); } /** * Returns an infinite sequential ordered {@code IntStream} produced by iterative * application of a function {@code f} to an initial element {@code seed}, * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, * {@code f(f(seed))}, etc. * * <p>The first element (position {@code 0}) in the {@code IntStream} will be * the provided {@code seed}. For {@code n > 0}, the element at position * {@code n}, will be the result of applying the function {@code f} to the * element at position {@code n - 1}. * * @param seed the initial element * @param f a function to be applied to to the previous element to produce * a new element * @return A new sequential {@code IntStream} */ public static IntStream iterate(final int seed, final IntUnaryOperator f) { Objects.requireNonNull(f); final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() { int t = seed; @Override public boolean hasNext() { return true; } @Override public int nextInt() { int v = t; t = f.applyAsInt(t); return v; } }; return StreamSupport.intStream(Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); } /** * Returns an infinite sequential unordered stream where each element is * generated by the provided {@code IntSupplier}. This is suitable for * generating constant streams, streams of random elements, etc. * * @param s the {@code IntSupplier} for generated elements * @return a new infinite sequential unordered {@code IntStream} */ public static IntStream generate(IntSupplier s) { Objects.requireNonNull(s); return StreamSupport.intStream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false); } /** * Returns a sequential ordered {@code IntStream} from {@code startInclusive} * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of * {@code 1}. * * @apiNote * <p>An equivalent sequence of increasing values can be produced * sequentially using a {@code for} loop as follows: * <pre>{@code * for (int i = startInclusive; i < endExclusive ; i++) { ... } * }</pre> * * @param startInclusive the (inclusive) initial value * @param endExclusive the exclusive upper bound * @return a sequential {@code IntStream} for the range of {@code int} * elements */ public static IntStream range(int startInclusive, int endExclusive) { if (startInclusive >= endExclusive) { return empty(); } else { return StreamSupport.intStream( new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false); } } /** * Returns a sequential ordered {@code IntStream} from {@code startInclusive} * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of * {@code 1}. * * @apiNote * <p>An equivalent sequence of increasing values can be produced * sequentially using a {@code for} loop as follows: * <pre>{@code * for (int i = startInclusive; i <= endInclusive ; i++) { ... } * }</pre> * * @param startInclusive the (inclusive) initial value * @param endInclusive the inclusive upper bound * @return a sequential {@code IntStream} for the range of {@code int} * elements */ public static IntStream rangeClosed(int startInclusive, int endInclusive) { if (startInclusive > endInclusive) { return empty(); } else { return StreamSupport.intStream( new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false); } } /** * Creates a lazily concatenated stream whose elements are all the * elements of the first stream followed by all the elements of the * second stream. The resulting stream is ordered if both * of the input streams are ordered, and parallel if either of the input * streams is parallel. When the resulting stream is closed, the close * handlers for both input streams are invoked. * * @implNote * Use caution when constructing streams from repeated concatenation. * Accessing an element of a deeply concatenated stream can result in deep * call chains, or even {@code StackOverflowException}. * * @param a the first stream * @param b the second stream * @return the concatenation of the two input streams */ public static IntStream concat(IntStream a, IntStream b) { Objects.requireNonNull(a); Objects.requireNonNull(b); Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt( a.spliterator(), b.spliterator()); IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel()); return stream.onClose(Streams.composedClose(a, b)); } /** * A mutable builder for an {@code IntStream}. * * <p>A stream builder has a lifecycle, which starts in a building * phase, during which elements can be added, and then transitions to a built * phase, after which elements may not be added. The built phase * begins when the {@link #build()} method is called, which creates an * ordered stream whose elements are the elements that were added to the * stream builder, in the order they were added. * * @see IntStream#builder() * @since 1.8 */ public interface Builder extends IntConsumer { /** * Adds an element to the stream being built. * * @throws IllegalStateException if the builder has already transitioned * to the built state */ @Override void accept(int t); /** * Adds an element to the stream being built. * * @implSpec * The default implementation behaves as if: * <pre>{@code * accept(t) * return this; * }</pre> * * @param t the element to add * @return {@code this} builder * @throws IllegalStateException if the builder has already transitioned * to the built state */ default Builder add(int t) { accept(t); return this; } /** * Builds the stream, transitioning this builder to the built state. * An {@code IllegalStateException} is thrown if there are further * attempts to operate on the builder after it has entered the built * state. * * @return the built stream * @throws IllegalStateException if the builder has already transitioned to * the built state */ IntStream build(); } }
googleapis/google-cloud-java
36,832
java-shopping-merchant-accounts/google-shopping-merchant-accounts/src/main/java/com/google/shopping/merchant/accounts/v1/ProgramsServiceClient.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.shopping.merchant.accounts.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.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.UnaryCallable; import com.google.common.util.concurrent.MoreExecutors; import com.google.shopping.merchant.accounts.v1.stub.ProgramsServiceStub; import com.google.shopping.merchant.accounts.v1.stub.ProgramsServiceStubSettings; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service for program management. * * <p>Programs provide a mechanism for adding functionality to merchant accounts. A typical example * of this is the [Free product listings](https://support.google.com/merchants/answer/13889434) * program, which enables products from a merchant's store to be shown across Google for free. * * <p>This service exposes methods to retrieve a business's participation in all available programs, * in addition to methods for explicitly enabling or disabling participation in each program. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.getProgram(name); * } * }</pre> * * <p>Note: close() needs to be called on the ProgramsServiceClient 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> GetProgram</td> * <td><p> Retrieves the specified program for the account.</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> getProgram(GetProgramRequest 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> getProgram(ProgramName name) * <li><p> getProgram(String name) * </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> getProgramCallable() * </ul> * </td> * </tr> * <tr> * <td><p> ListPrograms</td> * <td><p> Retrieves all programs for the account.</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> listPrograms(ListProgramsRequest 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> listPrograms(AccountName parent) * <li><p> listPrograms(String parent) * </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> listProgramsPagedCallable() * <li><p> listProgramsCallable() * </ul> * </td> * </tr> * <tr> * <td><p> EnableProgram</td> * <td><p> Enable participation in the specified program for the account.</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> enableProgram(EnableProgramRequest 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> enableProgram(ProgramName name) * <li><p> enableProgram(String name) * </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> enableProgramCallable() * </ul> * </td> * </tr> * <tr> * <td><p> DisableProgram</td> * <td><p> Disable participation in the specified program for the account.</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> disableProgram(DisableProgramRequest 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> disableProgram(ProgramName name) * <li><p> disableProgram(String name) * </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> disableProgramCallable() * </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 ProgramsServiceSettings 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 * ProgramsServiceSettings programsServiceSettings = * ProgramsServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * ProgramsServiceClient programsServiceClient = * ProgramsServiceClient.create(programsServiceSettings); * }</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 * ProgramsServiceSettings programsServiceSettings = * ProgramsServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * ProgramsServiceClient programsServiceClient = * ProgramsServiceClient.create(programsServiceSettings); * }</pre> * * <p>To use REST (HTTP1.1/JSON) transport (instead of gRPC) for sending and receiving requests over * the wire: * * <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 * ProgramsServiceSettings programsServiceSettings = * ProgramsServiceSettings.newHttpJsonBuilder().build(); * ProgramsServiceClient programsServiceClient = * ProgramsServiceClient.create(programsServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class ProgramsServiceClient implements BackgroundResource { private final ProgramsServiceSettings settings; private final ProgramsServiceStub stub; /** Constructs an instance of ProgramsServiceClient with default settings. */ public static final ProgramsServiceClient create() throws IOException { return create(ProgramsServiceSettings.newBuilder().build()); } /** * Constructs an instance of ProgramsServiceClient, 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 ProgramsServiceClient create(ProgramsServiceSettings settings) throws IOException { return new ProgramsServiceClient(settings); } /** * Constructs an instance of ProgramsServiceClient, using the given stub for making calls. This is * for advanced usage - prefer using create(ProgramsServiceSettings). */ public static final ProgramsServiceClient create(ProgramsServiceStub stub) { return new ProgramsServiceClient(stub); } /** * Constructs an instance of ProgramsServiceClient, 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 ProgramsServiceClient(ProgramsServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((ProgramsServiceStubSettings) settings.getStubSettings()).createStub(); } protected ProgramsServiceClient(ProgramsServiceStub stub) { this.settings = null; this.stub = stub; } public final ProgramsServiceSettings getSettings() { return settings; } public ProgramsServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.getProgram(name); * } * }</pre> * * @param name Required. The name of the program to retrieve. Format: * `accounts/{account}/programs/{program}`. For example, * `accounts/123456/programs/free-listings`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program getProgram(ProgramName name) { GetProgramRequest request = GetProgramRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String name = ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString(); * Program response = programsServiceClient.getProgram(name); * } * }</pre> * * @param name Required. The name of the program to retrieve. Format: * `accounts/{account}/programs/{program}`. For example, * `accounts/123456/programs/free-listings`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program getProgram(String name) { GetProgramRequest request = GetProgramRequest.newBuilder().setName(name).build(); return getProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * GetProgramRequest request = * GetProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * Program response = programsServiceClient.getProgram(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 Program getProgram(GetProgramRequest request) { return getProgramCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * GetProgramRequest request = * GetProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * ApiFuture<Program> future = programsServiceClient.getProgramCallable().futureCall(request); * // Do something. * Program response = future.get(); * } * }</pre> */ public final UnaryCallable<GetProgramRequest, Program> getProgramCallable() { return stub.getProgramCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * AccountName parent = AccountName.of("[ACCOUNT]"); * for (Program element : programsServiceClient.listPrograms(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The name of the account for which to retrieve all programs. Format: * `accounts/{account}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListProgramsPagedResponse listPrograms(AccountName parent) { ListProgramsRequest request = ListProgramsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listPrograms(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String parent = AccountName.of("[ACCOUNT]").toString(); * for (Program element : programsServiceClient.listPrograms(parent).iterateAll()) { * // doThingsWith(element); * } * } * }</pre> * * @param parent Required. The name of the account for which to retrieve all programs. Format: * `accounts/{account}` * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final ListProgramsPagedResponse listPrograms(String parent) { ListProgramsRequest request = ListProgramsRequest.newBuilder().setParent(parent).build(); return listPrograms(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ListProgramsRequest request = * ListProgramsRequest.newBuilder() * .setParent(AccountName.of("[ACCOUNT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * for (Program element : programsServiceClient.listPrograms(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 ListProgramsPagedResponse listPrograms(ListProgramsRequest request) { return listProgramsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ListProgramsRequest request = * ListProgramsRequest.newBuilder() * .setParent(AccountName.of("[ACCOUNT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * ApiFuture<Program> future = * programsServiceClient.listProgramsPagedCallable().futureCall(request); * // Do something. * for (Program element : future.get().iterateAll()) { * // doThingsWith(element); * } * } * }</pre> */ public final UnaryCallable<ListProgramsRequest, ListProgramsPagedResponse> listProgramsPagedCallable() { return stub.listProgramsPagedCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Retrieves all programs for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ListProgramsRequest request = * ListProgramsRequest.newBuilder() * .setParent(AccountName.of("[ACCOUNT]").toString()) * .setPageSize(883849137) * .setPageToken("pageToken873572522") * .build(); * while (true) { * ListProgramsResponse response = programsServiceClient.listProgramsCallable().call(request); * for (Program element : response.getProgramsList()) { * // doThingsWith(element); * } * String nextPageToken = response.getNextPageToken(); * if (!Strings.isNullOrEmpty(nextPageToken)) { * request = request.toBuilder().setPageToken(nextPageToken).build(); * } else { * break; * } * } * } * }</pre> */ public final UnaryCallable<ListProgramsRequest, ListProgramsResponse> listProgramsCallable() { return stub.listProgramsCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.enableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to enable participation for the given * account. Format: `accounts/{account}/programs/{program}`. For example, * `accounts/123456/programs/free-listings`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program enableProgram(ProgramName name) { EnableProgramRequest request = EnableProgramRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return enableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String name = ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString(); * Program response = programsServiceClient.enableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to enable participation for the given * account. Format: `accounts/{account}/programs/{program}`. For example, * `accounts/123456/programs/free-listings`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program enableProgram(String name) { EnableProgramRequest request = EnableProgramRequest.newBuilder().setName(name).build(); return enableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * EnableProgramRequest request = * EnableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * Program response = programsServiceClient.enableProgram(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 Program enableProgram(EnableProgramRequest request) { return enableProgramCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Enable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * EnableProgramRequest request = * EnableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * ApiFuture<Program> future = programsServiceClient.enableProgramCallable().futureCall(request); * // Do something. * Program response = future.get(); * } * }</pre> */ public final UnaryCallable<EnableProgramRequest, Program> enableProgramCallable() { return stub.enableProgramCallable(); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * ProgramName name = ProgramName.of("[ACCOUNT]", "[PROGRAM]"); * Program response = programsServiceClient.disableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to disable participation for the given * account. Format: `accounts/{account}/programs/{program}`. For example, * `accounts/123456/programs/free-listings`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program disableProgram(ProgramName name) { DisableProgramRequest request = DisableProgramRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return disableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * String name = ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString(); * Program response = programsServiceClient.disableProgram(name); * } * }</pre> * * @param name Required. The name of the program for which to disable participation for the given * account. Format: `accounts/{account}/programs/{program}`. For example, * `accounts/123456/programs/free-listings`. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final Program disableProgram(String name) { DisableProgramRequest request = DisableProgramRequest.newBuilder().setName(name).build(); return disableProgram(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * DisableProgramRequest request = * DisableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * Program response = programsServiceClient.disableProgram(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 Program disableProgram(DisableProgramRequest request) { return disableProgramCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Disable participation in the specified program for the account. * * <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 (ProgramsServiceClient programsServiceClient = ProgramsServiceClient.create()) { * DisableProgramRequest request = * DisableProgramRequest.newBuilder() * .setName(ProgramName.of("[ACCOUNT]", "[PROGRAM]").toString()) * .build(); * ApiFuture<Program> future = * programsServiceClient.disableProgramCallable().futureCall(request); * // Do something. * Program response = future.get(); * } * }</pre> */ public final UnaryCallable<DisableProgramRequest, Program> disableProgramCallable() { return stub.disableProgramCallable(); } @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 ListProgramsPagedResponse extends AbstractPagedListResponse< ListProgramsRequest, ListProgramsResponse, Program, ListProgramsPage, ListProgramsFixedSizeCollection> { public static ApiFuture<ListProgramsPagedResponse> createAsync( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ApiFuture<ListProgramsResponse> futureResponse) { ApiFuture<ListProgramsPage> futurePage = ListProgramsPage.createEmptyPage().createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, input -> new ListProgramsPagedResponse(input), MoreExecutors.directExecutor()); } private ListProgramsPagedResponse(ListProgramsPage page) { super(page, ListProgramsFixedSizeCollection.createEmptyCollection()); } } public static class ListProgramsPage extends AbstractPage<ListProgramsRequest, ListProgramsResponse, Program, ListProgramsPage> { private ListProgramsPage( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ListProgramsResponse response) { super(context, response); } private static ListProgramsPage createEmptyPage() { return new ListProgramsPage(null, null); } @Override protected ListProgramsPage createPage( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ListProgramsResponse response) { return new ListProgramsPage(context, response); } @Override public ApiFuture<ListProgramsPage> createPageAsync( PageContext<ListProgramsRequest, ListProgramsResponse, Program> context, ApiFuture<ListProgramsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); } } public static class ListProgramsFixedSizeCollection extends AbstractFixedSizeCollection< ListProgramsRequest, ListProgramsResponse, Program, ListProgramsPage, ListProgramsFixedSizeCollection> { private ListProgramsFixedSizeCollection(List<ListProgramsPage> pages, int collectionSize) { super(pages, collectionSize); } private static ListProgramsFixedSizeCollection createEmptyCollection() { return new ListProgramsFixedSizeCollection(null, 0); } @Override protected ListProgramsFixedSizeCollection createCollection( List<ListProgramsPage> pages, int collectionSize) { return new ListProgramsFixedSizeCollection(pages, collectionSize); } } }
googleads/google-ads-java
36,894
google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/GenerateAudienceCompositionInsightsResponse.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v19/services/audience_insights_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v19.services; /** * <pre> * Response message for * [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse} */ public final class GenerateAudienceCompositionInsightsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse) GenerateAudienceCompositionInsightsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use GenerateAudienceCompositionInsightsResponse.newBuilder() to construct. private GenerateAudienceCompositionInsightsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GenerateAudienceCompositionInsightsResponse() { sections_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new GenerateAudienceCompositionInsightsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_GenerateAudienceCompositionInsightsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.class, com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.Builder.class); } public static final int SECTIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v19.services.AudienceCompositionSection> sections_; /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v19.services.AudienceCompositionSection> getSectionsList() { return sections_; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder> getSectionsOrBuilderList() { return sections_; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public int getSectionsCount() { return sections_.size(); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.AudienceCompositionSection getSections(int index) { return sections_.get(index); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder getSectionsOrBuilder( int index) { return sections_.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 < sections_.size(); i++) { output.writeMessage(1, sections_.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 < sections_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, sections_.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.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse)) { return super.equals(obj); } com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse other = (com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse) obj; if (!getSectionsList() .equals(other.getSectionsList())) 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 (getSectionsCount() > 0) { hash = (37 * hash) + SECTIONS_FIELD_NUMBER; hash = (53 * hash) + getSectionsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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 * [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v19.services.AudienceInsightsService.GenerateAudienceCompositionInsights]. * </pre> * * Protobuf type {@code google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse) com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_GenerateAudienceCompositionInsightsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.class, com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.Builder.class); } // Construct using com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (sectionsBuilder_ == null) { sections_ = java.util.Collections.emptyList(); } else { sections_ = null; sectionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v19.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v19_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse getDefaultInstanceForType() { return com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse build() { com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse buildPartial() { com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse result = new com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse result) { if (sectionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { sections_ = java.util.Collections.unmodifiableList(sections_); bitField0_ = (bitField0_ & ~0x00000001); } result.sections_ = sections_; } else { result.sections_ = sectionsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse 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.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse) { return mergeFrom((com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse other) { if (other == com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse.getDefaultInstance()) return this; if (sectionsBuilder_ == null) { if (!other.sections_.isEmpty()) { if (sections_.isEmpty()) { sections_ = other.sections_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSectionsIsMutable(); sections_.addAll(other.sections_); } onChanged(); } } else { if (!other.sections_.isEmpty()) { if (sectionsBuilder_.isEmpty()) { sectionsBuilder_.dispose(); sectionsBuilder_ = null; sections_ = other.sections_; bitField0_ = (bitField0_ & ~0x00000001); sectionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSectionsFieldBuilder() : null; } else { sectionsBuilder_.addAllMessages(other.sections_); } } } 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.ads.googleads.v19.services.AudienceCompositionSection m = input.readMessage( com.google.ads.googleads.v19.services.AudienceCompositionSection.parser(), extensionRegistry); if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(m); } else { sectionsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v19.services.AudienceCompositionSection> sections_ = java.util.Collections.emptyList(); private void ensureSectionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { sections_ = new java.util.ArrayList<com.google.ads.googleads.v19.services.AudienceCompositionSection>(sections_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.AudienceCompositionSection, com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder> sectionsBuilder_; /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<com.google.ads.googleads.v19.services.AudienceCompositionSection> getSectionsList() { if (sectionsBuilder_ == null) { return java.util.Collections.unmodifiableList(sections_); } else { return sectionsBuilder_.getMessageList(); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public int getSectionsCount() { if (sectionsBuilder_ == null) { return sections_.size(); } else { return sectionsBuilder_.getCount(); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v19.services.AudienceCompositionSection getSections(int index) { if (sectionsBuilder_ == null) { return sections_.get(index); } else { return sectionsBuilder_.getMessage(index); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder setSections( int index, com.google.ads.googleads.v19.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.set(index, value); onChanged(); } else { sectionsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder setSections( int index, com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.set(index, builderForValue.build()); onChanged(); } else { sectionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections(com.google.ads.googleads.v19.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.add(value); onChanged(); } else { sectionsBuilder_.addMessage(value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( int index, com.google.ads.googleads.v19.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.add(index, value); onChanged(); } else { sectionsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(builderForValue.build()); onChanged(); } else { sectionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( int index, com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(index, builderForValue.build()); onChanged(); } else { sectionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder addAllSections( java.lang.Iterable<? extends com.google.ads.googleads.v19.services.AudienceCompositionSection> values) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, sections_); onChanged(); } else { sectionsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder clearSections() { if (sectionsBuilder_ == null) { sections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { sectionsBuilder_.clear(); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public Builder removeSections(int index) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.remove(index); onChanged(); } else { sectionsBuilder_.remove(index); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder getSectionsBuilder( int index) { return getSectionsFieldBuilder().getBuilder(index); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder getSectionsOrBuilder( int index) { if (sectionsBuilder_ == null) { return sections_.get(index); } else { return sectionsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder> getSectionsOrBuilderList() { if (sectionsBuilder_ != null) { return sectionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(sections_); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder addSectionsBuilder() { return getSectionsFieldBuilder().addBuilder( com.google.ads.googleads.v19.services.AudienceCompositionSection.getDefaultInstance()); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder addSectionsBuilder( int index) { return getSectionsFieldBuilder().addBuilder( index, com.google.ads.googleads.v19.services.AudienceCompositionSection.getDefaultInstance()); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v19.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder> getSectionsBuilderList() { return getSectionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.AudienceCompositionSection, com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder> getSectionsFieldBuilder() { if (sectionsBuilder_ == null) { sectionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v19.services.AudienceCompositionSection, com.google.ads.googleads.v19.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v19.services.AudienceCompositionSectionOrBuilder>( sections_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); sections_ = null; } return sectionsBuilder_; } @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.GenerateAudienceCompositionInsightsResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse) private static final com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse(); } public static com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GenerateAudienceCompositionInsightsResponse> PARSER = new com.google.protobuf.AbstractParser<GenerateAudienceCompositionInsightsResponse>() { @java.lang.Override public GenerateAudienceCompositionInsightsResponse 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<GenerateAudienceCompositionInsightsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GenerateAudienceCompositionInsightsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v19.services.GenerateAudienceCompositionInsightsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,894
google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/GenerateAudienceCompositionInsightsResponse.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v20/services/audience_insights_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v20.services; /** * <pre> * Response message for * [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse} */ public final class GenerateAudienceCompositionInsightsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse) GenerateAudienceCompositionInsightsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use GenerateAudienceCompositionInsightsResponse.newBuilder() to construct. private GenerateAudienceCompositionInsightsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GenerateAudienceCompositionInsightsResponse() { sections_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new GenerateAudienceCompositionInsightsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_GenerateAudienceCompositionInsightsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.class, com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.Builder.class); } public static final int SECTIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v20.services.AudienceCompositionSection> sections_; /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v20.services.AudienceCompositionSection> getSectionsList() { return sections_; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder> getSectionsOrBuilderList() { return sections_; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public int getSectionsCount() { return sections_.size(); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.AudienceCompositionSection getSections(int index) { return sections_.get(index); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder getSectionsOrBuilder( int index) { return sections_.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 < sections_.size(); i++) { output.writeMessage(1, sections_.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 < sections_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, sections_.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.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse)) { return super.equals(obj); } com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse other = (com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse) obj; if (!getSectionsList() .equals(other.getSectionsList())) 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 (getSectionsCount() > 0) { hash = (37 * hash) + SECTIONS_FIELD_NUMBER; hash = (53 * hash) + getSectionsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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 * [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v20.services.AudienceInsightsService.GenerateAudienceCompositionInsights]. * </pre> * * Protobuf type {@code google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse) com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_GenerateAudienceCompositionInsightsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.class, com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.Builder.class); } // Construct using com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (sectionsBuilder_ == null) { sections_ = java.util.Collections.emptyList(); } else { sections_ = null; sectionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v20.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v20_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse getDefaultInstanceForType() { return com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse build() { com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse buildPartial() { com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse result = new com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse result) { if (sectionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { sections_ = java.util.Collections.unmodifiableList(sections_); bitField0_ = (bitField0_ & ~0x00000001); } result.sections_ = sections_; } else { result.sections_ = sectionsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse 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.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse) { return mergeFrom((com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse other) { if (other == com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse.getDefaultInstance()) return this; if (sectionsBuilder_ == null) { if (!other.sections_.isEmpty()) { if (sections_.isEmpty()) { sections_ = other.sections_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSectionsIsMutable(); sections_.addAll(other.sections_); } onChanged(); } } else { if (!other.sections_.isEmpty()) { if (sectionsBuilder_.isEmpty()) { sectionsBuilder_.dispose(); sectionsBuilder_ = null; sections_ = other.sections_; bitField0_ = (bitField0_ & ~0x00000001); sectionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSectionsFieldBuilder() : null; } else { sectionsBuilder_.addAllMessages(other.sections_); } } } 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.ads.googleads.v20.services.AudienceCompositionSection m = input.readMessage( com.google.ads.googleads.v20.services.AudienceCompositionSection.parser(), extensionRegistry); if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(m); } else { sectionsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v20.services.AudienceCompositionSection> sections_ = java.util.Collections.emptyList(); private void ensureSectionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { sections_ = new java.util.ArrayList<com.google.ads.googleads.v20.services.AudienceCompositionSection>(sections_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.AudienceCompositionSection, com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder> sectionsBuilder_; /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<com.google.ads.googleads.v20.services.AudienceCompositionSection> getSectionsList() { if (sectionsBuilder_ == null) { return java.util.Collections.unmodifiableList(sections_); } else { return sectionsBuilder_.getMessageList(); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public int getSectionsCount() { if (sectionsBuilder_ == null) { return sections_.size(); } else { return sectionsBuilder_.getCount(); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v20.services.AudienceCompositionSection getSections(int index) { if (sectionsBuilder_ == null) { return sections_.get(index); } else { return sectionsBuilder_.getMessage(index); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder setSections( int index, com.google.ads.googleads.v20.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.set(index, value); onChanged(); } else { sectionsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder setSections( int index, com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.set(index, builderForValue.build()); onChanged(); } else { sectionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections(com.google.ads.googleads.v20.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.add(value); onChanged(); } else { sectionsBuilder_.addMessage(value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( int index, com.google.ads.googleads.v20.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.add(index, value); onChanged(); } else { sectionsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(builderForValue.build()); onChanged(); } else { sectionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( int index, com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(index, builderForValue.build()); onChanged(); } else { sectionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder addAllSections( java.lang.Iterable<? extends com.google.ads.googleads.v20.services.AudienceCompositionSection> values) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, sections_); onChanged(); } else { sectionsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder clearSections() { if (sectionsBuilder_ == null) { sections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { sectionsBuilder_.clear(); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public Builder removeSections(int index) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.remove(index); onChanged(); } else { sectionsBuilder_.remove(index); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder getSectionsBuilder( int index) { return getSectionsFieldBuilder().getBuilder(index); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder getSectionsOrBuilder( int index) { if (sectionsBuilder_ == null) { return sections_.get(index); } else { return sectionsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder> getSectionsOrBuilderList() { if (sectionsBuilder_ != null) { return sectionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(sections_); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder addSectionsBuilder() { return getSectionsFieldBuilder().addBuilder( com.google.ads.googleads.v20.services.AudienceCompositionSection.getDefaultInstance()); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder addSectionsBuilder( int index) { return getSectionsFieldBuilder().addBuilder( index, com.google.ads.googleads.v20.services.AudienceCompositionSection.getDefaultInstance()); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v20.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder> getSectionsBuilderList() { return getSectionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.AudienceCompositionSection, com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder> getSectionsFieldBuilder() { if (sectionsBuilder_ == null) { sectionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v20.services.AudienceCompositionSection, com.google.ads.googleads.v20.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v20.services.AudienceCompositionSectionOrBuilder>( sections_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); sections_ = null; } return sectionsBuilder_; } @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.GenerateAudienceCompositionInsightsResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse) private static final com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse(); } public static com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GenerateAudienceCompositionInsightsResponse> PARSER = new com.google.protobuf.AbstractParser<GenerateAudienceCompositionInsightsResponse>() { @java.lang.Override public GenerateAudienceCompositionInsightsResponse 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<GenerateAudienceCompositionInsightsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GenerateAudienceCompositionInsightsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v20.services.GenerateAudienceCompositionInsightsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleads/google-ads-java
36,894
google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/GenerateAudienceCompositionInsightsResponse.java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v21/services/audience_insights_service.proto // Protobuf Java Version: 3.25.7 package com.google.ads.googleads.v21.services; /** * <pre> * Response message for * [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse} */ public final class GenerateAudienceCompositionInsightsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse) GenerateAudienceCompositionInsightsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use GenerateAudienceCompositionInsightsResponse.newBuilder() to construct. private GenerateAudienceCompositionInsightsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private GenerateAudienceCompositionInsightsResponse() { sections_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new GenerateAudienceCompositionInsightsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_GenerateAudienceCompositionInsightsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.class, com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.Builder.class); } public static final int SECTIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.ads.googleads.v21.services.AudienceCompositionSection> sections_; /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public java.util.List<com.google.ads.googleads.v21.services.AudienceCompositionSection> getSectionsList() { return sections_; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder> getSectionsOrBuilderList() { return sections_; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public int getSectionsCount() { return sections_.size(); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.AudienceCompositionSection getSections(int index) { return sections_.get(index); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ @java.lang.Override public com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder getSectionsOrBuilder( int index) { return sections_.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 < sections_.size(); i++) { output.writeMessage(1, sections_.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 < sections_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, sections_.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.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse)) { return super.equals(obj); } com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse other = (com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse) obj; if (!getSectionsList() .equals(other.getSectionsList())) 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 (getSectionsCount() > 0) { hash = (37 * hash) + SECTIONS_FIELD_NUMBER; hash = (53 * hash) + getSectionsList().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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.GenerateAudienceCompositionInsightsResponse 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 * [AudienceInsightsService.GenerateAudienceCompositionInsights][google.ads.googleads.v21.services.AudienceInsightsService.GenerateAudienceCompositionInsights]. * </pre> * * Protobuf type {@code google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse) com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_GenerateAudienceCompositionInsightsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.class, com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.Builder.class); } // Construct using com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.newBuilder() private Builder() { } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (sectionsBuilder_ == null) { sections_ = java.util.Collections.emptyList(); } else { sections_ = null; sectionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v21.services.AudienceInsightsServiceProto.internal_static_google_ads_googleads_v21_services_GenerateAudienceCompositionInsightsResponse_descriptor; } @java.lang.Override public com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse getDefaultInstanceForType() { return com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse build() { com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse buildPartial() { com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse result = new com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields(com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse result) { if (sectionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { sections_ = java.util.Collections.unmodifiableList(sections_); bitField0_ = (bitField0_ & ~0x00000001); } result.sections_ = sections_; } else { result.sections_ = sectionsBuilder_.build(); } } private void buildPartial0(com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse 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.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse) { return mergeFrom((com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse other) { if (other == com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse.getDefaultInstance()) return this; if (sectionsBuilder_ == null) { if (!other.sections_.isEmpty()) { if (sections_.isEmpty()) { sections_ = other.sections_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSectionsIsMutable(); sections_.addAll(other.sections_); } onChanged(); } } else { if (!other.sections_.isEmpty()) { if (sectionsBuilder_.isEmpty()) { sectionsBuilder_.dispose(); sectionsBuilder_ = null; sections_ = other.sections_; bitField0_ = (bitField0_ & ~0x00000001); sectionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSectionsFieldBuilder() : null; } else { sectionsBuilder_.addAllMessages(other.sections_); } } } 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.ads.googleads.v21.services.AudienceCompositionSection m = input.readMessage( com.google.ads.googleads.v21.services.AudienceCompositionSection.parser(), extensionRegistry); if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(m); } else { sectionsBuilder_.addMessage(m); } break; } // case 10 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.ads.googleads.v21.services.AudienceCompositionSection> sections_ = java.util.Collections.emptyList(); private void ensureSectionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { sections_ = new java.util.ArrayList<com.google.ads.googleads.v21.services.AudienceCompositionSection>(sections_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.AudienceCompositionSection, com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder> sectionsBuilder_; /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<com.google.ads.googleads.v21.services.AudienceCompositionSection> getSectionsList() { if (sectionsBuilder_ == null) { return java.util.Collections.unmodifiableList(sections_); } else { return sectionsBuilder_.getMessageList(); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public int getSectionsCount() { if (sectionsBuilder_ == null) { return sections_.size(); } else { return sectionsBuilder_.getCount(); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v21.services.AudienceCompositionSection getSections(int index) { if (sectionsBuilder_ == null) { return sections_.get(index); } else { return sectionsBuilder_.getMessage(index); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder setSections( int index, com.google.ads.googleads.v21.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.set(index, value); onChanged(); } else { sectionsBuilder_.setMessage(index, value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder setSections( int index, com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.set(index, builderForValue.build()); onChanged(); } else { sectionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections(com.google.ads.googleads.v21.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.add(value); onChanged(); } else { sectionsBuilder_.addMessage(value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( int index, com.google.ads.googleads.v21.services.AudienceCompositionSection value) { if (sectionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSectionsIsMutable(); sections_.add(index, value); onChanged(); } else { sectionsBuilder_.addMessage(index, value); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(builderForValue.build()); onChanged(); } else { sectionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder addSections( int index, com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder builderForValue) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.add(index, builderForValue.build()); onChanged(); } else { sectionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder addAllSections( java.lang.Iterable<? extends com.google.ads.googleads.v21.services.AudienceCompositionSection> values) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, sections_); onChanged(); } else { sectionsBuilder_.addAllMessages(values); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder clearSections() { if (sectionsBuilder_ == null) { sections_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { sectionsBuilder_.clear(); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public Builder removeSections(int index) { if (sectionsBuilder_ == null) { ensureSectionsIsMutable(); sections_.remove(index); onChanged(); } else { sectionsBuilder_.remove(index); } return this; } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder getSectionsBuilder( int index) { return getSectionsFieldBuilder().getBuilder(index); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder getSectionsOrBuilder( int index) { if (sectionsBuilder_ == null) { return sections_.get(index); } else { return sectionsBuilder_.getMessageOrBuilder(index); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<? extends com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder> getSectionsOrBuilderList() { if (sectionsBuilder_ != null) { return sectionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(sections_); } } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder addSectionsBuilder() { return getSectionsFieldBuilder().addBuilder( com.google.ads.googleads.v21.services.AudienceCompositionSection.getDefaultInstance()); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder addSectionsBuilder( int index) { return getSectionsFieldBuilder().addBuilder( index, com.google.ads.googleads.v21.services.AudienceCompositionSection.getDefaultInstance()); } /** * <pre> * The contents of the insights report, organized into sections. * Each section is associated with one of the AudienceInsightsDimension values * in the request. There may be more than one section per dimension. * </pre> * * <code>repeated .google.ads.googleads.v21.services.AudienceCompositionSection sections = 1;</code> */ public java.util.List<com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder> getSectionsBuilderList() { return getSectionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.AudienceCompositionSection, com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder> getSectionsFieldBuilder() { if (sectionsBuilder_ == null) { sectionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.ads.googleads.v21.services.AudienceCompositionSection, com.google.ads.googleads.v21.services.AudienceCompositionSection.Builder, com.google.ads.googleads.v21.services.AudienceCompositionSectionOrBuilder>( sections_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); sections_ = null; } return sectionsBuilder_; } @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.GenerateAudienceCompositionInsightsResponse) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse) private static final com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse(); } public static com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<GenerateAudienceCompositionInsightsResponse> PARSER = new com.google.protobuf.AbstractParser<GenerateAudienceCompositionInsightsResponse>() { @java.lang.Override public GenerateAudienceCompositionInsightsResponse 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<GenerateAudienceCompositionInsightsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<GenerateAudienceCompositionInsightsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v21.services.GenerateAudienceCompositionInsightsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/xmlgraphics-fop
36,592
fop-core/src/main/java/org/apache/fop/render/intermediate/IFSerializer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.intermediate; import java.awt.Color; import java.awt.Dimension; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.w3c.dom.Document; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import org.apache.xmlgraphics.image.loader.ImageManager; import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.xmlgraphics.util.QName; import org.apache.xmlgraphics.util.XMLizable; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.apps.FOUserAgent; import org.apache.fop.fo.extensions.InternalElementMapping; import org.apache.fop.fonts.FontInfo; import org.apache.fop.render.DefaultRendererConfigurator; import org.apache.fop.render.RendererEventProducer; import org.apache.fop.render.RenderingContext; import org.apache.fop.render.intermediate.IFRendererConfig.IFRendererConfigParser; import org.apache.fop.render.intermediate.IFStructureTreeBuilder.IFStructureTreeElement; import org.apache.fop.render.intermediate.extensions.AbstractAction; import org.apache.fop.render.intermediate.extensions.Bookmark; import org.apache.fop.render.intermediate.extensions.BookmarkTree; import org.apache.fop.render.intermediate.extensions.DocumentNavigationExtensionConstants; import org.apache.fop.render.intermediate.extensions.Link; import org.apache.fop.render.intermediate.extensions.NamedDestination; import org.apache.fop.traits.BorderProps; import org.apache.fop.traits.RuleStyle; import org.apache.fop.util.ColorUtil; import org.apache.fop.util.DOM2SAX; import org.apache.fop.util.LanguageTags; import org.apache.fop.util.XMLConstants; import org.apache.fop.util.XMLUtil; /** * IFPainter implementation that serializes the intermediate format to XML. */ public class IFSerializer extends AbstractXMLWritingIFDocumentHandler implements IFConstants, IFPainter, IFDocumentNavigationHandler { /** * Intermediate Format (IF) version, used to express an @version attribute * in the root element of the IF document, the initial value of which * is set to '2.0' to signify that something preceded it (but didn't * happen to be marked as such), and that this version is not necessarily * backwards compatible with the unmarked (&lt;2.0) version. */ public static final String VERSION = "2.0"; private IFDocumentHandler mimicHandler; private int pageSequenceIndex; // used for accessibility /** Holds the intermediate format state */ private IFState state; private String currentID = ""; private IFStructureTreeBuilder structureTreeBuilder; private int pageNumberEnded; public IFSerializer(IFContext context) { super(context); } /** {@inheritDoc} */ @Override protected String getMainNamespace() { return NAMESPACE; } /** {@inheritDoc} */ public boolean supportsPagesOutOfOrder() { return false; //Theoretically supported but disabled to improve performance when //rendering the IF to the final format later on } /** {@inheritDoc} */ public String getMimeType() { return MIME_TYPE; } /** {@inheritDoc} */ public IFDocumentHandlerConfigurator getConfigurator() { if (this.mimicHandler != null) { return getMimickedDocumentHandler().getConfigurator(); } else { return new DefaultRendererConfigurator(getUserAgent(), new IFRendererConfigParser()); } } /** {@inheritDoc} */ @Override public IFDocumentNavigationHandler getDocumentNavigationHandler() { return this; } /** * Tells this serializer to mimic the given document handler (mostly applies to the font set * that is used during layout). * @param targetHandler the document handler to mimic */ public void mimicDocumentHandler(IFDocumentHandler targetHandler) { this.mimicHandler = targetHandler; } /** * Returns the document handler that is being mimicked by this serializer. * @return the mimicked document handler or null if no such document handler has been set */ public IFDocumentHandler getMimickedDocumentHandler() { return this.mimicHandler; } /** {@inheritDoc} */ public FontInfo getFontInfo() { if (this.mimicHandler != null) { return this.mimicHandler.getFontInfo(); } else { return null; } } /** {@inheritDoc} */ public void setFontInfo(FontInfo fontInfo) { if (this.mimicHandler != null) { this.mimicHandler.setFontInfo(fontInfo); } } /** {@inheritDoc} */ public void setDefaultFontInfo(FontInfo fontInfo) { if (this.mimicHandler != null) { this.mimicHandler.setDefaultFontInfo(fontInfo); } } @Override public StructureTreeEventHandler getStructureTreeEventHandler() { if (structureTreeBuilder == null) { structureTreeBuilder = new IFStructureTreeBuilder(); } return structureTreeBuilder; } /** {@inheritDoc} */ @Override public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping(DocumentNavigationExtensionConstants.PREFIX, DocumentNavigationExtensionConstants.NAMESPACE); handler.startPrefixMapping(InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "version", VERSION); handler.startElement(EL_DOCUMENT, atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } } @Override public void setDocumentLocale(Locale locale) { AttributesImpl atts = new AttributesImpl(); atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(locale)); try { handler.startElement(EL_LOCALE, atts); handler.endElement(EL_LOCALE); } catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); } } /** {@inheritDoc} */ @Override public void startDocumentHeader() throws IFException { try { handler.startElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } } /** {@inheritDoc} */ @Override public void endDocumentHeader() throws IFException { try { handler.endElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } } /** {@inheritDoc} */ @Override public void startDocumentTrailer() throws IFException { try { handler.startElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); } } /** {@inheritDoc} */ @Override public void endDocumentTrailer() throws IFException { try { handler.endElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); } } /** {@inheritDoc} */ public void endDocument() throws IFException { try { handler.endElement(EL_DOCUMENT); handler.endDocument(); finishDocumentNavigation(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } } /** {@inheritDoc} */ public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", XMLUtil.CDATA, id); } Locale lang = getContext().getLanguage(); if (lang != null) { atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(lang)); } XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); addForeignAttributes(atts); handler.startElement(EL_PAGE_SEQUENCE, atts); if (this.getUserAgent().isAccessibilityEnabled()) { assert (structureTreeBuilder != null); structureTreeBuilder.replayEventsForPageSequence(handler, pageSequenceIndex++); } } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } } /** {@inheritDoc} */ public void endPageSequence() throws IFException { try { handler.endElement(EL_PAGE_SEQUENCE); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } } /** {@inheritDoc} */ public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "index", Integer.toString(index)); addAttribute(atts, "name", name); if (pageMasterName != null) { //fox:external-document doesn't have a page-master addAttribute(atts, "page-master-name", pageMasterName); } addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); addForeignAttributes(atts); getContext().setPageIndex(index); handler.startElement(EL_PAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } } /** {@inheritDoc} */ @Override public void startPageHeader() throws IFException { try { handler.startElement(EL_PAGE_HEADER); if (this.getUserAgent().isAccessibilityEnabled()) { structureTreeBuilder.replayEventsForRetrievedMarkers(handler); } } catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); } } /** {@inheritDoc} */ @Override public void endPageHeader() throws IFException { try { handler.endElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); } } /** {@inheritDoc} */ public IFPainter startPageContent() throws IFException { try { handler.startElement(EL_PAGE_CONTENT); this.state = IFState.create(); return this; } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } } /** {@inheritDoc} */ public void endPageContent() throws IFException { try { this.state = null; currentID = ""; handler.endElement(EL_PAGE_CONTENT); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } } /** {@inheritDoc} */ @Override public void startPageTrailer() throws IFException { try { handler.startElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); } } /** {@inheritDoc} */ @Override public void endPageTrailer() throws IFException { try { commitNavigation(); handler.endElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); } } /** {@inheritDoc} */ public void endPage() throws IFException { try { handler.endElement(EL_PAGE); getContext().setPageIndex(-1); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } if (mimicHandler != null) { pageNumberEnded++; FOUserAgent userAgent = mimicHandler.getContext().getUserAgent(); RendererEventProducer.Provider.get(userAgent.getEventBroadcaster()).endPage(this, pageNumberEnded); } } //---=== IFPainter ===--- /** {@inheritDoc} */ public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { startViewport(IFUtil.toString(transform), size, clipRect); } /** {@inheritDoc} */ public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(IFUtil.toString(transforms), size, clipRect); } private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); if (clipRect != null) { addAttribute(atts, "clip-rect", IFUtil.toString(clipRect)); } if (getUserAgent().isAccessibilityEnabled() && getContext().getRegionType() != null) { addAttribute(atts, "region-type", getContext().getRegionType()); } handler.startElement(EL_VIEWPORT, atts); } catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); } } /** {@inheritDoc} */ public void endViewport() throws IFException { try { handler.endElement(EL_VIEWPORT); } catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); } } /** {@inheritDoc} */ public void startGroup(AffineTransform[] transforms, String layer) throws IFException { startGroup(IFUtil.toString(transforms), layer); } /** {@inheritDoc} */ public void startGroup(AffineTransform transform, String layer) throws IFException { startGroup(IFUtil.toString(transform), layer); } private void startGroup(String transform, String layer) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } if (layer != null && layer.length() > 0) { addAttribute(atts, "layer", layer); } handler.startElement(EL_GROUP, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } } /** {@inheritDoc} */ public void endGroup() throws IFException { try { handler.endElement(EL_GROUP); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } } /** {@inheritDoc} */ public void drawImage(String uri, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, XLINK_HREF, uri); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.element(EL_IMAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } finally { ImageSessionContext session = getUserAgent().getImageSessionContext(); ImageManager imageManager = getUserAgent().getImageManager(); imageManager.closeImage(uri, session); } } private void addForeignAttributes(AttributesImpl atts) throws SAXException { Map foreignAttributes = getContext().getForeignAttributes(); if (!foreignAttributes.isEmpty()) { for (Object o : foreignAttributes.entrySet()) { Map.Entry entry = (Map.Entry) o; addAttribute(atts, (QName) entry.getKey(), entry.getValue().toString()); } } } /** {@inheritDoc} */ public void drawImage(Document doc, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.startElement(EL_IMAGE, atts); new DOM2SAX(handler).writeDocument(doc, true); handler.endElement(EL_IMAGE); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } } @Override public boolean supportsSoftHyphen() { return false; } private static String toString(Paint paint) { if (paint instanceof Color) { return ColorUtil.colorToString((Color)paint); } else { throw new UnsupportedOperationException("Paint not supported: " + paint); } } /** {@inheritDoc} */ public void clipRect(Rectangle rect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); handler.element(EL_CLIP_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); } } /** {@inheritDoc} */ public void clipBackground(Rectangle rect, BorderProps bpsBefore, BorderProps bpsAfter, BorderProps bpsStart, BorderProps bpsEnd) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); if (hasRoundedCorners(bpsBefore, bpsAfter, bpsStart, bpsEnd)) { if (bpsBefore != null) { addAttribute(atts, "top", bpsBefore.toString()); } if (bpsAfter != null) { addAttribute(atts, "bottom", bpsAfter.toString()); } if (bpsStart != null) { addAttribute(atts, "left", bpsStart.toString()); } if (bpsEnd != null) { addAttribute(atts, "right", bpsEnd.toString()); } } handler.element(EL_CLIP_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); } } /** {@inheritDoc} */ public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addAttribute(atts, "fill", toString(fill)); handler.element(EL_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } } //TODO create a class representing all borders should exist //with query methods like this private boolean hasRoundedCorners(BorderProps bpsBefore, BorderProps bpsAfter, BorderProps bpsStart, BorderProps bpsEnd) { boolean rtn = false; if (bpsBefore != null && bpsBefore.getRadiusStart() > 0 && bpsStart != null && bpsStart.getRadiusStart() > 0) { rtn = true; } if (bpsBefore != null && bpsBefore.getRadiusEnd() > 0 && bpsEnd != null && bpsEnd.getRadiusStart() > 0) { rtn = true; } if (bpsEnd != null && bpsEnd.getRadiusEnd() > 0 && bpsAfter != null && bpsAfter.getRadiusEnd() > 0) { rtn = true; } if (bpsAfter != null && bpsAfter.getRadiusStart() > 0 && bpsStart != null && bpsStart.getRadiusEnd() > 0) { rtn = true; } return rtn; } /** {@inheritDoc} */ public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right, Color innerBackgroundColor) throws IFException { if (top == null && bottom == null && left == null && right == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); if (top != null) { addAttribute(atts, "top", top.toString()); } if (bottom != null) { addAttribute(atts, "bottom", bottom.toString()); } if (left != null) { addAttribute(atts, "left", left.toString()); } if (right != null) { addAttribute(atts, "right", right.toString()); } if (innerBackgroundColor != null) { addAttribute(atts, "inner-background-color", ColorUtil.colorToString(innerBackgroundColor)); } handler.element(EL_BORDER_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); } } /** {@inheritDoc} */ public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x1", Integer.toString(start.x)); addAttribute(atts, "y1", Integer.toString(start.y)); addAttribute(atts, "x2", Integer.toString(end.x)); addAttribute(atts, "y2", Integer.toString(end.y)); addAttribute(atts, "stroke-width", Integer.toString(width)); addAttribute(atts, "color", ColorUtil.colorToString(color)); addAttribute(atts, "style", style.getName()); handler.element(EL_LINE, atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } } /** {@inheritDoc} */ public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { drawText(x, y, letterSpacing, wordSpacing, dp, text, false); } /** {@inheritDoc} */ public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text, boolean nextIsSpace) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(x)); addAttribute(atts, "y", Integer.toString(y)); if (nextIsSpace) { addAttribute(atts, "next-is-space", "true"); } if (letterSpacing != 0) { addAttribute(atts, "letter-spacing", Integer.toString(letterSpacing)); } if (wordSpacing != 0) { addAttribute(atts, "word-spacing", Integer.toString(wordSpacing)); } if (dp != null) { if (IFUtil.isDPIdentity(dp)) { // don't add dx or dp attribute } else if (IFUtil.isDPOnlyDX(dp)) { // add dx attribute only int[] dx = IFUtil.convertDPToDX(dp); addAttribute(atts, "dx", IFUtil.toString(dx)); } else { // add dp attribute only addAttribute(atts, "dp", XMLUtil.encodePositionAdjustments(dp)); } } addStructureReference(atts); if (getContext().isHyphenated()) { addAttribute(atts, "hyphenated", "true"); } handler.startElement(EL_TEXT, atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement(EL_TEXT); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } } /** {@inheritDoc} */ public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { try { AttributesImpl atts = new AttributesImpl(); boolean changed; if (family != null) { changed = !family.equals(state.getFontFamily()); if (changed) { state.setFontFamily(family); addAttribute(atts, "family", family); } } if (style != null) { changed = !style.equals(state.getFontStyle()); if (changed) { state.setFontStyle(style); addAttribute(atts, "style", style); } } if (weight != null) { changed = (weight != state.getFontWeight()); if (changed) { state.setFontWeight(weight); addAttribute(atts, "weight", weight.toString()); } } if (variant != null) { changed = !variant.equals(state.getFontVariant()); if (changed) { state.setFontVariant(variant); addAttribute(atts, "variant", variant); } } if (size != null) { changed = (size != state.getFontSize()); if (changed) { state.setFontSize(size); addAttribute(atts, "size", size.toString()); } } if (color != null) { changed = !org.apache.xmlgraphics.java2d.color.ColorUtil.isSameColor( color, state.getTextColor()); if (changed) { state.setTextColor(color); addAttribute(atts, "color", toString(color)); } } if (atts.getLength() > 0) { handler.element(EL_FONT, atts); } } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } } /** {@inheritDoc} */ public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } } /** * @return a new rendering context * @throws IllegalStateException unless overridden */ protected RenderingContext createRenderingContext() throws IllegalStateException { throw new IllegalStateException("Should never be called!"); } private void addAttribute(AttributesImpl atts, org.apache.xmlgraphics.util.QName attribute, String value) throws SAXException { handler.startPrefixMapping(attribute.getPrefix(), attribute.getNamespaceURI()); XMLUtil.addAttribute(atts, attribute, value); } private void addAttribute(AttributesImpl atts, String localName, String value) { XMLUtil.addAttribute(atts, localName, value); } private void addStructureReference(AttributesImpl atts) { IFStructureTreeElement structureTreeElement = (IFStructureTreeElement) getContext().getStructureTreeElement(); if (structureTreeElement != null) { addStructRefAttribute(atts, structureTreeElement.getId()); } } private void addStructRefAttribute(AttributesImpl atts, String id) { atts.addAttribute(InternalElementMapping.URI, InternalElementMapping.STRUCT_REF, InternalElementMapping.STANDARD_PREFIX + ":" + InternalElementMapping.STRUCT_REF, XMLConstants.CDATA, id); } private void addID() throws SAXException { String id = getContext().getID(); if (!currentID.equals(id)) { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "name", id); handler.startElement(EL_ID, atts); handler.endElement(EL_ID); currentID = id; } } private Map incompleteActions = new java.util.HashMap(); private List completeActions = new java.util.LinkedList(); private void noteAction(AbstractAction action) { if (action == null) { throw new NullPointerException("action must not be null"); } if (!action.isComplete()) { assert action.hasID(); incompleteActions.put(action.getID(), action); } } /** {@inheritDoc} */ public void renderNamedDestination(NamedDestination destination) throws IFException { noteAction(destination.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "name", "name", XMLConstants.CDATA, destination.getName()); try { handler.startElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION, atts); serializeXMLizable(destination.getAction()); handler.endElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION); } catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); } } /** {@inheritDoc} */ public void renderBookmarkTree(BookmarkTree tree) throws IFException { AttributesImpl atts = new AttributesImpl(); try { handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE, atts); for (Object o : tree.getBookmarks()) { Bookmark b = (Bookmark) o; if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE); } catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); } } private void serializeBookmark(Bookmark bookmark) throws SAXException, IFException { noteAction(bookmark.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "title", "title", XMLUtil.CDATA, bookmark.getTitle()); atts.addAttribute("", "starting-state", "starting-state", XMLUtil.CDATA, bookmark.isShown() ? "show" : "hide"); handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK, atts); serializeXMLizable(bookmark.getAction()); for (Object o : bookmark.getChildBookmarks()) { Bookmark b = (Bookmark) o; if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK); } /** {@inheritDoc} */ public void renderLink(Link link) throws IFException { noteAction(link.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "rect", "rect", XMLConstants.CDATA, IFUtil.toString(link.getTargetRect())); if (getUserAgent().isAccessibilityEnabled()) { IFStructureTreeElement structureTreeElement = (IFStructureTreeElement) link.getAction().getStructureTreeElement(); if (structureTreeElement != null) { addStructRefAttribute(atts, structureTreeElement.getId()); } } try { handler.startElement(DocumentNavigationExtensionConstants.LINK, atts); serializeXMLizable(link.getAction()); handler.endElement(DocumentNavigationExtensionConstants.LINK); } catch (SAXException e) { throw new IFException("SAX error serializing link", e); } } /** {@inheritDoc} */ public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); assert action.hasID(); AbstractAction noted = (AbstractAction)incompleteActions.remove(action.getID()); if (noted != null) { completeActions.add(action); } else { //ignore as it was already complete when it was first used. } } public int getPageIndex() { return -1; } private void commitNavigation() throws IFException { Iterator iter = this.completeActions.iterator(); while (iter.hasNext()) { AbstractAction action = (AbstractAction)iter.next(); iter.remove(); serializeXMLizable(action); } assert this.completeActions.size() == 0; } private void finishDocumentNavigation() { assert this.incompleteActions.size() == 0 : "Still holding incomplete actions!"; } private void serializeXMLizable(XMLizable object) throws IFException { try { object.toSAX(handler); } catch (SAXException e) { throw new IFException("SAX error serializing object", e); } } /** {@inheritDoc} */ public boolean isBackgroundRequired(BorderProps bpsTop, BorderProps bpsBottom, BorderProps bpsLeft, BorderProps bpsRight) { return true; } }
apache/harmony
36,689
classlib/modules/pack200/src/main/java/org/apache/harmony/unpack200/NewAttributeBands.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.unpack200; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.apache.harmony.pack200.BHSDCodec; import org.apache.harmony.pack200.Codec; import org.apache.harmony.pack200.Pack200Exception; import org.apache.harmony.unpack200.bytecode.Attribute; import org.apache.harmony.unpack200.bytecode.CPClass; import org.apache.harmony.unpack200.bytecode.CPDouble; import org.apache.harmony.unpack200.bytecode.CPFieldRef; import org.apache.harmony.unpack200.bytecode.CPFloat; import org.apache.harmony.unpack200.bytecode.CPInteger; import org.apache.harmony.unpack200.bytecode.CPInterfaceMethodRef; import org.apache.harmony.unpack200.bytecode.CPLong; import org.apache.harmony.unpack200.bytecode.CPMethodRef; import org.apache.harmony.unpack200.bytecode.CPNameAndType; import org.apache.harmony.unpack200.bytecode.CPString; import org.apache.harmony.unpack200.bytecode.CPUTF8; import org.apache.harmony.unpack200.bytecode.NewAttribute; /** * Set of bands relating to a non-predefined attribute */ public class NewAttributeBands extends BandSet { private final AttributeLayout attributeLayout; private int backwardsCallCount; protected List attributeLayoutElements; public NewAttributeBands(Segment segment, AttributeLayout attributeLayout) throws IOException { super(segment); this.attributeLayout = attributeLayout; parseLayout(); attributeLayout.setBackwardsCallCount(backwardsCallCount); } /* * (non-Javadoc) * * @see org.apache.harmony.unpack200.BandSet#unpack(java.io.InputStream) */ public void read(InputStream in) throws IOException, Pack200Exception { // does nothing - use parseAttributes instead } /** * Parse the bands relating to this AttributeLayout and return the correct * class file attributes as a List of {@link Attribute} * * @throws Pack200Exception */ public List parseAttributes(InputStream in, int occurrenceCount) throws IOException, Pack200Exception { for (int i = 0; i < attributeLayoutElements.size(); i++) { AttributeLayoutElement element = (AttributeLayoutElement) attributeLayoutElements .get(i); element.readBands(in, occurrenceCount); } List attributes = new ArrayList(occurrenceCount); for (int i = 0; i < occurrenceCount; i++) { attributes.add(getOneAttribute(i, attributeLayoutElements)); } return attributes; } /** * Get one attribute at the given index from the various bands. The correct * bands must have already been read in. * * @param index * @param elements * @return */ private Attribute getOneAttribute(int index, List elements) { NewAttribute attribute = new NewAttribute(segment.getCpBands() .cpUTF8Value(attributeLayout.getName()), attributeLayout.getIndex()); for (int i = 0; i < elements.size(); i++) { AttributeLayoutElement element = (AttributeLayoutElement) elements .get(i); element.addToAttribute(index, attribute); } return attribute; } /** * Tokenise the layout into AttributeElements * * @throws IOException */ private void parseLayout() throws IOException { if (attributeLayoutElements == null) { attributeLayoutElements = new ArrayList(); StringReader stream = new StringReader(attributeLayout.getLayout()); AttributeLayoutElement e; while ((e = readNextAttributeElement(stream)) != null) { attributeLayoutElements.add(e); } resolveCalls(); } } /** * Resolve calls in the attribute layout and returns the number of backwards * calls */ private void resolveCalls() { int backwardsCalls = 0; for (int i = 0; i < attributeLayoutElements.size(); i++) { AttributeLayoutElement element = (AttributeLayoutElement) attributeLayoutElements .get(i); if (element instanceof Callable) { Callable callable = (Callable) element; if (i == 0) { callable.setFirstCallable(true); } List body = callable.body; // Look for calls in the body for (int iIndex = 0; iIndex < body.size(); iIndex++) { LayoutElement layoutElement = (LayoutElement) body .get(iIndex); // Set the callable for each call backwardsCalls += resolveCallsForElement(i, callable, layoutElement); } } } backwardsCallCount = backwardsCalls; } private int resolveCallsForElement(int i, Callable currentCallable, LayoutElement layoutElement) { int backwardsCalls = 0; if (layoutElement instanceof Call) { Call call = (Call) layoutElement; int index = call.callableIndex; if (index == 0) { // Calls the parent callable backwardsCalls++; call.setCallable(currentCallable); } else if (index > 0) { // Forwards call for (int k = i + 1; k < attributeLayoutElements.size(); k++) { AttributeLayoutElement el = (AttributeLayoutElement) attributeLayoutElements .get(k); if (el instanceof Callable) { index--; if (index == 0) { call.setCallable((Callable) el); break; } } } } else { // Backwards call backwardsCalls++; for (int k = i - 1; k >= 0; k--) { AttributeLayoutElement el = (AttributeLayoutElement) attributeLayoutElements .get(k); if (el instanceof Callable) { index++; if (index == 0) { call.setCallable((Callable) el); break; } } } } } else if (layoutElement instanceof Replication) { List children = ((Replication) layoutElement).layoutElements; for (Iterator iterator = children.iterator(); iterator.hasNext();) { LayoutElement object = (LayoutElement) iterator.next(); backwardsCalls += resolveCallsForElement(i, currentCallable, object); } } return backwardsCalls; } private AttributeLayoutElement readNextAttributeElement(StringReader stream) throws IOException { stream.mark(1); int nextChar = stream.read(); if (nextChar == -1) { return null; } if (nextChar == '[') { List body = readBody(getStreamUpToMatchingBracket(stream)); return new Callable(body); } else { stream.reset(); return readNextLayoutElement(stream); } } private LayoutElement readNextLayoutElement(StringReader stream) throws IOException { int nextChar = stream.read(); if (nextChar == -1) { return null; } switch (nextChar) { // Integrals case 'B': case 'H': case 'I': case 'V': return new Integral(new String(new char[] { (char) nextChar })); case 'S': case 'F': return new Integral(new String(new char[] { (char) nextChar, (char) stream.read() })); case 'P': stream.mark(1); if (stream.read() != 'O') { stream.reset(); return new Integral("P" + (char) stream.read()); } else { return new Integral("PO" + (char) stream.read()); } case 'O': stream.mark(1); if (stream.read() != 'S') { stream.reset(); return new Integral("O" + (char) stream.read()); } else { return new Integral("OS" + (char) stream.read()); } // Replication case 'N': char uint_type = (char) stream.read(); stream.read(); // '[' String str = readUpToMatchingBracket(stream); return new Replication("" + uint_type, str); // Union case 'T': String int_type = "" + (char) stream.read(); if (int_type.equals("S")) { int_type += (char) stream.read(); } List unionCases = new ArrayList(); UnionCase c; while ((c = readNextUnionCase(stream)) != null) { unionCases.add(c); } stream.read(); // '(' stream.read(); // ')' stream.read(); // '[' List body = null; stream.mark(1); char next = (char) stream.read(); if (next != ']') { stream.reset(); body = readBody(getStreamUpToMatchingBracket(stream)); } return new Union(int_type, unionCases, body); // Call case '(': int number = readNumber(stream).intValue(); stream.read(); // ')' return new Call(number); // Reference case 'K': case 'R': String string = "" + (char) nextChar + (char) stream.read(); char nxt = (char) stream.read(); string += nxt; if (nxt == 'N') { string += (char) stream.read(); } return new Reference(string); } return null; } /** * Read a UnionCase from the stream * * @param stream * @return * @throws IOException */ private UnionCase readNextUnionCase(StringReader stream) throws IOException { stream.mark(2); stream.read(); // '(' char next = (char) stream.read(); if (next == ')') { stream.reset(); return null; } else { stream.reset(); stream.read(); // '(' } List tags = new ArrayList(); Integer nextTag; do { nextTag = readNumber(stream); if (nextTag != null) { tags.add(nextTag); stream.read(); // ',' or ')' } } while (nextTag != null); stream.read(); // '[' stream.mark(1); next = (char) stream.read(); if (next == ']') { return new UnionCase(tags); } else { stream.reset(); return new UnionCase(tags, readBody(getStreamUpToMatchingBracket(stream))); } } /** * An AttributeLayoutElement is a part of an attribute layout and has one or * more bands associated with it, which transmit the AttributeElement data * for successive Attributes of this type. */ private interface AttributeLayoutElement { /** * Read the bands associated with this part of the layout * * @param in * @param count * @throws Pack200Exception * @throws IOException */ public void readBands(InputStream in, int count) throws IOException, Pack200Exception; /** * Add the band data for this element at the given index to the * attribute * * @param index * @param attribute */ public void addToAttribute(int index, NewAttribute attribute); } private abstract class LayoutElement implements AttributeLayoutElement { protected int getLength(char uint_type) { int length = 0; switch (uint_type) { case 'B': length = 1; break; case 'H': length = 2; break; case 'I': length = 4; break; case 'V': length = 0; break; } return length; } } public class Integral extends LayoutElement { private final String tag; private int[] band; public Integral(String tag) { this.tag = tag; } public void readBands(InputStream in, int count) throws IOException, Pack200Exception { band = decodeBandInt(attributeLayout.getName() + "_" + tag, in, getCodec(tag), count); } public void addToAttribute(int n, NewAttribute attribute) { long value = band[n]; if (tag.equals("B") || tag.equals("FB")) { attribute.addInteger(1, value); } else if (tag.equals("SB")) { attribute.addInteger(1, (byte) value); } else if (tag.equals("H") || tag.equals("FH")) { attribute.addInteger(2, value); } else if (tag.equals("SH")) { attribute.addInteger(2, (short) value); } else if (tag.equals("I") || tag.equals("FI")) { attribute.addInteger(4, value); } else if (tag.equals("SI")) { attribute.addInteger(4, (int) value); } else if (tag.equals("V") || tag.equals("FV") || tag.equals("SV")) { // Don't add V's - they shouldn't be written out to the class // file } else if (tag.startsWith("PO")) { char uint_type = tag.substring(2).toCharArray()[0]; int length = getLength(uint_type); attribute.addBCOffset(length, (int) value); } else if (tag.startsWith("P")) { char uint_type = tag.substring(1).toCharArray()[0]; int length = getLength(uint_type); attribute.addBCIndex(length, (int) value); } else if (tag.startsWith("OS")) { char uint_type = tag.substring(2).toCharArray()[0]; int length = getLength(uint_type); if (length == 1) { value = (byte) value; } else if (length == 2) { value = (short) value; } else if (length == 4) { value = (int) value; } attribute.addBCLength(length, (int) value); } else if (tag.startsWith("O")) { char uint_type = tag.substring(1).toCharArray()[0]; int length = getLength(uint_type); attribute.addBCLength(length, (int) value); } } long getValue(int index) { return band[index]; } public String getTag() { return tag; } } /** * A replication is an array of layout elements, with an associated count */ public class Replication extends LayoutElement { private final Integral countElement; private final List layoutElements = new ArrayList(); public Replication(String tag, String contents) throws IOException { this.countElement = new Integral(tag); StringReader stream = new StringReader(contents); LayoutElement e; while ((e = readNextLayoutElement(stream)) != null) { layoutElements.add(e); } } public void readBands(InputStream in, int count) throws IOException, Pack200Exception { countElement.readBands(in, count); int arrayCount = 0; for (int i = 0; i < count; i++) { arrayCount += countElement.getValue(i); } for (int i = 0; i < layoutElements.size(); i++) { LayoutElement element = (LayoutElement) layoutElements.get(i); element.readBands(in, arrayCount); } } public void addToAttribute(int index, NewAttribute attribute) { // Add the count value countElement.addToAttribute(index, attribute); // Add the corresponding array values int offset = 0; for (int i = 0; i < index; i++) { offset += countElement.getValue(i); } long numElements = countElement.getValue(index); for (int i = offset; i < offset + numElements; i++) { for (int it = 0; it < layoutElements.size(); it++) { LayoutElement element = (LayoutElement) layoutElements .get(it); element.addToAttribute(i, attribute); } } } public Integral getCountElement() { return countElement; } public List getLayoutElements() { return layoutElements; } } /** * A Union is a type of layout element where the tag value acts as a * selector for one of the union cases */ public class Union extends LayoutElement { private final Integral unionTag; private final List unionCases; private final List defaultCaseBody; private int[] caseCounts; private int defaultCount; public Union(String tag, List unionCases, List body) { this.unionTag = new Integral(tag); this.unionCases = unionCases; this.defaultCaseBody = body; } public void readBands(InputStream in, int count) throws IOException, Pack200Exception { unionTag.readBands(in, count); int[] values = unionTag.band; // Count the band size for each union case then read the bands caseCounts = new int[unionCases.size()]; for (int i = 0; i < caseCounts.length; i++) { UnionCase unionCase = (UnionCase) unionCases.get(i); for (int j = 0; j < values.length; j++) { if (unionCase.hasTag(values[j])) { caseCounts[i]++; } } unionCase.readBands(in, caseCounts[i]); } // Count number of default cases then read the default bands for (int i = 0; i < values.length; i++) { boolean found = false; for (int it = 0; it < unionCases.size(); it++) { UnionCase unionCase = (UnionCase) unionCases.get(it); if (unionCase.hasTag(values[i])) { found = true; } } if (!found) { defaultCount++; } } if (defaultCaseBody != null) { for (int i = 0; i < defaultCaseBody.size(); i++) { LayoutElement element = (LayoutElement) defaultCaseBody .get(i); element.readBands(in, defaultCount); } } } public void addToAttribute(int n, NewAttribute attribute) { unionTag.addToAttribute(n, attribute); int offset = 0; int[] tagBand = unionTag.band; long tag = unionTag.getValue(n); boolean defaultCase = true; for (int i = 0; i < unionCases.size(); i++) { UnionCase element = (UnionCase) unionCases.get(i); if (element.hasTag(tag)) { defaultCase = false; for (int j = 0; j < n; j++) { if (element.hasTag(tagBand[j])) { offset++; } } element.addToAttribute(offset, attribute); } } if (defaultCase) { // default case int defaultOffset = 0; for (int j = 0; j < n; j++) { boolean found = false; for (int i = 0; i < unionCases.size(); i++) { UnionCase element = (UnionCase) unionCases.get(i); if (element.hasTag(tagBand[j])) { found = true; } } if (!found) { defaultOffset++; } } if (defaultCaseBody != null) { for (int i = 0; i < defaultCaseBody.size(); i++) { LayoutElement element = (LayoutElement) defaultCaseBody .get(i); element.addToAttribute(defaultOffset, attribute); } } } } public Integral getUnionTag() { return unionTag; } public List getUnionCases() { return unionCases; } public List getDefaultCaseBody() { return defaultCaseBody; } } public class Call extends LayoutElement { private final int callableIndex; private Callable callable; public Call(int callableIndex) { this.callableIndex = callableIndex; } public void setCallable(Callable callable) { this.callable = callable; if (callableIndex < 1) { callable.setBackwardsCallable(); } } public void readBands(InputStream in, int count) { /* * We don't read anything here, but we need to pass the extra count * to the callable if it's a forwards call. For backwards callables * the count is transmitted directly in the attribute bands and so * it is added later. */ if (callableIndex > 0) { callable.addCount(count); } } public void addToAttribute(int n, NewAttribute attribute) { callable.addNextToAttribute(attribute); } public int getCallableIndex() { return callableIndex; } public Callable getCallable() { return callable; } } /** * Constant Pool Reference */ public class Reference extends LayoutElement { private final String tag; private Object band; private final int length; public Reference(String tag) { this.tag = tag; length = getLength(tag.charAt(tag.length() - 1)); } public void readBands(InputStream in, int count) throws IOException, Pack200Exception { if (tag.startsWith("KI")) { // Integer band = parseCPIntReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("KJ")) { // Long band = parseCPLongReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("KF")) { // Float band = parseCPFloatReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("KD")) { // Double band = parseCPDoubleReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("KS")) { // String band = parseCPStringReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RC")) { // Class band = parseCPClassReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RS")) { // Signature band = parseCPSignatureReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RD")) { // Descriptor band = parseCPDescriptorReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RF")) { // Field Reference band = parseCPFieldRefReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RM")) { // Method Reference band = parseCPMethodRefReferences(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RI")) { // Interface Method Reference band = parseCPInterfaceMethodRefReferences( attributeLayout.getName(), in, Codec.UNSIGNED5, count); } else if (tag.startsWith("RU")) { // UTF8 String band = parseCPUTF8References(attributeLayout.getName(), in, Codec.UNSIGNED5, count); } } public void addToAttribute(int n, NewAttribute attribute) { if (tag.startsWith("KI")) { // Integer attribute.addToBody(length, ((CPInteger[]) band)[n]); } else if (tag.startsWith("KJ")) { // Long attribute.addToBody(length, ((CPLong[]) band)[n]); } else if (tag.startsWith("KF")) { // Float attribute.addToBody(length, ((CPFloat[]) band)[n]); } else if (tag.startsWith("KD")) { // Double attribute.addToBody(length, ((CPDouble[]) band)[n]); } else if (tag.startsWith("KS")) { // String attribute.addToBody(length, ((CPString[]) band)[n]); } else if (tag.startsWith("RC")) { // Class attribute.addToBody(length, ((CPClass[]) band)[n]); } else if (tag.startsWith("RS")) { // Signature attribute.addToBody(length, ((CPUTF8[]) band)[n]); } else if (tag.startsWith("RD")) { // Descriptor attribute.addToBody(length, ((CPNameAndType[]) band)[n]); } else if (tag.startsWith("RF")) { // Field Reference attribute.addToBody(length, ((CPFieldRef[]) band)[n]); } else if (tag.startsWith("RM")) { // Method Reference attribute.addToBody(length, ((CPMethodRef[]) band)[n]); } else if (tag.startsWith("RI")) { // Interface Method Reference attribute.addToBody(length, ((CPInterfaceMethodRef[]) band)[n]); } else if (tag.startsWith("RU")) { // UTF8 String attribute.addToBody(length, ((CPUTF8[]) band)[n]); } } public String getTag() { return tag; } } public static class Callable implements AttributeLayoutElement { private final List body; private boolean isBackwardsCallable; private boolean isFirstCallable; public Callable(List body) throws IOException { this.body = body; } private int count; private int index; /** * Used by calls when adding band contents to attributes so they don't * have to keep track of the internal index of the callable * * @param attribute */ public void addNextToAttribute(NewAttribute attribute) { for (int i = 0; i < body.size(); i++) { LayoutElement element = (LayoutElement) body.get(i); element.addToAttribute(index, attribute); } index++; } /** * Adds the count of a call to this callable (ie the number of calls) * * @param count */ public void addCount(int count) { this.count += count; } public void readBands(InputStream in, int count) throws IOException, Pack200Exception { if (isFirstCallable) { count += this.count; } else { count = this.count; } for (int i = 0; i < body.size(); i++) { LayoutElement element = (LayoutElement) body.get(i); element.readBands(in, count); } } public void addToAttribute(int n, NewAttribute attribute) { if (isFirstCallable) { // Ignore n because bands also contain element parts from calls for (int i = 0; i < body.size(); i++) { LayoutElement element = (LayoutElement) body.get(i); element.addToAttribute(index, attribute); } index++; } } public boolean isBackwardsCallable() { return isBackwardsCallable; } /** * Tells this Callable that it is a backwards callable */ public void setBackwardsCallable() { this.isBackwardsCallable = true; } public void setFirstCallable(boolean isFirstCallable) { this.isFirstCallable = isFirstCallable; } public List getBody() { return body; } } /** * A Union case */ public class UnionCase extends LayoutElement { private List body; private final List tags; public UnionCase(List tags) { this.tags = tags; } public boolean hasTag(long l) { return tags.contains(new Integer((int) l)); } public UnionCase(List tags, List body) throws IOException { this.tags = tags; this.body = body; } public void readBands(InputStream in, int count) throws IOException, Pack200Exception { if (body != null) { for (int i = 0; i < body.size(); i++) { LayoutElement element = (LayoutElement) body.get(i); element.readBands(in, count); } } } public void addToAttribute(int index, NewAttribute attribute) { if (body != null) { for (int i = 0; i < body.size(); i++) { LayoutElement element = (LayoutElement) body.get(i); element.addToAttribute(index, attribute); } } } public List getBody() { return body == null ? Collections.EMPTY_LIST : body; } } /** * Utility method to get the contents of the given stream, up to the next * ']', (ignoring pairs of brackets '[' and ']') * * @param stream * @return * @throws IOException */ private StringReader getStreamUpToMatchingBracket(StringReader stream) throws IOException { StringBuffer sb = new StringBuffer(); int foundBracket = -1; while (foundBracket != 0) { char c = (char) stream.read(); if (c == ']') { foundBracket++; } if (c == '[') { foundBracket--; } if (!(foundBracket == 0)) { sb.append(c); } } return new StringReader(sb.toString()); } /** * Returns the {@link BHSDCodec} that should be used for the given layout * element * * @param layoutElement */ public BHSDCodec getCodec(String layoutElement) { if (layoutElement.indexOf('O') >= 0) { return Codec.BRANCH5; } else if (layoutElement.indexOf('P') >= 0) { return Codec.BCI5; } else if (layoutElement.indexOf('S') >= 0 && layoutElement.indexOf("KS") < 0 //$NON-NLS-1$ && layoutElement.indexOf("RS") < 0) { //$NON-NLS-1$ return Codec.SIGNED5; } else if (layoutElement.indexOf('B') >= 0) { return Codec.BYTE1; } else { return Codec.UNSIGNED5; } } /** * Utility method to get the contents of the given stream, up to the next * ']', (ignoring pairs of brackets '[' and ']') * * @param stream * @return * @throws IOException */ private String readUpToMatchingBracket(StringReader stream) throws IOException { StringBuffer sb = new StringBuffer(); int foundBracket = -1; while (foundBracket != 0) { char c = (char) stream.read(); if (c == ']') { foundBracket++; } if (c == '[') { foundBracket--; } if (!(foundBracket == 0)) { sb.append(c); } } return sb.toString(); } /** * Read a number from the stream and return it * * @param stream * @return * @throws IOException */ private Integer readNumber(StringReader stream) throws IOException { stream.mark(1); char first = (char) stream.read(); boolean negative = first == '-'; if (!negative) { stream.reset(); } stream.mark(100); int i; int length = 0; while ((i = (stream.read())) != -1 && Character.isDigit((char) i)) { length++; } stream.reset(); if (length == 0) { return null; } char[] digits = new char[length]; int read = stream.read(digits); if (read != digits.length) { throw new IOException("Error reading from the input stream"); } return new Integer(Integer.parseInt((negative ? "-" : "") + new String(digits))); } /** * Read a 'body' section of the layout from the given stream * * @param stream * @return List of LayoutElements * @throws IOException */ private List readBody(StringReader stream) throws IOException { List layoutElements = new ArrayList(); LayoutElement e; while ((e = readNextLayoutElement(stream)) != null) { layoutElements.add(e); } return layoutElements; } public int getBackwardsCallCount() { return backwardsCallCount; } /** * Once the attribute bands have been read the callables can be informed * about the number of times each is subject to a backwards call. This * method is used to set this information. * * @param backwardsCalls * one int for each backwards callable, which contains the number * of times that callable is subject to a backwards call. * @throws IOException */ public void setBackwardsCalls(int[] backwardsCalls) throws IOException { int index = 0; parseLayout(); for (int i = 0; i < attributeLayoutElements.size(); i++) { AttributeLayoutElement element = (AttributeLayoutElement) attributeLayoutElements .get(i); if (element instanceof Callable && ((Callable) element).isBackwardsCallable()) { ((Callable) element).addCount(backwardsCalls[index]); index++; } } } public void unpack() throws IOException, Pack200Exception { } }
apache/hudi
36,655
hudi-hadoop-common/src/test/java/org/apache/hudi/parquet/io/TestHoodieParquetFileBinaryCopier.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.hudi.parquet.io; import org.apache.hudi.util.HoodieFileMetadataMerger; import org.apache.hudi.storage.StoragePath; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.parquet.HadoopReadOptions; import org.apache.parquet.Version; import org.apache.parquet.column.ColumnDescriptor; import org.apache.parquet.column.ParquetProperties; import org.apache.parquet.crypto.ParquetCipher; import org.apache.parquet.example.data.Group; import org.apache.parquet.example.data.simple.SimpleGroup; import org.apache.parquet.format.DataPageHeader; import org.apache.parquet.format.DataPageHeaderV2; import org.apache.parquet.format.PageHeader; import org.apache.parquet.format.converter.ParquetMetadataConverter; import org.apache.parquet.hadoop.ParquetFileReader; import org.apache.parquet.hadoop.ParquetReader; import org.apache.parquet.hadoop.ParquetWriter; import org.apache.parquet.hadoop.example.ExampleParquetWriter; import org.apache.parquet.hadoop.example.GroupReadSupport; import org.apache.parquet.hadoop.example.GroupWriteSupport; import org.apache.parquet.hadoop.metadata.BlockMetaData; import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData; import org.apache.parquet.hadoop.metadata.CompressionCodecName; import org.apache.parquet.hadoop.metadata.FileMetaData; import org.apache.parquet.hadoop.metadata.ParquetMetadata; import org.apache.parquet.hadoop.util.CompressionConverter.TransParquetFileReader; import org.apache.parquet.hadoop.util.HadoopInputFile; import org.apache.parquet.internal.column.columnindex.ColumnIndex; import org.apache.parquet.internal.column.columnindex.OffsetIndex; import org.apache.parquet.io.api.Binary; import org.apache.parquet.schema.GroupType; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.OriginalType; import org.apache.parquet.schema.PrimitiveType; import org.apache.parquet.schema.Type; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.stream.Collectors; import static org.apache.hudi.common.model.HoodieRecord.FILENAME_METADATA_FIELD; import static org.apache.parquet.internal.column.columnindex.BoundaryOrder.ASCENDING; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.BINARY; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT32; import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName.INT64; import static org.apache.parquet.schema.Type.Repetition.OPTIONAL; import static org.apache.parquet.schema.Type.Repetition.REPEATED; import static org.apache.parquet.schema.Type.Repetition.REQUIRED; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; public class TestHoodieParquetFileBinaryCopier { private final int numRecord = 1000; private Configuration conf = new Configuration(); private List<TestFile> inputFiles = null; private String outputFile = null; private HoodieParquetFileBinaryCopier writer = null; @BeforeEach public void setUp() { outputFile = TestFileBuilder.createTempFile("test"); } @AfterEach public void after() { if (outputFile != null) { TestFileBuilder.deleteTempFile(outputFile); } if (inputFiles != null) { inputFiles.stream().map(TestFile::getFileName).forEach(TestFileBuilder::deleteTempFile); } } @Test public void testBasic() throws Exception { MessageType schema = createSchema(); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(schema, "GZIP")); inputFiles.add(makeTestFile(schema, "GZIP")); writer = parquetFileBinaryCopier(schema, "GZIP"); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), schema, true); writer.close(); verify(schema, CompressionCodecName.GZIP); } @Test public void testTranslateCodec() throws Exception { MessageType schema = createSchema(); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(schema, "GZIP")); inputFiles.add(makeTestFile(schema, "UNCOMPRESSED")); writer = parquetFileBinaryCopier(schema, "ZSTD"); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), schema, true); writer.close(); verify(schema, CompressionCodecName.ZSTD); } @Test public void testDifferentSchema() throws Exception { MessageType schema1 = new MessageType("schema", new PrimitiveType(OPTIONAL, INT64, "DocId"), new PrimitiveType(REQUIRED, BINARY, "Name"), new PrimitiveType(OPTIONAL, BINARY, "Gender"), new GroupType(OPTIONAL, "Links", new PrimitiveType(REPEATED, BINARY, "Backward"), new PrimitiveType(REPEATED, BINARY, "Forward"))); MessageType schema2 = new MessageType("schema", new PrimitiveType(OPTIONAL, INT64, "DocId"), new PrimitiveType(REQUIRED, BINARY, "Name"), new PrimitiveType(OPTIONAL, BINARY, "Gender")); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(schema1, "UNCOMPRESSED")); inputFiles.add(makeTestFile(schema2, "UNCOMPRESSED")); writer = parquetFileBinaryCopier(schema1, "UNCOMPRESSED"); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), schema1, true); writer.close(); verify(schema1, CompressionCodecName.UNCOMPRESSED); } @Test public void testConvertLegacy3LevelArrayType() throws Exception { MessageType requiredSchema = new MessageType("schema", new PrimitiveType(REQUIRED, BINARY, "Name"), new GroupType(OPTIONAL, "Links", OriginalType.LIST, new GroupType(REPEATED, "list", new PrimitiveType(REPEATED, BINARY, "element")) ) ); MessageType inputSchema = new MessageType("schema", new PrimitiveType(REQUIRED, BINARY, "Name"), new GroupType(OPTIONAL, "Links", OriginalType.LIST, new GroupType(OPTIONAL, "bag", new PrimitiveType(REPEATED, BINARY, "array")) ) ); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(requiredSchema, "GZIP")); inputFiles.add(makeTestFile(inputSchema, "GZIP")); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); writer = parquetFileBinaryCopier(requiredSchema, "GZIP"); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), requiredSchema, true); writer.close(); List<ColumnDescriptor> columns = inputSchema.getColumns(); Assertions.assertEquals(2, columns.size()); verifyColumnConvert(columns.get(0), writer::convertLegacy3LevelArray, false, "Name", "Name"); verifyColumnConvert(columns.get(1), writer::convertLegacy3LevelArray, true, "Links.bag.array", "Links.list.element"); verify(requiredSchema, CompressionCodecName.GZIP); } @Test public void testConvertLegacy3LevelArrayTypeInNestedField() throws Exception { // two column, // column 1: Links is ArrayType with every element is ArrayType // column 1: Map is MapType, key of map is BinaryType and value of map is ArrayType MessageType requiredSchema = new MessageType("schema", new GroupType(OPTIONAL, "Links", OriginalType.LIST, new GroupType(REPEATED, "list", new GroupType(OPTIONAL, "element", OriginalType.LIST, new GroupType(REPEATED, "list", new PrimitiveType(REPEATED, BINARY, "element") ) ) ) ), new GroupType(OPTIONAL, "Map", OriginalType.MAP, new GroupType(REPEATED, "key_value", new PrimitiveType(REQUIRED, BINARY, "key"), new GroupType(OPTIONAL, "value", OriginalType.LIST, new GroupType(REPEATED, "list", new PrimitiveType(REPEATED, BINARY, "element") ) ) ) ) ); MessageType inputSchema = new MessageType("schema", new GroupType(OPTIONAL, "Links", OriginalType.LIST, new GroupType(OPTIONAL, "bag", new GroupType(OPTIONAL, "array", OriginalType.LIST, new GroupType(OPTIONAL, "bag", new PrimitiveType(REPEATED, BINARY, "array") ) ) ) ), new GroupType(OPTIONAL, "Map", OriginalType.MAP, new GroupType(REPEATED, "key_value", new PrimitiveType(REQUIRED, BINARY, "key"), new GroupType(OPTIONAL, "value", OriginalType.LIST, new GroupType(REPEATED, "bag", new PrimitiveType(REPEATED, BINARY, "array") ) ) ) ) ); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(requiredSchema, "GZIP")); inputFiles.add(makeTestFile(inputSchema, "GZIP")); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); writer = parquetFileBinaryCopier(requiredSchema, "GZIP"); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), requiredSchema, true); writer.close(); List<ColumnDescriptor> columns = inputSchema.getColumns(); Assertions.assertEquals(3, columns.size()); verifyColumnConvert(columns.get(0), writer::convertLegacy3LevelArray, true, "Links.bag.array.bag.array", "Links.list.element.list.element"); verifyColumnConvert(columns.get(1), writer::convertLegacy3LevelArray, false, "Map.key_value.key", "Map.key_value.key"); verifyColumnConvert(columns.get(2), writer::convertLegacy3LevelArray, true, "Map.key_value.value.bag.array", "Map.key_value.value.list.element"); verify(requiredSchema, CompressionCodecName.GZIP); } @Test public void testConvertLegacyMapType() throws Exception { MessageType requiredSchema = new MessageType("schema", new PrimitiveType(REQUIRED, BINARY, "Name"), new GroupType(OPTIONAL, "Map", OriginalType.MAP, new GroupType(REPEATED, "key_value", OriginalType.MAP_KEY_VALUE, new PrimitiveType(REQUIRED, BINARY, "key"), new PrimitiveType(OPTIONAL, BINARY, "value") ) ) ); MessageType inputSchema = new MessageType("schema", new PrimitiveType(REQUIRED, BINARY, "Name"), new GroupType(OPTIONAL, "Map", OriginalType.MAP, new GroupType(REPEATED, "map", new PrimitiveType(REQUIRED, BINARY, "key"), new PrimitiveType(OPTIONAL, BINARY, "value") ) ) ); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(requiredSchema, "GZIP")); inputFiles.add(makeTestFile(inputSchema, "GZIP")); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); writer = parquetFileBinaryCopier(requiredSchema, "GZIP"); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), requiredSchema, true); writer.close(); List<ColumnDescriptor> columns = inputSchema.getColumns(); Assertions.assertEquals(3, columns.size()); verifyColumnConvert(columns.get(0), writer::convertLegacyMap, false, "Name", "Name"); verifyColumnConvert(columns.get(1), writer::convertLegacyMap, true, "Map.map.key", "Map.key_value.key"); verifyColumnConvert(columns.get(2), writer::convertLegacyMap, true, "Map.map.value", "Map.key_value.value"); verify(requiredSchema, CompressionCodecName.GZIP); } @Test public void testConvertLegacyMapTypeInNestedField() throws Exception { // two column, // column 1: Links is ArrayType with every element is Map // column 1: Map is MapType, key of map is BinaryType and value of map is Map MessageType requiredSchema = new MessageType("schema", new GroupType(OPTIONAL, "Links", OriginalType.LIST, new GroupType(REPEATED, "list", new GroupType(OPTIONAL, "element", OriginalType.MAP, new GroupType(REPEATED, "key_value", new PrimitiveType(REQUIRED, BINARY, "key"), new PrimitiveType(REPEATED, BINARY, "value") ) ) ) ), new GroupType(OPTIONAL, "Map", OriginalType.MAP, new GroupType(REPEATED, "key_value", new PrimitiveType(REQUIRED, BINARY, "key"), new GroupType(OPTIONAL, "value", OriginalType.MAP, new GroupType(REPEATED, "key_value", new PrimitiveType(REPEATED, BINARY, "key"), new PrimitiveType(REPEATED, BINARY, "value") ) ) ) ) ); MessageType inputSchema = new MessageType("schema", new GroupType(OPTIONAL, "Links", OriginalType.LIST, new GroupType(REPEATED, "list", new GroupType(OPTIONAL, "element", OriginalType.MAP, new GroupType(REPEATED, "map", OriginalType.MAP_KEY_VALUE, new PrimitiveType(REQUIRED, BINARY, "key"), new PrimitiveType(REPEATED, BINARY, "value") ) ) ) ), new GroupType(OPTIONAL, "Map", OriginalType.MAP, new GroupType(REPEATED, "map", OriginalType.MAP_KEY_VALUE, new PrimitiveType(REQUIRED, BINARY, "key"), new GroupType(OPTIONAL, "value", OriginalType.MAP, new GroupType(REPEATED, "map", OriginalType.MAP_KEY_VALUE, new PrimitiveType(REPEATED, BINARY, "key"), new PrimitiveType(REPEATED, BINARY, "value") ) ) ) ) ); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(requiredSchema, "GZIP")); inputFiles.add(makeTestFile(inputSchema, "GZIP")); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); writer = parquetFileBinaryCopier(requiredSchema, "GZIP"); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), requiredSchema, true); writer.close(); List<ColumnDescriptor> columns = inputSchema.getColumns(); Assertions.assertEquals(5, columns.size()); verifyColumnConvert(columns.get(0), writer::convertLegacyMap, true, "Links.list.element.map.key", "Links.list.element.key_value.key"); verifyColumnConvert(columns.get(1), writer::convertLegacyMap, true, "Links.list.element.map.value", "Links.list.element.key_value.value"); verifyColumnConvert(columns.get(2), writer::convertLegacyMap, true, "Map.map.key", "Map.key_value.key"); verifyColumnConvert(columns.get(3), writer::convertLegacyMap, true, "Map.map.value.map.key", "Map.key_value.value.key_value.key"); verifyColumnConvert(columns.get(4), writer::convertLegacyMap, true, "Map.map.value.map.value", "Map.key_value.value.key_value.value"); verify(requiredSchema, CompressionCodecName.GZIP); } @Test public void testHoodieMetaColumn() throws Exception { MessageType schema = new MessageType("schema", new PrimitiveType(OPTIONAL, BINARY, FILENAME_METADATA_FIELD), new PrimitiveType(OPTIONAL, INT64, "DocId"), new PrimitiveType(REQUIRED, BINARY, "Name"), new PrimitiveType(OPTIONAL, BINARY, "Gender"), new GroupType(OPTIONAL, "Links", new PrimitiveType(REPEATED, BINARY, "Backward"), new PrimitiveType(REPEATED, BINARY, "Forward"))); inputFiles = new ArrayList<>(); inputFiles.add(makeTestFile(schema, "GZIP")); inputFiles.add(makeTestFile(schema, "GZIP")); writer = parquetFileBinaryCopier(schema, "GZIP"); List<StoragePath> inputPaths = inputFiles.stream() .map(TestFile::getFileName) .map(StoragePath::new) .collect(Collectors.toList()); StoragePath outputPath = new StoragePath(outputFile); writer.binaryCopy(inputPaths, Collections.singletonList(outputPath), schema, true); writer.close(); verify(schema, CompressionCodecName.GZIP); } private TestFile makeTestFile(MessageType schema, String codec) throws IOException { return new TestFileBuilder(conf, schema) .withNumRecord(numRecord) .withCodec(codec) .withPageSize(ParquetProperties.DEFAULT_PAGE_SIZE) .build(); } private HoodieParquetFileBinaryCopier parquetFileBinaryCopier(MessageType schema, String codec) { CompressionCodecName codecName = CompressionCodecName.fromConf(codec); HoodieFileMetadataMerger metadataMerger = new HoodieFileMetadataMerger(); return new HoodieParquetFileBinaryCopier(conf, codecName, metadataMerger); } private MessageType createSchema() { return new MessageType("schema", new PrimitiveType(OPTIONAL, INT64, "DocId"), new PrimitiveType(REQUIRED, BINARY, "Name"), new PrimitiveType(OPTIONAL, BINARY, "Gender"), new GroupType(OPTIONAL, "Links", new PrimitiveType(REPEATED, BINARY, "Backward"), new PrimitiveType(REPEATED, BINARY, "Forward"))); } private void validateColumnData(MessageType requiredSchema) throws IOException { Path outputFilePath = new Path(outputFile); ParquetReader<Group> reader = ParquetReader.builder(new GroupReadSupport(), outputFilePath) .withConf(conf) .build(); // Get total number of rows from input files int totalRows = 0; for (TestFile inputFile : inputFiles) { totalRows += inputFile.getFileContent().length; } for (int i = 0; i < totalRows; i++) { Group group = reader.read(); assertNotNull(group); SimpleGroup expectGroup = inputFiles.get(i / numRecord).getFileContent()[i % numRecord]; checkField(requiredSchema, expectGroup, group); } reader.close(); } private void checkField(GroupType schema, Group expectGroup, Group actualGroup) { for (int i = 0; i < schema.getFieldCount(); i++) { if (expectGroup.getType().getFieldCount() - 1 < i) { assertEquals(0, actualGroup.getFieldRepetitionCount(i)); continue; } Type type = schema.getType(i); if (FILENAME_METADATA_FIELD.equals(type.getName())) { Path outputFilePath = new Path(outputFile); assertEquals(outputFilePath.getName(), actualGroup.getString(FILENAME_METADATA_FIELD, 0)); assertNotEquals(actualGroup.getString(FILENAME_METADATA_FIELD, 0), expectGroup.getString(FILENAME_METADATA_FIELD, 0)); continue; } if (type.isPrimitive()) { PrimitiveType primitiveType = (PrimitiveType) type; if (primitiveType.getPrimitiveTypeName().equals(INT32)) { assertEquals(expectGroup.getInteger(i, 0), actualGroup.getInteger(i, 0)); } else if (primitiveType.getPrimitiveTypeName().equals(INT64)) { assertEquals(expectGroup.getLong(i, 0), actualGroup.getLong(i, 0)); } else if (primitiveType.getPrimitiveTypeName().equals(BINARY)) { assertEquals(expectGroup.getString(i, 0), actualGroup.getString(i, 0)); } } else { GroupType groupType = (GroupType) type; checkField(groupType, expectGroup.getGroup(i, 0), actualGroup.getGroup(i, 0)); } } } private ParquetMetadata getFileMetaData(String file) throws IOException { return ParquetFileReader.readFooter(conf, new Path(file)); } private void verify(MessageType requiredSchema, CompressionCodecName expectedCodec) throws Exception { // Verify the schema are not changed for the columns not pruned ParquetMetadata pmd = ParquetFileReader.readFooter(conf, new Path(outputFile), ParquetMetadataConverter.NO_FILTER); MessageType fileSchema = pmd.getFileMetaData().getSchema(); assertEquals(requiredSchema, fileSchema); // Verify codec has been translated verifyCodec(outputFile, expectedCodec); // Verify the data are not changed validateColumnData(requiredSchema); // Verify the page index validatePageIndex(requiredSchema); // Verify original.created.by is preserved validateCreatedBy(); } private void verifyCodec(String file, CompressionCodecName expectedCodecs) throws IOException { Set<CompressionCodecName> codecs = new HashSet<>(); ParquetMetadata pmd = getFileMetaData(file); for (int i = 0; i < pmd.getBlocks().size(); i++) { BlockMetaData block = pmd.getBlocks().get(i); for (int j = 0; j < block.getColumns().size(); ++j) { ColumnChunkMetaData columnChunkMetaData = block.getColumns().get(j); codecs.add(columnChunkMetaData.getCodec()); } } assertEquals(new HashSet<CompressionCodecName>() { { add(expectedCodecs); } }, codecs); } /** * Verify the page index is correct. * * @param columnIdxs the idx of column to be validated. */ private void validatePageIndex(MessageType requiredSchema) throws Exception { ParquetMetadata outMetaData = getFileMetaData(outputFile); int inputFileIndex = 0; TransParquetFileReader inReader = new TransParquetFileReader( HadoopInputFile.fromPath(new Path(inputFiles.get(inputFileIndex).getFileName()), conf), HadoopReadOptions.builder(conf).build() ); ParquetMetadata inMetaData = inReader.getFooter(); Path outputFilePath = new Path(outputFile); try (TransParquetFileReader outReader = new TransParquetFileReader( HadoopInputFile.fromPath(outputFilePath, conf), HadoopReadOptions.builder(conf).build())) { for (int outBlockId = 0, inBlockId = 0; outBlockId < outMetaData.getBlocks().size(); ++outBlockId, ++inBlockId) { // Refresh reader of input file if (inBlockId == inMetaData.getBlocks().size()) { inReader = new TransParquetFileReader( HadoopInputFile.fromPath(new Path(inputFiles.get(++inputFileIndex).getFileName()), conf), HadoopReadOptions.builder(conf).build()); inMetaData = inReader.getFooter(); inBlockId = 0; } BlockMetaData inBlockMetaData = inMetaData.getBlocks().get(inBlockId); BlockMetaData outBlockMetaData = outMetaData.getBlocks().get(outBlockId); int inputColumns = inBlockMetaData.getColumns().size(); List<Type> fields = requiredSchema.getFields(); for (int i = 0; i < fields.size(); i++) { ColumnChunkMetaData outChunk = outBlockMetaData.getColumns().get(i); ColumnIndex outColumnIndex = outReader.readColumnIndex(outChunk); OffsetIndex outOffsetIndex = outReader.readOffsetIndex(outChunk); if (inputColumns - 1 < i) { assertEquals(ASCENDING, outColumnIndex.getBoundaryOrder()); assertEquals(1, outColumnIndex.getNullCounts().size()); assertEquals(outChunk.getValueCount(), outColumnIndex.getNullCounts().get(0)); List<Long> outOffsets = getOffsets(outReader, outChunk); assertEquals(outOffsetIndex.getPageCount(), outOffsets.size()); for (int k = 0; k < outOffsetIndex.getPageCount(); k++) { assertEquals(outOffsetIndex.getOffset(k), (long) outOffsets.get(k)); } continue; } ColumnChunkMetaData inChunk = inBlockMetaData.getColumns().get(i); ColumnIndex inColumnIndex = inReader.readColumnIndex(inChunk); OffsetIndex inOffsetIndex = inReader.readOffsetIndex(inChunk); if (outChunk.getPath().toDotString().equals(FILENAME_METADATA_FIELD)) { assertEquals(ASCENDING, outColumnIndex.getBoundaryOrder()); assertEquals(1, outColumnIndex.getNullCounts().size()); assertEquals(0, outColumnIndex.getNullCounts().get(0)); assertEquals(outputFilePath.getName(), Binary.fromReusedByteBuffer(outColumnIndex.getMaxValues().get(0)).toStringUsingUTF8()); assertEquals(outputFilePath.getName(), Binary.fromReusedByteBuffer(outColumnIndex.getMinValues().get(0)).toStringUsingUTF8()); List<Long> outOffsets = getOffsets(outReader, outChunk); assertEquals(outOffsetIndex.getPageCount(), outOffsets.size()); for (int k = 0; k < outOffsetIndex.getPageCount(); k++) { assertEquals(outOffsetIndex.getOffset(k), (long) outOffsets.get(k)); } continue; } if (inColumnIndex != null) { assertEquals(inColumnIndex.getBoundaryOrder(), outColumnIndex.getBoundaryOrder()); assertEquals(inColumnIndex.getMaxValues(), outColumnIndex.getMaxValues()); assertEquals(inColumnIndex.getMinValues(), outColumnIndex.getMinValues()); assertEquals(inColumnIndex.getNullCounts(), outColumnIndex.getNullCounts()); } if (inOffsetIndex != null) { List<Long> inOffsets = getOffsets(inReader, inChunk); List<Long> outOffsets = getOffsets(outReader, outChunk); assertEquals(inOffsets.size(), outOffsets.size()); assertEquals(inOffsets.size(), inOffsetIndex.getPageCount()); assertEquals(inOffsetIndex.getPageCount(), outOffsetIndex.getPageCount()); for (int k = 0; k < inOffsetIndex.getPageCount(); k++) { assertEquals(inOffsetIndex.getFirstRowIndex(k), outOffsetIndex.getFirstRowIndex(k)); assertEquals(inOffsetIndex.getLastRowIndex(k, inChunk.getValueCount()), outOffsetIndex.getLastRowIndex(k, outChunk.getValueCount())); assertEquals(inOffsetIndex.getOffset(k), (long) inOffsets.get(k)); assertEquals(outOffsetIndex.getOffset(k), (long) outOffsets.get(k)); } } } } } } private List<Long> getOffsets(TransParquetFileReader reader, ColumnChunkMetaData chunk) throws IOException { List<Long> offsets = new ArrayList<>(); reader.setStreamPosition(chunk.getStartingPos()); long readValues = 0; long totalChunkValues = chunk.getValueCount(); while (readValues < totalChunkValues) { long curOffset = reader.getPos(); PageHeader pageHeader = reader.readPageHeader(); switch (pageHeader.type) { case DICTIONARY_PAGE: writer.readBlock(pageHeader.getCompressed_page_size(), reader); break; case DATA_PAGE: DataPageHeader headerV1 = pageHeader.data_page_header; offsets.add(curOffset); writer.readBlock(pageHeader.getCompressed_page_size(), reader); readValues += headerV1.getNum_values(); break; case DATA_PAGE_V2: DataPageHeaderV2 headerV2 = pageHeader.data_page_header_v2; offsets.add(curOffset); int rlLength = headerV2.getRepetition_levels_byte_length(); writer.readBlock(rlLength, reader); int dlLength = headerV2.getDefinition_levels_byte_length(); writer.readBlock(dlLength, reader); int payLoadLength = pageHeader.getCompressed_page_size() - rlLength - dlLength; writer.readBlock(payLoadLength, reader); readValues += headerV2.getNum_values(); break; default: throw new IOException("Not recognized page type"); } } return offsets; } private void validateCreatedBy() throws Exception { Set<String> createdBySet = new HashSet<>(); for (TestFile inputFile : inputFiles) { ParquetMetadata pmd = getFileMetaData(inputFile.getFileName()); createdBySet.add(pmd.getFileMetaData().getCreatedBy()); assertNull(pmd.getFileMetaData().getKeyValueMetaData().get(HoodieParquetFileBinaryCopier.ORIGINAL_CREATED_BY_KEY)); } // Verify created_by from input files have been deduplicated Object[] inputCreatedBys = createdBySet.toArray(); assertEquals(1, inputCreatedBys.length); // Verify created_by has been set FileMetaData outFMD = getFileMetaData(outputFile).getFileMetaData(); final String createdBy = outFMD.getCreatedBy(); assertNotNull(createdBy); assertEquals(createdBy, Version.FULL_VERSION); // Verify original.created.by has been set String inputCreatedBy = (String) inputCreatedBys[0]; String originalCreatedBy = outFMD.getKeyValueMetaData().get(HoodieParquetFileBinaryCopier.ORIGINAL_CREATED_BY_KEY); assertEquals(inputCreatedBy, originalCreatedBy); } public static class TestFileBuilder { private MessageType schema; private Configuration conf; private Map<String, String> extraMeta = new HashMap<>(); private int numRecord = 100000; private ParquetProperties.WriterVersion writerVersion = ParquetProperties.WriterVersion.PARQUET_1_0; private int pageSize = ParquetProperties.DEFAULT_PAGE_SIZE; private String codec = "ZSTD"; private String[] encryptColumns = {}; private ParquetCipher cipher = ParquetCipher.AES_GCM_V1; private Boolean footerEncryption = false; public TestFileBuilder(Configuration conf, MessageType schema) { this.conf = conf; this.schema = schema; conf.set(GroupWriteSupport.PARQUET_EXAMPLE_SCHEMA, schema.toString()); } public TestFileBuilder withNumRecord(int numRecord) { this.numRecord = numRecord; return this; } public TestFileBuilder withEncrytionAlgorithm(ParquetCipher cipher) { this.cipher = cipher; return this; } public TestFileBuilder withExtraMeta(Map<String, String> extraMeta) { this.extraMeta = extraMeta; return this; } public TestFileBuilder withWriterVersion(ParquetProperties.WriterVersion writerVersion) { this.writerVersion = writerVersion; return this; } public TestFileBuilder withPageSize(int pageSize) { this.pageSize = pageSize; return this; } public TestFileBuilder withCodec(String codec) { this.codec = codec; return this; } public TestFileBuilder withEncryptColumns(String[] encryptColumns) { this.encryptColumns = encryptColumns; return this; } public TestFileBuilder withFooterEncryption() { this.footerEncryption = true; return this; } public TestFile build() throws IOException { String fileName = createTempFile("test"); SimpleGroup[] fileContent = createFileContent(schema); ExampleParquetWriter.Builder builder = ExampleParquetWriter.builder(new Path(fileName)) .withConf(conf) .withWriterVersion(writerVersion) .withExtraMetaData(extraMeta) .withValidation(true) .withPageSize(pageSize) .withCompressionCodec(CompressionCodecName.valueOf(codec)); try (ParquetWriter writer = builder.build()) { for (int i = 0; i < fileContent.length; i++) { writer.write(fileContent[i]); } } return new TestFile(fileName, fileContent); } private SimpleGroup[] createFileContent(MessageType schema) { SimpleGroup[] simpleGroups = new SimpleGroup[numRecord]; for (int i = 0; i < simpleGroups.length; i++) { SimpleGroup g = new SimpleGroup(schema); for (Type type : schema.getFields()) { addValueToSimpleGroup(g, type); } simpleGroups[i] = g; } return simpleGroups; } private void addValueToSimpleGroup(Group g, Type type) { if (type.isPrimitive()) { PrimitiveType primitiveType = (PrimitiveType) type; if (primitiveType.getPrimitiveTypeName().equals(INT32)) { g.add(type.getName(), getInt()); } else if (primitiveType.getPrimitiveTypeName().equals(INT64)) { g.add(type.getName(), getLong()); } else if (primitiveType.getPrimitiveTypeName().equals(BINARY)) { g.add(type.getName(), getString()); } // Only support 3 types now, more can be added later } else { GroupType groupType = (GroupType) type; Group parentGroup = g.addGroup(groupType.getName()); for (Type field : groupType.getFields()) { addValueToSimpleGroup(parentGroup, field); } } } private static long getInt() { return ThreadLocalRandom.current().nextInt(10000); } private static long getLong() { return ThreadLocalRandom.current().nextLong(100000); } private static String getString() { char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'x', 'z', 'y'}; StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.append(chars[ThreadLocalRandom.current().nextInt(10)]); } return sb.toString(); } public static String createTempFile(String prefix) { try { return Files.createTempDirectory(prefix).toAbsolutePath().toString() + "/test.parquet"; } catch (IOException e) { throw new AssertionError("Unable to create temporary file", e); } } public static void deleteTempFile(String file) { try { Files.delete(Paths.get(file)); } catch (IOException e) { e.printStackTrace(); } } } public static class TestFile { private final String fileName; private final SimpleGroup[] fileContent; public TestFile(String fileName, SimpleGroup[] fileContent) { this.fileName = fileName; this.fileContent = fileContent; } public String getFileName() { return this.fileName; } public SimpleGroup[] getFileContent() { return this.fileContent; } } private void verifyColumnConvert( ColumnDescriptor column, Function<String[], Boolean> converter, Boolean changed, String originalPathStr, String convertedPathStr) { String[] path = column.getPath(); String[] originalPath = Arrays.copyOf(path, path.length); assertEquals(changed, converter.apply(path)); assertEquals(originalPathStr, pathToString(originalPath)); assertEquals(convertedPathStr, pathToString(path)); } private String pathToString(String[] path) { return Arrays.stream(path).collect(Collectors.joining(".")); } }
google/schemaorg-java
36,676
src/main/java/com/google/schemaorg/core/impl/MusicGroupImpl.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.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.schemaorg.SchemaOrgType; import com.google.schemaorg.SchemaOrgTypeImpl; import com.google.schemaorg.ValueType; import com.google.schemaorg.core.datatype.Date; import com.google.schemaorg.core.datatype.Text; import com.google.schemaorg.core.datatype.URL; import com.google.schemaorg.goog.GoogConstants; import com.google.schemaorg.goog.PopularityScoreSpecification; /** Implementation of {@link MusicGroup}. */ public class MusicGroupImpl extends PerformingGroupImpl implements MusicGroup { private static final ImmutableSet<String> PROPERTY_SET = initializePropertySet(); private static ImmutableSet<String> initializePropertySet() { ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.add(CoreConstants.PROPERTY_ADDITIONAL_TYPE); builder.add(CoreConstants.PROPERTY_ADDRESS); builder.add(CoreConstants.PROPERTY_AGGREGATE_RATING); builder.add(CoreConstants.PROPERTY_ALBUM); builder.add(CoreConstants.PROPERTY_ALBUMS); builder.add(CoreConstants.PROPERTY_ALTERNATE_NAME); builder.add(CoreConstants.PROPERTY_ALUMNI); builder.add(CoreConstants.PROPERTY_AREA_SERVED); builder.add(CoreConstants.PROPERTY_AWARD); builder.add(CoreConstants.PROPERTY_AWARDS); builder.add(CoreConstants.PROPERTY_BRAND); builder.add(CoreConstants.PROPERTY_CONTACT_POINT); builder.add(CoreConstants.PROPERTY_CONTACT_POINTS); builder.add(CoreConstants.PROPERTY_DEPARTMENT); builder.add(CoreConstants.PROPERTY_DESCRIPTION); builder.add(CoreConstants.PROPERTY_DISSOLUTION_DATE); builder.add(CoreConstants.PROPERTY_DUNS); builder.add(CoreConstants.PROPERTY_EMAIL); builder.add(CoreConstants.PROPERTY_EMPLOYEE); builder.add(CoreConstants.PROPERTY_EMPLOYEES); builder.add(CoreConstants.PROPERTY_EVENT); builder.add(CoreConstants.PROPERTY_EVENTS); builder.add(CoreConstants.PROPERTY_FAX_NUMBER); builder.add(CoreConstants.PROPERTY_FOUNDER); builder.add(CoreConstants.PROPERTY_FOUNDERS); builder.add(CoreConstants.PROPERTY_FOUNDING_DATE); builder.add(CoreConstants.PROPERTY_FOUNDING_LOCATION); builder.add(CoreConstants.PROPERTY_GENRE); builder.add(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER); builder.add(CoreConstants.PROPERTY_HAS_OFFER_CATALOG); builder.add(CoreConstants.PROPERTY_HAS_POS); builder.add(CoreConstants.PROPERTY_IMAGE); builder.add(CoreConstants.PROPERTY_ISIC_V4); builder.add(CoreConstants.PROPERTY_LEGAL_NAME); builder.add(CoreConstants.PROPERTY_LOCATION); builder.add(CoreConstants.PROPERTY_LOGO); builder.add(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE); builder.add(CoreConstants.PROPERTY_MAKES_OFFER); builder.add(CoreConstants.PROPERTY_MEMBER); builder.add(CoreConstants.PROPERTY_MEMBER_OF); builder.add(CoreConstants.PROPERTY_MEMBERS); builder.add(CoreConstants.PROPERTY_MUSIC_GROUP_MEMBER); builder.add(CoreConstants.PROPERTY_NAICS); builder.add(CoreConstants.PROPERTY_NAME); builder.add(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES); builder.add(CoreConstants.PROPERTY_OWNS); builder.add(CoreConstants.PROPERTY_PARENT_ORGANIZATION); builder.add(CoreConstants.PROPERTY_POTENTIAL_ACTION); builder.add(CoreConstants.PROPERTY_REVIEW); builder.add(CoreConstants.PROPERTY_REVIEWS); builder.add(CoreConstants.PROPERTY_SAME_AS); builder.add(CoreConstants.PROPERTY_SEEKS); builder.add(CoreConstants.PROPERTY_SERVICE_AREA); builder.add(CoreConstants.PROPERTY_SUB_ORGANIZATION); builder.add(CoreConstants.PROPERTY_TAX_ID); builder.add(CoreConstants.PROPERTY_TELEPHONE); builder.add(CoreConstants.PROPERTY_TRACK); builder.add(CoreConstants.PROPERTY_TRACKS); builder.add(CoreConstants.PROPERTY_URL); builder.add(CoreConstants.PROPERTY_VAT_ID); builder.add(GoogConstants.PROPERTY_DETAILED_DESCRIPTION); builder.add(GoogConstants.PROPERTY_POPULARITY_SCORE); return builder.build(); } static final class BuilderImpl extends SchemaOrgTypeImpl.BuilderImpl<MusicGroup.Builder> implements MusicGroup.Builder { @Override public MusicGroup.Builder addAdditionalType(URL value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, value); } @Override public MusicGroup.Builder addAdditionalType(String value) { return addProperty(CoreConstants.PROPERTY_ADDITIONAL_TYPE, Text.of(value)); } @Override public MusicGroup.Builder addAddress(PostalAddress value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, value); } @Override public MusicGroup.Builder addAddress(PostalAddress.Builder value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, value.build()); } @Override public MusicGroup.Builder addAddress(Text value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, value); } @Override public MusicGroup.Builder addAddress(String value) { return addProperty(CoreConstants.PROPERTY_ADDRESS, Text.of(value)); } @Override public MusicGroup.Builder addAggregateRating(AggregateRating value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value); } @Override public MusicGroup.Builder addAggregateRating(AggregateRating.Builder value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, value.build()); } @Override public MusicGroup.Builder addAggregateRating(String value) { return addProperty(CoreConstants.PROPERTY_AGGREGATE_RATING, Text.of(value)); } @Override public MusicGroup.Builder addAlbum(MusicAlbum value) { return addProperty(CoreConstants.PROPERTY_ALBUM, value); } @Override public MusicGroup.Builder addAlbum(MusicAlbum.Builder value) { return addProperty(CoreConstants.PROPERTY_ALBUM, value.build()); } @Override public MusicGroup.Builder addAlbum(String value) { return addProperty(CoreConstants.PROPERTY_ALBUM, Text.of(value)); } @Override public MusicGroup.Builder addAlbums(MusicAlbum value) { return addProperty(CoreConstants.PROPERTY_ALBUMS, value); } @Override public MusicGroup.Builder addAlbums(MusicAlbum.Builder value) { return addProperty(CoreConstants.PROPERTY_ALBUMS, value.build()); } @Override public MusicGroup.Builder addAlbums(String value) { return addProperty(CoreConstants.PROPERTY_ALBUMS, Text.of(value)); } @Override public MusicGroup.Builder addAlternateName(Text value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, value); } @Override public MusicGroup.Builder addAlternateName(String value) { return addProperty(CoreConstants.PROPERTY_ALTERNATE_NAME, Text.of(value)); } @Override public MusicGroup.Builder addAlumni(Person value) { return addProperty(CoreConstants.PROPERTY_ALUMNI, value); } @Override public MusicGroup.Builder addAlumni(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_ALUMNI, value.build()); } @Override public MusicGroup.Builder addAlumni(String value) { return addProperty(CoreConstants.PROPERTY_ALUMNI, Text.of(value)); } @Override public MusicGroup.Builder addAreaServed(AdministrativeArea value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value); } @Override public MusicGroup.Builder addAreaServed(AdministrativeArea.Builder value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value.build()); } @Override public MusicGroup.Builder addAreaServed(GeoShape value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value); } @Override public MusicGroup.Builder addAreaServed(GeoShape.Builder value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value.build()); } @Override public MusicGroup.Builder addAreaServed(Place value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value); } @Override public MusicGroup.Builder addAreaServed(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value.build()); } @Override public MusicGroup.Builder addAreaServed(Text value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, value); } @Override public MusicGroup.Builder addAreaServed(String value) { return addProperty(CoreConstants.PROPERTY_AREA_SERVED, Text.of(value)); } @Override public MusicGroup.Builder addAward(Text value) { return addProperty(CoreConstants.PROPERTY_AWARD, value); } @Override public MusicGroup.Builder addAward(String value) { return addProperty(CoreConstants.PROPERTY_AWARD, Text.of(value)); } @Override public MusicGroup.Builder addAwards(Text value) { return addProperty(CoreConstants.PROPERTY_AWARDS, value); } @Override public MusicGroup.Builder addAwards(String value) { return addProperty(CoreConstants.PROPERTY_AWARDS, Text.of(value)); } @Override public MusicGroup.Builder addBrand(Brand value) { return addProperty(CoreConstants.PROPERTY_BRAND, value); } @Override public MusicGroup.Builder addBrand(Brand.Builder value) { return addProperty(CoreConstants.PROPERTY_BRAND, value.build()); } @Override public MusicGroup.Builder addBrand(Organization value) { return addProperty(CoreConstants.PROPERTY_BRAND, value); } @Override public MusicGroup.Builder addBrand(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_BRAND, value.build()); } @Override public MusicGroup.Builder addBrand(String value) { return addProperty(CoreConstants.PROPERTY_BRAND, Text.of(value)); } @Override public MusicGroup.Builder addContactPoint(ContactPoint value) { return addProperty(CoreConstants.PROPERTY_CONTACT_POINT, value); } @Override public MusicGroup.Builder addContactPoint(ContactPoint.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTACT_POINT, value.build()); } @Override public MusicGroup.Builder addContactPoint(String value) { return addProperty(CoreConstants.PROPERTY_CONTACT_POINT, Text.of(value)); } @Override public MusicGroup.Builder addContactPoints(ContactPoint value) { return addProperty(CoreConstants.PROPERTY_CONTACT_POINTS, value); } @Override public MusicGroup.Builder addContactPoints(ContactPoint.Builder value) { return addProperty(CoreConstants.PROPERTY_CONTACT_POINTS, value.build()); } @Override public MusicGroup.Builder addContactPoints(String value) { return addProperty(CoreConstants.PROPERTY_CONTACT_POINTS, Text.of(value)); } @Override public MusicGroup.Builder addDepartment(Organization value) { return addProperty(CoreConstants.PROPERTY_DEPARTMENT, value); } @Override public MusicGroup.Builder addDepartment(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_DEPARTMENT, value.build()); } @Override public MusicGroup.Builder addDepartment(String value) { return addProperty(CoreConstants.PROPERTY_DEPARTMENT, Text.of(value)); } @Override public MusicGroup.Builder addDescription(Text value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, value); } @Override public MusicGroup.Builder addDescription(String value) { return addProperty(CoreConstants.PROPERTY_DESCRIPTION, Text.of(value)); } @Override public MusicGroup.Builder addDissolutionDate(Date value) { return addProperty(CoreConstants.PROPERTY_DISSOLUTION_DATE, value); } @Override public MusicGroup.Builder addDissolutionDate(String value) { return addProperty(CoreConstants.PROPERTY_DISSOLUTION_DATE, Text.of(value)); } @Override public MusicGroup.Builder addDuns(Text value) { return addProperty(CoreConstants.PROPERTY_DUNS, value); } @Override public MusicGroup.Builder addDuns(String value) { return addProperty(CoreConstants.PROPERTY_DUNS, Text.of(value)); } @Override public MusicGroup.Builder addEmail(Text value) { return addProperty(CoreConstants.PROPERTY_EMAIL, value); } @Override public MusicGroup.Builder addEmail(String value) { return addProperty(CoreConstants.PROPERTY_EMAIL, Text.of(value)); } @Override public MusicGroup.Builder addEmployee(Person value) { return addProperty(CoreConstants.PROPERTY_EMPLOYEE, value); } @Override public MusicGroup.Builder addEmployee(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_EMPLOYEE, value.build()); } @Override public MusicGroup.Builder addEmployee(String value) { return addProperty(CoreConstants.PROPERTY_EMPLOYEE, Text.of(value)); } @Override public MusicGroup.Builder addEmployees(Person value) { return addProperty(CoreConstants.PROPERTY_EMPLOYEES, value); } @Override public MusicGroup.Builder addEmployees(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_EMPLOYEES, value.build()); } @Override public MusicGroup.Builder addEmployees(String value) { return addProperty(CoreConstants.PROPERTY_EMPLOYEES, Text.of(value)); } @Override public MusicGroup.Builder addEvent(Event value) { return addProperty(CoreConstants.PROPERTY_EVENT, value); } @Override public MusicGroup.Builder addEvent(Event.Builder value) { return addProperty(CoreConstants.PROPERTY_EVENT, value.build()); } @Override public MusicGroup.Builder addEvent(String value) { return addProperty(CoreConstants.PROPERTY_EVENT, Text.of(value)); } @Override public MusicGroup.Builder addEvents(Event value) { return addProperty(CoreConstants.PROPERTY_EVENTS, value); } @Override public MusicGroup.Builder addEvents(Event.Builder value) { return addProperty(CoreConstants.PROPERTY_EVENTS, value.build()); } @Override public MusicGroup.Builder addEvents(String value) { return addProperty(CoreConstants.PROPERTY_EVENTS, Text.of(value)); } @Override public MusicGroup.Builder addFaxNumber(Text value) { return addProperty(CoreConstants.PROPERTY_FAX_NUMBER, value); } @Override public MusicGroup.Builder addFaxNumber(String value) { return addProperty(CoreConstants.PROPERTY_FAX_NUMBER, Text.of(value)); } @Override public MusicGroup.Builder addFounder(Person value) { return addProperty(CoreConstants.PROPERTY_FOUNDER, value); } @Override public MusicGroup.Builder addFounder(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_FOUNDER, value.build()); } @Override public MusicGroup.Builder addFounder(String value) { return addProperty(CoreConstants.PROPERTY_FOUNDER, Text.of(value)); } @Override public MusicGroup.Builder addFounders(Person value) { return addProperty(CoreConstants.PROPERTY_FOUNDERS, value); } @Override public MusicGroup.Builder addFounders(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_FOUNDERS, value.build()); } @Override public MusicGroup.Builder addFounders(String value) { return addProperty(CoreConstants.PROPERTY_FOUNDERS, Text.of(value)); } @Override public MusicGroup.Builder addFoundingDate(Date value) { return addProperty(CoreConstants.PROPERTY_FOUNDING_DATE, value); } @Override public MusicGroup.Builder addFoundingDate(String value) { return addProperty(CoreConstants.PROPERTY_FOUNDING_DATE, Text.of(value)); } @Override public MusicGroup.Builder addFoundingLocation(Place value) { return addProperty(CoreConstants.PROPERTY_FOUNDING_LOCATION, value); } @Override public MusicGroup.Builder addFoundingLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_FOUNDING_LOCATION, value.build()); } @Override public MusicGroup.Builder addFoundingLocation(String value) { return addProperty(CoreConstants.PROPERTY_FOUNDING_LOCATION, Text.of(value)); } @Override public MusicGroup.Builder addGenre(Text value) { return addProperty(CoreConstants.PROPERTY_GENRE, value); } @Override public MusicGroup.Builder addGenre(URL value) { return addProperty(CoreConstants.PROPERTY_GENRE, value); } @Override public MusicGroup.Builder addGenre(String value) { return addProperty(CoreConstants.PROPERTY_GENRE, Text.of(value)); } @Override public MusicGroup.Builder addGlobalLocationNumber(Text value) { return addProperty(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER, value); } @Override public MusicGroup.Builder addGlobalLocationNumber(String value) { return addProperty(CoreConstants.PROPERTY_GLOBAL_LOCATION_NUMBER, Text.of(value)); } @Override public MusicGroup.Builder addHasOfferCatalog(OfferCatalog value) { return addProperty(CoreConstants.PROPERTY_HAS_OFFER_CATALOG, value); } @Override public MusicGroup.Builder addHasOfferCatalog(OfferCatalog.Builder value) { return addProperty(CoreConstants.PROPERTY_HAS_OFFER_CATALOG, value.build()); } @Override public MusicGroup.Builder addHasOfferCatalog(String value) { return addProperty(CoreConstants.PROPERTY_HAS_OFFER_CATALOG, Text.of(value)); } @Override public MusicGroup.Builder addHasPOS(Place value) { return addProperty(CoreConstants.PROPERTY_HAS_POS, value); } @Override public MusicGroup.Builder addHasPOS(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_HAS_POS, value.build()); } @Override public MusicGroup.Builder addHasPOS(String value) { return addProperty(CoreConstants.PROPERTY_HAS_POS, Text.of(value)); } @Override public MusicGroup.Builder addImage(ImageObject value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public MusicGroup.Builder addImage(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value.build()); } @Override public MusicGroup.Builder addImage(URL value) { return addProperty(CoreConstants.PROPERTY_IMAGE, value); } @Override public MusicGroup.Builder addImage(String value) { return addProperty(CoreConstants.PROPERTY_IMAGE, Text.of(value)); } @Override public MusicGroup.Builder addIsicV4(Text value) { return addProperty(CoreConstants.PROPERTY_ISIC_V4, value); } @Override public MusicGroup.Builder addIsicV4(String value) { return addProperty(CoreConstants.PROPERTY_ISIC_V4, Text.of(value)); } @Override public MusicGroup.Builder addLegalName(Text value) { return addProperty(CoreConstants.PROPERTY_LEGAL_NAME, value); } @Override public MusicGroup.Builder addLegalName(String value) { return addProperty(CoreConstants.PROPERTY_LEGAL_NAME, Text.of(value)); } @Override public MusicGroup.Builder addLocation(Place value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public MusicGroup.Builder addLocation(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value.build()); } @Override public MusicGroup.Builder addLocation(PostalAddress value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public MusicGroup.Builder addLocation(PostalAddress.Builder value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value.build()); } @Override public MusicGroup.Builder addLocation(Text value) { return addProperty(CoreConstants.PROPERTY_LOCATION, value); } @Override public MusicGroup.Builder addLocation(String value) { return addProperty(CoreConstants.PROPERTY_LOCATION, Text.of(value)); } @Override public MusicGroup.Builder addLogo(ImageObject value) { return addProperty(CoreConstants.PROPERTY_LOGO, value); } @Override public MusicGroup.Builder addLogo(ImageObject.Builder value) { return addProperty(CoreConstants.PROPERTY_LOGO, value.build()); } @Override public MusicGroup.Builder addLogo(URL value) { return addProperty(CoreConstants.PROPERTY_LOGO, value); } @Override public MusicGroup.Builder addLogo(String value) { return addProperty(CoreConstants.PROPERTY_LOGO, Text.of(value)); } @Override public MusicGroup.Builder addMainEntityOfPage(CreativeWork value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public MusicGroup.Builder addMainEntityOfPage(CreativeWork.Builder value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value.build()); } @Override public MusicGroup.Builder addMainEntityOfPage(URL value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, value); } @Override public MusicGroup.Builder addMainEntityOfPage(String value) { return addProperty(CoreConstants.PROPERTY_MAIN_ENTITY_OF_PAGE, Text.of(value)); } @Override public MusicGroup.Builder addMakesOffer(Offer value) { return addProperty(CoreConstants.PROPERTY_MAKES_OFFER, value); } @Override public MusicGroup.Builder addMakesOffer(Offer.Builder value) { return addProperty(CoreConstants.PROPERTY_MAKES_OFFER, value.build()); } @Override public MusicGroup.Builder addMakesOffer(String value) { return addProperty(CoreConstants.PROPERTY_MAKES_OFFER, Text.of(value)); } @Override public MusicGroup.Builder addMember(Organization value) { return addProperty(CoreConstants.PROPERTY_MEMBER, value); } @Override public MusicGroup.Builder addMember(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_MEMBER, value.build()); } @Override public MusicGroup.Builder addMember(Person value) { return addProperty(CoreConstants.PROPERTY_MEMBER, value); } @Override public MusicGroup.Builder addMember(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_MEMBER, value.build()); } @Override public MusicGroup.Builder addMember(String value) { return addProperty(CoreConstants.PROPERTY_MEMBER, Text.of(value)); } @Override public MusicGroup.Builder addMemberOf(Organization value) { return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value); } @Override public MusicGroup.Builder addMemberOf(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value.build()); } @Override public MusicGroup.Builder addMemberOf(ProgramMembership value) { return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value); } @Override public MusicGroup.Builder addMemberOf(ProgramMembership.Builder value) { return addProperty(CoreConstants.PROPERTY_MEMBER_OF, value.build()); } @Override public MusicGroup.Builder addMemberOf(String value) { return addProperty(CoreConstants.PROPERTY_MEMBER_OF, Text.of(value)); } @Override public MusicGroup.Builder addMembers(Organization value) { return addProperty(CoreConstants.PROPERTY_MEMBERS, value); } @Override public MusicGroup.Builder addMembers(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_MEMBERS, value.build()); } @Override public MusicGroup.Builder addMembers(Person value) { return addProperty(CoreConstants.PROPERTY_MEMBERS, value); } @Override public MusicGroup.Builder addMembers(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_MEMBERS, value.build()); } @Override public MusicGroup.Builder addMembers(String value) { return addProperty(CoreConstants.PROPERTY_MEMBERS, Text.of(value)); } @Override public MusicGroup.Builder addMusicGroupMember(Person value) { return addProperty(CoreConstants.PROPERTY_MUSIC_GROUP_MEMBER, value); } @Override public MusicGroup.Builder addMusicGroupMember(Person.Builder value) { return addProperty(CoreConstants.PROPERTY_MUSIC_GROUP_MEMBER, value.build()); } @Override public MusicGroup.Builder addMusicGroupMember(String value) { return addProperty(CoreConstants.PROPERTY_MUSIC_GROUP_MEMBER, Text.of(value)); } @Override public MusicGroup.Builder addNaics(Text value) { return addProperty(CoreConstants.PROPERTY_NAICS, value); } @Override public MusicGroup.Builder addNaics(String value) { return addProperty(CoreConstants.PROPERTY_NAICS, Text.of(value)); } @Override public MusicGroup.Builder addName(Text value) { return addProperty(CoreConstants.PROPERTY_NAME, value); } @Override public MusicGroup.Builder addName(String value) { return addProperty(CoreConstants.PROPERTY_NAME, Text.of(value)); } @Override public MusicGroup.Builder addNumberOfEmployees(QuantitativeValue value) { return addProperty(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES, value); } @Override public MusicGroup.Builder addNumberOfEmployees(QuantitativeValue.Builder value) { return addProperty(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES, value.build()); } @Override public MusicGroup.Builder addNumberOfEmployees(String value) { return addProperty(CoreConstants.PROPERTY_NUMBER_OF_EMPLOYEES, Text.of(value)); } @Override public MusicGroup.Builder addOwns(OwnershipInfo value) { return addProperty(CoreConstants.PROPERTY_OWNS, value); } @Override public MusicGroup.Builder addOwns(OwnershipInfo.Builder value) { return addProperty(CoreConstants.PROPERTY_OWNS, value.build()); } @Override public MusicGroup.Builder addOwns(Product value) { return addProperty(CoreConstants.PROPERTY_OWNS, value); } @Override public MusicGroup.Builder addOwns(Product.Builder value) { return addProperty(CoreConstants.PROPERTY_OWNS, value.build()); } @Override public MusicGroup.Builder addOwns(String value) { return addProperty(CoreConstants.PROPERTY_OWNS, Text.of(value)); } @Override public MusicGroup.Builder addParentOrganization(Organization value) { return addProperty(CoreConstants.PROPERTY_PARENT_ORGANIZATION, value); } @Override public MusicGroup.Builder addParentOrganization(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_PARENT_ORGANIZATION, value.build()); } @Override public MusicGroup.Builder addParentOrganization(String value) { return addProperty(CoreConstants.PROPERTY_PARENT_ORGANIZATION, Text.of(value)); } @Override public MusicGroup.Builder addPotentialAction(Action value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value); } @Override public MusicGroup.Builder addPotentialAction(Action.Builder value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, value.build()); } @Override public MusicGroup.Builder addPotentialAction(String value) { return addProperty(CoreConstants.PROPERTY_POTENTIAL_ACTION, Text.of(value)); } @Override public MusicGroup.Builder addReview(Review value) { return addProperty(CoreConstants.PROPERTY_REVIEW, value); } @Override public MusicGroup.Builder addReview(Review.Builder value) { return addProperty(CoreConstants.PROPERTY_REVIEW, value.build()); } @Override public MusicGroup.Builder addReview(String value) { return addProperty(CoreConstants.PROPERTY_REVIEW, Text.of(value)); } @Override public MusicGroup.Builder addReviews(Review value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, value); } @Override public MusicGroup.Builder addReviews(Review.Builder value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, value.build()); } @Override public MusicGroup.Builder addReviews(String value) { return addProperty(CoreConstants.PROPERTY_REVIEWS, Text.of(value)); } @Override public MusicGroup.Builder addSameAs(URL value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, value); } @Override public MusicGroup.Builder addSameAs(String value) { return addProperty(CoreConstants.PROPERTY_SAME_AS, Text.of(value)); } @Override public MusicGroup.Builder addSeeks(Demand value) { return addProperty(CoreConstants.PROPERTY_SEEKS, value); } @Override public MusicGroup.Builder addSeeks(Demand.Builder value) { return addProperty(CoreConstants.PROPERTY_SEEKS, value.build()); } @Override public MusicGroup.Builder addSeeks(String value) { return addProperty(CoreConstants.PROPERTY_SEEKS, Text.of(value)); } @Override public MusicGroup.Builder addServiceArea(AdministrativeArea value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value); } @Override public MusicGroup.Builder addServiceArea(AdministrativeArea.Builder value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value.build()); } @Override public MusicGroup.Builder addServiceArea(GeoShape value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value); } @Override public MusicGroup.Builder addServiceArea(GeoShape.Builder value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value.build()); } @Override public MusicGroup.Builder addServiceArea(Place value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value); } @Override public MusicGroup.Builder addServiceArea(Place.Builder value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, value.build()); } @Override public MusicGroup.Builder addServiceArea(String value) { return addProperty(CoreConstants.PROPERTY_SERVICE_AREA, Text.of(value)); } @Override public MusicGroup.Builder addSubOrganization(Organization value) { return addProperty(CoreConstants.PROPERTY_SUB_ORGANIZATION, value); } @Override public MusicGroup.Builder addSubOrganization(Organization.Builder value) { return addProperty(CoreConstants.PROPERTY_SUB_ORGANIZATION, value.build()); } @Override public MusicGroup.Builder addSubOrganization(String value) { return addProperty(CoreConstants.PROPERTY_SUB_ORGANIZATION, Text.of(value)); } @Override public MusicGroup.Builder addTaxID(Text value) { return addProperty(CoreConstants.PROPERTY_TAX_ID, value); } @Override public MusicGroup.Builder addTaxID(String value) { return addProperty(CoreConstants.PROPERTY_TAX_ID, Text.of(value)); } @Override public MusicGroup.Builder addTelephone(Text value) { return addProperty(CoreConstants.PROPERTY_TELEPHONE, value); } @Override public MusicGroup.Builder addTelephone(String value) { return addProperty(CoreConstants.PROPERTY_TELEPHONE, Text.of(value)); } @Override public MusicGroup.Builder addTrack(ItemList value) { return addProperty(CoreConstants.PROPERTY_TRACK, value); } @Override public MusicGroup.Builder addTrack(ItemList.Builder value) { return addProperty(CoreConstants.PROPERTY_TRACK, value.build()); } @Override public MusicGroup.Builder addTrack(MusicRecording value) { return addProperty(CoreConstants.PROPERTY_TRACK, value); } @Override public MusicGroup.Builder addTrack(MusicRecording.Builder value) { return addProperty(CoreConstants.PROPERTY_TRACK, value.build()); } @Override public MusicGroup.Builder addTrack(String value) { return addProperty(CoreConstants.PROPERTY_TRACK, Text.of(value)); } @Override public MusicGroup.Builder addTracks(MusicRecording value) { return addProperty(CoreConstants.PROPERTY_TRACKS, value); } @Override public MusicGroup.Builder addTracks(MusicRecording.Builder value) { return addProperty(CoreConstants.PROPERTY_TRACKS, value.build()); } @Override public MusicGroup.Builder addTracks(String value) { return addProperty(CoreConstants.PROPERTY_TRACKS, Text.of(value)); } @Override public MusicGroup.Builder addUrl(URL value) { return addProperty(CoreConstants.PROPERTY_URL, value); } @Override public MusicGroup.Builder addUrl(String value) { return addProperty(CoreConstants.PROPERTY_URL, Text.of(value)); } @Override public MusicGroup.Builder addVatID(Text value) { return addProperty(CoreConstants.PROPERTY_VAT_ID, value); } @Override public MusicGroup.Builder addVatID(String value) { return addProperty(CoreConstants.PROPERTY_VAT_ID, Text.of(value)); } @Override public MusicGroup.Builder addDetailedDescription(Article value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value); } @Override public MusicGroup.Builder addDetailedDescription(Article.Builder value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, value.build()); } @Override public MusicGroup.Builder addDetailedDescription(String value) { return addProperty(GoogConstants.PROPERTY_DETAILED_DESCRIPTION, Text.of(value)); } @Override public MusicGroup.Builder addPopularityScore(PopularityScoreSpecification value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value); } @Override public MusicGroup.Builder addPopularityScore(PopularityScoreSpecification.Builder value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, value.build()); } @Override public MusicGroup.Builder addPopularityScore(String value) { return addProperty(GoogConstants.PROPERTY_POPULARITY_SCORE, Text.of(value)); } @Override public MusicGroup build() { return new MusicGroupImpl(properties, reverseMap); } } public MusicGroupImpl( Multimap<String, ValueType> properties, Multimap<String, Thing> reverseMap) { super(properties, reverseMap); } @Override public String getFullTypeName() { return CoreConstants.TYPE_MUSIC_GROUP; } @Override public boolean includesProperty(String property) { return PROPERTY_SET.contains(CoreConstants.NAMESPACE + property) || PROPERTY_SET.contains(GoogConstants.NAMESPACE + property) || PROPERTY_SET.contains(property); } @Override public ImmutableList<SchemaOrgType> getAlbumList() { return getProperty(CoreConstants.PROPERTY_ALBUM); } @Override public ImmutableList<SchemaOrgType> getAlbumsList() { return getProperty(CoreConstants.PROPERTY_ALBUMS); } @Override public ImmutableList<SchemaOrgType> getGenreList() { return getProperty(CoreConstants.PROPERTY_GENRE); } @Override public ImmutableList<SchemaOrgType> getMusicGroupMemberList() { return getProperty(CoreConstants.PROPERTY_MUSIC_GROUP_MEMBER); } @Override public ImmutableList<SchemaOrgType> getTrackList() { return getProperty(CoreConstants.PROPERTY_TRACK); } @Override public ImmutableList<SchemaOrgType> getTracksList() { return getProperty(CoreConstants.PROPERTY_TRACKS); } }
googleapis/google-cloud-java
36,612
java-discoveryengine/proto-google-cloud-discoveryengine-v1beta/src/main/java/com/google/cloud/discoveryengine/v1beta/ListSessionsResponse.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/v1beta/conversational_search_service.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.discoveryengine.v1beta; /** * * * <pre> * Response for ListSessions method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1beta.ListSessionsResponse} */ public final class ListSessionsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1beta.ListSessionsResponse) ListSessionsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListSessionsResponse.newBuilder() to construct. private ListSessionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListSessionsResponse() { sessions_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListSessionsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListSessionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListSessionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.class, com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.Builder.class); } public static final int SESSIONS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.discoveryengine.v1beta.Session> sessions_; /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.discoveryengine.v1beta.Session> getSessionsList() { return sessions_; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.discoveryengine.v1beta.SessionOrBuilder> getSessionsOrBuilderList() { return sessions_; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ @java.lang.Override public int getSessionsCount() { return sessions_.size(); } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ @java.lang.Override public com.google.cloud.discoveryengine.v1beta.Session getSessions(int index) { return sessions_.get(index); } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ @java.lang.Override public com.google.cloud.discoveryengine.v1beta.SessionOrBuilder getSessionsOrBuilder(int index) { return sessions_.get(index); } public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2; @SuppressWarnings("serial") private volatile java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pagination token, if not returned indicates the last 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> * Pagination token, if not returned indicates the last 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 < sessions_.size(); i++) { output.writeMessage(1, sessions_.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 < sessions_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, sessions_.get(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.discoveryengine.v1beta.ListSessionsResponse)) { return super.equals(obj); } com.google.cloud.discoveryengine.v1beta.ListSessionsResponse other = (com.google.cloud.discoveryengine.v1beta.ListSessionsResponse) obj; if (!getSessionsList().equals(other.getSessionsList())) 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 (getSessionsCount() > 0) { hash = (37 * hash) + SESSIONS_FIELD_NUMBER; hash = (53 * hash) + getSessionsList().hashCode(); } hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER; hash = (53 * hash) + getNextPageToken().hashCode(); hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse 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.v1beta.ListSessionsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse 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.v1beta.ListSessionsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse 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.v1beta.ListSessionsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse 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.v1beta.ListSessionsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse 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.v1beta.ListSessionsResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Response for ListSessions method. * </pre> * * Protobuf type {@code google.cloud.discoveryengine.v1beta.ListSessionsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1beta.ListSessionsResponse) com.google.cloud.discoveryengine.v1beta.ListSessionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListSessionsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListSessionsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.class, com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.Builder.class); } // Construct using com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (sessionsBuilder_ == null) { sessions_ = java.util.Collections.emptyList(); } else { sessions_ = null; sessionsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.discoveryengine.v1beta.ConversationalSearchServiceProto .internal_static_google_cloud_discoveryengine_v1beta_ListSessionsResponse_descriptor; } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListSessionsResponse getDefaultInstanceForType() { return com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListSessionsResponse build() { com.google.cloud.discoveryengine.v1beta.ListSessionsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListSessionsResponse buildPartial() { com.google.cloud.discoveryengine.v1beta.ListSessionsResponse result = new com.google.cloud.discoveryengine.v1beta.ListSessionsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.discoveryengine.v1beta.ListSessionsResponse result) { if (sessionsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { sessions_ = java.util.Collections.unmodifiableList(sessions_); bitField0_ = (bitField0_ & ~0x00000001); } result.sessions_ = sessions_; } else { result.sessions_ = sessionsBuilder_.build(); } } private void buildPartial0( com.google.cloud.discoveryengine.v1beta.ListSessionsResponse result) { int from_bitField0_ = bitField0_; if (((from_bitField0_ & 0x00000002) != 0)) { result.nextPageToken_ = nextPageToken_; } } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.discoveryengine.v1beta.ListSessionsResponse) { return mergeFrom((com.google.cloud.discoveryengine.v1beta.ListSessionsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.discoveryengine.v1beta.ListSessionsResponse other) { if (other == com.google.cloud.discoveryengine.v1beta.ListSessionsResponse.getDefaultInstance()) return this; if (sessionsBuilder_ == null) { if (!other.sessions_.isEmpty()) { if (sessions_.isEmpty()) { sessions_ = other.sessions_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureSessionsIsMutable(); sessions_.addAll(other.sessions_); } onChanged(); } } else { if (!other.sessions_.isEmpty()) { if (sessionsBuilder_.isEmpty()) { sessionsBuilder_.dispose(); sessionsBuilder_ = null; sessions_ = other.sessions_; bitField0_ = (bitField0_ & ~0x00000001); sessionsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getSessionsFieldBuilder() : null; } else { sessionsBuilder_.addAllMessages(other.sessions_); } } } if (!other.getNextPageToken().isEmpty()) { nextPageToken_ = other.nextPageToken_; bitField0_ |= 0x00000002; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { com.google.cloud.discoveryengine.v1beta.Session m = input.readMessage( com.google.cloud.discoveryengine.v1beta.Session.parser(), extensionRegistry); if (sessionsBuilder_ == null) { ensureSessionsIsMutable(); sessions_.add(m); } else { sessionsBuilder_.addMessage(m); } break; } // case 10 case 18: { nextPageToken_ = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int bitField0_; private java.util.List<com.google.cloud.discoveryengine.v1beta.Session> sessions_ = java.util.Collections.emptyList(); private void ensureSessionsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { sessions_ = new java.util.ArrayList<com.google.cloud.discoveryengine.v1beta.Session>(sessions_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.discoveryengine.v1beta.Session, com.google.cloud.discoveryengine.v1beta.Session.Builder, com.google.cloud.discoveryengine.v1beta.SessionOrBuilder> sessionsBuilder_; /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public java.util.List<com.google.cloud.discoveryengine.v1beta.Session> getSessionsList() { if (sessionsBuilder_ == null) { return java.util.Collections.unmodifiableList(sessions_); } else { return sessionsBuilder_.getMessageList(); } } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public int getSessionsCount() { if (sessionsBuilder_ == null) { return sessions_.size(); } else { return sessionsBuilder_.getCount(); } } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public com.google.cloud.discoveryengine.v1beta.Session getSessions(int index) { if (sessionsBuilder_ == null) { return sessions_.get(index); } else { return sessionsBuilder_.getMessage(index); } } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder setSessions(int index, com.google.cloud.discoveryengine.v1beta.Session value) { if (sessionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSessionsIsMutable(); sessions_.set(index, value); onChanged(); } else { sessionsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder setSessions( int index, com.google.cloud.discoveryengine.v1beta.Session.Builder builderForValue) { if (sessionsBuilder_ == null) { ensureSessionsIsMutable(); sessions_.set(index, builderForValue.build()); onChanged(); } else { sessionsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder addSessions(com.google.cloud.discoveryengine.v1beta.Session value) { if (sessionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSessionsIsMutable(); sessions_.add(value); onChanged(); } else { sessionsBuilder_.addMessage(value); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder addSessions(int index, com.google.cloud.discoveryengine.v1beta.Session value) { if (sessionsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSessionsIsMutable(); sessions_.add(index, value); onChanged(); } else { sessionsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder addSessions( com.google.cloud.discoveryengine.v1beta.Session.Builder builderForValue) { if (sessionsBuilder_ == null) { ensureSessionsIsMutable(); sessions_.add(builderForValue.build()); onChanged(); } else { sessionsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder addSessions( int index, com.google.cloud.discoveryengine.v1beta.Session.Builder builderForValue) { if (sessionsBuilder_ == null) { ensureSessionsIsMutable(); sessions_.add(index, builderForValue.build()); onChanged(); } else { sessionsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder addAllSessions( java.lang.Iterable<? extends com.google.cloud.discoveryengine.v1beta.Session> values) { if (sessionsBuilder_ == null) { ensureSessionsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, sessions_); onChanged(); } else { sessionsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder clearSessions() { if (sessionsBuilder_ == null) { sessions_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { sessionsBuilder_.clear(); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public Builder removeSessions(int index) { if (sessionsBuilder_ == null) { ensureSessionsIsMutable(); sessions_.remove(index); onChanged(); } else { sessionsBuilder_.remove(index); } return this; } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public com.google.cloud.discoveryengine.v1beta.Session.Builder getSessionsBuilder(int index) { return getSessionsFieldBuilder().getBuilder(index); } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public com.google.cloud.discoveryengine.v1beta.SessionOrBuilder getSessionsOrBuilder( int index) { if (sessionsBuilder_ == null) { return sessions_.get(index); } else { return sessionsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public java.util.List<? extends com.google.cloud.discoveryengine.v1beta.SessionOrBuilder> getSessionsOrBuilderList() { if (sessionsBuilder_ != null) { return sessionsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(sessions_); } } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public com.google.cloud.discoveryengine.v1beta.Session.Builder addSessionsBuilder() { return getSessionsFieldBuilder() .addBuilder(com.google.cloud.discoveryengine.v1beta.Session.getDefaultInstance()); } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public com.google.cloud.discoveryengine.v1beta.Session.Builder addSessionsBuilder(int index) { return getSessionsFieldBuilder() .addBuilder(index, com.google.cloud.discoveryengine.v1beta.Session.getDefaultInstance()); } /** * * * <pre> * All the Sessions for a given data store. * </pre> * * <code>repeated .google.cloud.discoveryengine.v1beta.Session sessions = 1;</code> */ public java.util.List<com.google.cloud.discoveryengine.v1beta.Session.Builder> getSessionsBuilderList() { return getSessionsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.discoveryengine.v1beta.Session, com.google.cloud.discoveryengine.v1beta.Session.Builder, com.google.cloud.discoveryengine.v1beta.SessionOrBuilder> getSessionsFieldBuilder() { if (sessionsBuilder_ == null) { sessionsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.discoveryengine.v1beta.Session, com.google.cloud.discoveryengine.v1beta.Session.Builder, com.google.cloud.discoveryengine.v1beta.SessionOrBuilder>( sessions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); sessions_ = null; } return sessionsBuilder_; } private java.lang.Object nextPageToken_ = ""; /** * * * <pre> * Pagination token, if not returned indicates the last 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> * Pagination token, if not returned indicates the last 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> * Pagination token, if not returned indicates the last 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> * Pagination token, if not returned indicates the last 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> * Pagination token, if not returned indicates the last 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.discoveryengine.v1beta.ListSessionsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1beta.ListSessionsResponse) private static final com.google.cloud.discoveryengine.v1beta.ListSessionsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1beta.ListSessionsResponse(); } public static com.google.cloud.discoveryengine.v1beta.ListSessionsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListSessionsResponse> PARSER = new com.google.protobuf.AbstractParser<ListSessionsResponse>() { @java.lang.Override public ListSessionsResponse 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<ListSessionsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListSessionsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.discoveryengine.v1beta.ListSessionsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache/hadoop
36,578
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMHA.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.yarn.server.resourcemanager; import java.io.DataOutputStream; import java.io.File; import java.nio.file.Files; import java.util.UUID; import java.util.function.Supplier; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.net.InetSocketAddress; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.HAServiceProtocol; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo; import org.apache.hadoop.ha.HealthCheckFailedException; import org.apache.hadoop.ha.ServiceFailedException; import org.apache.hadoop.http.JettyUtils; import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.service.AbstractService; import org.apache.hadoop.yarn.conf.HAUtil; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.event.Dispatcher; import org.apache.hadoop.yarn.event.DrainDispatcher; import org.apache.hadoop.yarn.event.Event; import org.apache.hadoop.yarn.event.EventHandler; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore; import org.apache.hadoop.yarn.server.resourcemanager.recovery.StoreFencedException; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.glassfish.jersey.jettison.internal.entity.JettisonObjectProvider; public class TestRMHA { private static final Logger LOG = LoggerFactory.getLogger(TestRMHA.class); private Configuration configuration; private MockRM rm = null; private MockNM nm = null; private RMApp app = null; private RMAppAttempt attempt = null; private static final String STATE_ERR = "ResourceManager is in wrong HA state"; private static final String RM1_ADDRESS = "1.1.1.1:1"; private static final String RM1_NODE_ID = "rm1"; private static final String RM2_ADDRESS = "0.0.0.0:0"; private static final String RM2_NODE_ID = "rm2"; private static final String RM3_ADDRESS = "2.2.2.2:2"; private static final String RM3_NODE_ID = "rm3"; @BeforeEach public void setUp() throws Exception { configuration = new Configuration(); UserGroupInformation.setConfiguration(configuration); configuration.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); configuration.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); for (String confKey : YarnConfiguration .getServiceAddressConfKeys(configuration)) { configuration.set(HAUtil.addSuffix(confKey, RM1_NODE_ID), RM1_ADDRESS); configuration.set(HAUtil.addSuffix(confKey, RM2_NODE_ID), RM2_ADDRESS); configuration.set(HAUtil.addSuffix(confKey, RM3_NODE_ID), RM3_ADDRESS); } // Enable webapp to test web-services also configuration.setBoolean(MockRM.ENABLE_WEBAPP, true); configuration.setBoolean(YarnConfiguration.YARN_ACL_ENABLE, true); ClusterMetrics.destroy(); QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.shutdown(); } private void checkMonitorHealth() throws IOException { try { rm.adminService.monitorHealth(); } catch (HealthCheckFailedException e) { fail("The RM is in bad health: it is Active, but the active services " + "are not running"); } } private void checkStandbyRMFunctionality() throws IOException { assertEquals(HAServiceState.STANDBY, rm.adminService.getServiceStatus().getState(), STATE_ERR); assertFalse(rm.areActiveServicesRunning(), "Active RM services are started"); assertTrue(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is not ready to become active"); } private void checkActiveRMFunctionality() throws Exception { assertEquals(HAServiceState.ACTIVE, rm.adminService.getServiceStatus().getState(), STATE_ERR); assertTrue(rm.areActiveServicesRunning(), "Active RM services aren't started"); assertTrue(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is not ready to become active"); try { rm.getNewAppId(); nm = rm.registerNode("127.0.0.1:1", 2048); app = MockRMAppSubmitter.submitWithMemory(1024, rm); attempt = app.getCurrentAppAttempt(); rm.waitForState(attempt.getAppAttemptId(), RMAppAttemptState.SCHEDULED); } catch (Exception e) { fail("Unable to perform Active RM functions"); LOG.error("ActiveRM check failed", e); } checkActiveRMWebServices(); } // Do some sanity testing of the web-services after fail-over. private void checkActiveRMWebServices() throws JSONException { // Validate web-service Client webServiceClient = ClientBuilder. newClient(). register(new JettisonObjectProvider.App()); InetSocketAddress rmWebappAddr = NetUtils.getConnectAddress(rm.getWebapp().getListenerAddress()); String webappURL = "http://" + rmWebappAddr.getHostName() + ":" + rmWebappAddr.getPort(); WebTarget webResource = webServiceClient.target(webappURL); String path = app.getApplicationId().toString(); Response response = webResource.path("ws").path("v1").path("cluster").path("apps") .path(path).request(MediaType.APPLICATION_JSON) .get(Response.class); assertEquals(MediaType.APPLICATION_JSON_TYPE + ";" + JettyUtils.UTF_8, response.getMediaType().toString()); JSONObject json = response.readEntity(JSONObject.class); assertEquals(1, json.length(), "incorrect number of elements"); JSONObject appJson = json.getJSONObject("app"); assertEquals("ACCEPTED", appJson.getString("state")); // Other stuff is verified in the regular web-services related tests } /** * Test to verify the following RM HA transitions to the following states. * 1. Standby: Should be a no-op * 2. Active: Active services should start * 3. Active: Should be a no-op. * While active, submit a couple of jobs * 4. Standby: Active services should stop * 5. Active: Active services should start * 6. Stop the RM: All services should stop and RM should not be ready to * become Active */ @Test @Timeout(value = 30) public void testFailoverAndTransitions() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(HAServiceState.INITIALIZING, rm.adminService.getServiceStatus().getState(), STATE_ERR); assertFalse(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is ready to become active before being started"); checkMonitorHealth(); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 1. Transition to Standby - must be a no-op rm.adminService.transitionToStandby(requestInfo); checkMonitorHealth(); checkStandbyRMFunctionality(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 2. Transition to active rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 1, 1, 1, 2048, 1); // 3. Transition to active - no-op rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 2, 2, 2, 2048, 2); // 4. Transition to standby rm.adminService.transitionToStandby(requestInfo); checkMonitorHealth(); checkStandbyRMFunctionality(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 5. Transition to active to check Active->Standby->Active works rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 1, 1, 1, 2048, 1); // 6. Stop the RM. All services should stop and RM should not be ready to // become active rm.stop(); assertEquals(HAServiceState.STOPPING, rm.adminService.getServiceStatus().getState(), STATE_ERR); assertFalse(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is ready to become active even after it is stopped"); assertFalse(rm.areActiveServicesRunning(), "Active RM services are started"); checkMonitorHealth(); } @Test public void testTransitionsWhenAutomaticFailoverEnabled() throws Exception { final String ERR_UNFORCED_REQUEST = "User request succeeded even when " + "automatic failover is enabled"; Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); // Transition to standby try { rm.adminService.transitionToStandby(requestInfo); fail(ERR_UNFORCED_REQUEST); } catch (AccessControlException e) { // expected } checkMonitorHealth(); checkStandbyRMFunctionality(); // Transition to active try { rm.adminService.transitionToActive(requestInfo); fail(ERR_UNFORCED_REQUEST); } catch (AccessControlException e) { // expected } checkMonitorHealth(); checkStandbyRMFunctionality(); final String ERR_FORCED_REQUEST = "Forced request by user should work " + "even if automatic failover is enabled"; requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER_FORCED); // Transition to standby try { rm.adminService.transitionToStandby(requestInfo); } catch (AccessControlException e) { fail(ERR_FORCED_REQUEST); } checkMonitorHealth(); checkStandbyRMFunctionality(); // Transition to active try { rm.adminService.transitionToActive(requestInfo); } catch (AccessControlException e) { fail(ERR_FORCED_REQUEST); } checkMonitorHealth(); checkActiveRMFunctionality(); } @Test public void testRMDispatcherForHA() throws IOException { String errorMessageForEventHandler = "Expect to get the same number of handlers"; String errorMessageForService = "Expect to get the same number of services"; configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf) { @Override protected Dispatcher createDispatcher() { return new MyCountingDispatcher(); } }; rm.init(conf); int expectedEventHandlerCount = ((MyCountingDispatcher) rm.getRMContext().getDispatcher()) .getEventHandlerCount(); int expectedServiceCount = rm.getServices().size(); assertTrue(expectedEventHandlerCount != 0); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(HAServiceState.INITIALIZING, rm.adminService.getServiceStatus().getState(), STATE_ERR); assertFalse(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is ready to become active before being started"); rm.start(); //call transitions to standby and active a couple of times rm.adminService.transitionToStandby(requestInfo); rm.adminService.transitionToActive(requestInfo); rm.adminService.transitionToStandby(requestInfo); rm.adminService.transitionToActive(requestInfo); rm.adminService.transitionToStandby(requestInfo); MyCountingDispatcher dispatcher = (MyCountingDispatcher) rm.getRMContext().getDispatcher(); assertTrue(!dispatcher.isStopped()); rm.adminService.transitionToActive(requestInfo); assertEquals(expectedEventHandlerCount, ((MyCountingDispatcher) rm.getRMContext().getDispatcher()) .getEventHandlerCount(), errorMessageForEventHandler); assertEquals(expectedServiceCount, rm.getServices().size(), errorMessageForService); // Keep the dispatcher reference before transitioning to standby dispatcher = (MyCountingDispatcher) rm.getRMContext().getDispatcher(); rm.adminService.transitionToStandby(requestInfo); assertEquals(expectedEventHandlerCount, ((MyCountingDispatcher) rm.getRMContext().getDispatcher()) .getEventHandlerCount(), errorMessageForEventHandler); assertEquals(expectedServiceCount, rm.getServices().size(), errorMessageForService); assertTrue(dispatcher.isStopped()); rm.stop(); } @Test public void testHAIDLookup() { //test implicitly lookup HA-ID Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); assertThat(conf.get(YarnConfiguration.RM_HA_ID)).isEqualTo(RM2_NODE_ID); //test explicitly lookup HA-ID configuration.set(YarnConfiguration.RM_HA_ID, RM1_NODE_ID); conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); assertThat(conf.get(YarnConfiguration.RM_HA_ID)).isEqualTo(RM1_NODE_ID); //test if RM_HA_ID can not be found configuration .set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM3_NODE_ID); configuration.unset(YarnConfiguration.RM_HA_ID); conf = new YarnConfiguration(configuration); try { rm = new MockRM(conf); rm.init(conf); fail("Should get an exception here."); } catch (Exception ex) { assertTrue(ex.getMessage().contains( "Invalid configuration! Can not find valid RM_HA_ID.")); } } @Test public void testHAWithRMHostName() throws Exception { innerTestHAWithRMHostName(false); configuration.clear(); setUp(); innerTestHAWithRMHostName(true); } @Test @Timeout(value = 30) public void testFailoverWhenTransitionToActiveThrowException() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); MemoryRMStateStore memStore = new MockMemoryRMStateStore() { int count = 0; @Override public synchronized void startInternal() throws Exception { // first time throw exception if (count++ == 0) { throw new Exception("Session Expired"); } } }; // start RM memStore.init(conf); rm = new MockRM(conf, memStore); rm.init(conf); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(HAServiceState.INITIALIZING, rm.adminService .getServiceStatus().getState(), STATE_ERR); assertFalse(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is ready to become active before being started"); checkMonitorHealth(); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Try Transition to active, throw exception try { rm.adminService.transitionToActive(requestInfo); fail("Transitioned to Active should throw exception."); } catch (Exception e) { assertTrue("Error when transitioning to Active mode".contains(e .getMessage())); } // 3. Transition to active, success rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); } @Test public void testTransitionedToStandbyShouldNotHang() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); Configuration conf = new YarnConfiguration(configuration); MemoryRMStateStore memStore = new MockMemoryRMStateStore() { @Override public void updateApplicationState(ApplicationStateData appState) { notifyStoreOperationFailed(new StoreFencedException()); } }; memStore.init(conf); rm = new MockRM(conf, memStore) { @Override void stopActiveServices() { try { Thread.sleep(10000); } catch (Exception e) { throw new RuntimeException (e); } super.stopActiveServices(); } }; rm.init(conf); final StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); assertEquals(HAServiceState.INITIALIZING, rm.adminService .getServiceStatus().getState(), STATE_ERR); assertFalse(rm.adminService.getServiceStatus().isReadyToBecomeActive(), "RM is ready to become active before being started"); checkMonitorHealth(); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Transition to Active. rm.adminService.transitionToActive(requestInfo); // 3. Try Transition to standby Thread t = new Thread(new Runnable() { @Override public void run() { try { rm.transitionToStandby(true); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); t.start(); rm.getRMContext().getStateStore().updateApplicationState(null); t.join(); // wait for thread to finish rm.adminService.transitionToStandby(requestInfo); checkStandbyRMFunctionality(); rm.stop(); } @Test public void testFailoverClearsRMContext() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); configuration.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); Configuration conf = new YarnConfiguration(configuration); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); // 1. start RM rm = new MockRM(conf); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Transition to active rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); verifyClusterMetrics(1, 1, 1, 1, 2048, 1); assertEquals(1, rm.getRMContext().getRMNodes().size()); assertEquals(1, rm.getRMContext().getRMApps().size()); assertNotNull(nm, "Node not registered"); rm.adminService.transitionToStandby(requestInfo); checkMonitorHealth(); checkStandbyRMFunctionality(); // race condition causes to register/node heartbeat node even after service // is stopping/stopped. New RMContext is being created on every transition // to standby, so metrics should be 0 which indicates new context reference // has taken. nm.registerNode(); verifyClusterMetrics(0, 0, 0, 0, 0, 0); // 3. Create new RM rm = new MockRM(conf, rm.getRMStateStore()) { @Override protected ResourceTrackerService createResourceTrackerService() { return new ResourceTrackerService(this.rmContext, this.nodesListManager, this.nmLivelinessMonitor, this.rmContext.getContainerTokenSecretManager(), this.rmContext.getNMTokenSecretManager()) { @Override protected void serviceStart() throws Exception { throw new Exception("ResourceTracker service failed"); } }; } }; rm.init(conf); rm.start(); checkMonitorHealth(); checkStandbyRMFunctionality(); // 4. Try Transition to active, throw exception try { rm.adminService.transitionToActive(requestInfo); fail("Transitioned to Active should throw exception."); } catch (Exception e) { assertTrue("Error when transitioning to Active mode".contains(e .getMessage())); } // 5. Clears the metrics verifyClusterMetrics(0, 0, 0, 0, 0, 0); assertEquals(0, rm.getRMContext().getRMNodes().size()); assertEquals(0, rm.getRMContext().getRMApps().size()); } @Test @Timeout(value = 9000) public void testTransitionedToActiveRefreshFail() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); rm = new MockRM(configuration) { @Override protected AdminService createAdminService() { return new AdminService(this) { int counter = 0; @Override protected void setConfig(Configuration conf) { super.setConfig(configuration); } @Override protected void refreshAll() throws ServiceFailedException { if (counter == 0) { counter++; throw new ServiceFailedException("Simulate RefreshFail"); } else { super.refreshAll(); } } }; } @Override protected Dispatcher createDispatcher() { return new FailFastDispatcher(); } }; rm.init(configuration); rm.start(); final StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); FailFastDispatcher dispatcher = ((FailFastDispatcher) rm.rmContext.getDispatcher()); // Verify transition to transitionToStandby rm.adminService.transitionToStandby(requestInfo); assertEquals(0, dispatcher.getEventCount(), "Fatal Event should be 0"); assertEquals(HAServiceState.STANDBY, rm.getRMContext().getHAServiceState(), "HA state should be in standBy State"); try { // Verify refreshAll call failure and check fail Event is dispatched rm.adminService.transitionToActive(requestInfo); fail("Transition to Active should have failed for refreshAll()"); } catch (Exception e) { assertTrue(e instanceof ServiceFailedException, "Service fail Exception expected"); } // Since refreshAll failed we are expecting fatal event to be send // Then fatal event is send RM will shutdown dispatcher.await(); assertEquals(1, dispatcher.getEventCount(), "Fatal Event to be received"); // Check of refreshAll success HA can be active rm.adminService.transitionToActive(requestInfo); assertEquals(HAServiceState.ACTIVE, rm.getRMContext().getHAServiceState()); rm.adminService.transitionToStandby(requestInfo); assertEquals(HAServiceState.STANDBY, rm.getRMContext().getHAServiceState()); } @Test public void testOpportunisticAllocatorAfterFailover() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); configuration.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); Configuration conf = new YarnConfiguration(configuration); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); conf.setBoolean( YarnConfiguration.OPPORTUNISTIC_CONTAINER_ALLOCATION_ENABLED, true); // 1. start RM rm = new MockRM(conf); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); // 2. Transition to active rm.adminService.transitionToActive(requestInfo); // 3. Transition to standby rm.adminService.transitionToStandby(requestInfo); // 4. Transition to active rm.adminService.transitionToActive(requestInfo); MockNM nm1 = rm.registerNode("h1:1234", 8 * 1024); RMNode rmNode1 = rm.getRMContext().getRMNodes().get(nm1.getNodeId()); rmNode1.getRMContext().getDispatcher().getEventHandler() .handle(new NodeUpdateSchedulerEvent(rmNode1)); OpportunisticContainerAllocatorAMService appMaster = (OpportunisticContainerAllocatorAMService) rm.getRMContext() .getApplicationMasterService(); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return appMaster.getLeastLoadedNodes().size() == 1; } }, 100, 3000); rm.stop(); assertEquals(1, appMaster.getLeastLoadedNodes().size()); } @Test public void testResourceProfilesManagerAfterRMWentStandbyThenBackToActive() throws Exception { configuration.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); configuration.setBoolean(YarnConfiguration.RECOVERY_ENABLED, true); Configuration conf = new YarnConfiguration(configuration); conf.set(YarnConfiguration.RM_STORE, MemoryRMStateStore.class.getName()); // 1. start RM rm = new MockRM(conf); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); checkMonitorHealth(); checkStandbyRMFunctionality(); // 2. Transition to active rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); // 3. Transition to standby rm.adminService.transitionToStandby(requestInfo); checkMonitorHealth(); checkStandbyRMFunctionality(); // 4. Transition to active rm.adminService.transitionToActive(requestInfo); checkMonitorHealth(); checkActiveRMFunctionality(); // 5. Check ResourceProfilesManager assertNotNull(rm.getRMContext().getResourceProfilesManager(), "ResourceProfilesManager should not be null!"); } @Test public void testTransitionedToActiveWithExcludeFileNotExist() throws Exception { final String errUnforcedRequest = "User request succeeded even when " + "automatic failover is enabled"; Configuration conf = new YarnConfiguration(configuration); String nodeExcludeFilePath = "/tmp/non-existent-path-" + UUID.randomUUID(); conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH, nodeExcludeFilePath); DataOutputStream output = null; final File confFile = new File("target/test-classes/"+YarnConfiguration.YARN_SITE_CONFIGURATION_FILE); final File backupConfFile = new File( "target/test-classes/" + YarnConfiguration.YARN_SITE_CONFIGURATION_FILE + ".backup." + UUID.randomUUID()); boolean hasRenamed = false; try { if (confFile.exists()) { hasRenamed = confFile.renameTo(backupConfFile); if (!hasRenamed) { fail("Can not rename " + confFile.getAbsolutePath() + " to " + backupConfFile.getAbsolutePath()); } } if (!confFile.createNewFile()) { fail( "Can not create " + YarnConfiguration.YARN_SITE_CONFIGURATION_FILE); } output = new DataOutputStream(Files.newOutputStream(confFile.toPath())); conf.writeXml(output); } finally { if (output != null) { output.close(); } } try { rm = new MockRM(conf); rm.init(conf); rm.start(); StateChangeRequestInfo requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER); // Transition to standby try { rm.adminService.transitionToStandby(requestInfo); fail(errUnforcedRequest); } catch (AccessControlException e) { // expected } checkMonitorHealth(); checkStandbyRMFunctionality(); // Transition to active try { rm.adminService.transitionToActive(requestInfo); fail(errUnforcedRequest); } catch (AccessControlException e) { // expected } checkMonitorHealth(); checkStandbyRMFunctionality(); final String errForcedRequest = "Forced request by user should work " + "even if automatic failover is enabled"; requestInfo = new StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER_FORCED); // Transition to standby try { rm.adminService.transitionToStandby(requestInfo); } catch (AccessControlException e) { fail(errForcedRequest); } checkMonitorHealth(); checkStandbyRMFunctionality(); // Transition to active try { rm.adminService.transitionToActive(requestInfo); } catch (AccessControlException e) { fail(errForcedRequest); } checkMonitorHealth(); checkActiveRMFunctionality(); } finally { if (confFile.exists()) { if (!hasRenamed) { confFile.delete(); } else { backupConfFile.renameTo(confFile); } } if (rm != null) { rm.stop(); } } } public void innerTestHAWithRMHostName(boolean includeBindHost) { //this is run two times, with and without a bind host configured if (includeBindHost) { configuration.set(YarnConfiguration.RM_BIND_HOST, "9.9.9.9"); } //test if both RM_HOSTBANE_{rm_id} and RM_RPCADDRESS_{rm_id} are set //We should only read rpc addresses from RM_RPCADDRESS_{rm_id} configuration configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM1_NODE_ID), "1.1.1.1"); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM2_NODE_ID), "0.0.0.0"); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM3_NODE_ID), "2.2.2.2"); try { Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); for (String confKey : YarnConfiguration.getServiceAddressConfKeys(conf)) { assertEquals(RM1_ADDRESS, conf.get(HAUtil.addSuffix(confKey, RM1_NODE_ID)), "RPC address not set for " + confKey); assertEquals(RM2_ADDRESS, conf.get(HAUtil.addSuffix(confKey, RM2_NODE_ID)), "RPC address not set for " + confKey); assertEquals(RM3_ADDRESS, conf.get(HAUtil.addSuffix(confKey, RM3_NODE_ID)), "RPC address not set for " + confKey); if (includeBindHost) { assertEquals(rm.webAppAddress.substring(0, 7), "9.9.9.9", "Web address misconfigured WITH bind-host"); } else { //YarnConfiguration tries to figure out which rm host it's on by binding to it, //which doesn't happen for any of these fake addresses, so we end up with 0.0.0.0 assertEquals(rm.webAppAddress.substring(0, 7), "0.0.0.0", "Web address misconfigured WITHOUT bind-host"); } } } catch (YarnRuntimeException e) { fail("Should not throw any exceptions."); } //test if only RM_HOSTBANE_{rm_id} is set configuration.clear(); configuration.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); configuration.set(YarnConfiguration.RM_HA_IDS, RM1_NODE_ID + "," + RM2_NODE_ID); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM1_NODE_ID), "1.1.1.1"); configuration.set(HAUtil.addSuffix(YarnConfiguration.RM_HOSTNAME, RM2_NODE_ID), "0.0.0.0"); try { Configuration conf = new YarnConfiguration(configuration); rm = new MockRM(conf); rm.init(conf); assertEquals("1.1.1.1:8032", conf.get(HAUtil.addSuffix(YarnConfiguration.RM_ADDRESS, RM1_NODE_ID)), "RPC address not set for " + YarnConfiguration.RM_ADDRESS); assertEquals("0.0.0.0:8032", conf.get(HAUtil.addSuffix(YarnConfiguration.RM_ADDRESS, RM2_NODE_ID)), "RPC address not set for " + YarnConfiguration.RM_ADDRESS); } catch (YarnRuntimeException e) { fail("Should not throw any exceptions."); } } private void verifyClusterMetrics(int activeNodes, int appsSubmitted, int appsPending, int containersPending, long availableMB, int activeApplications) throws Exception { int timeoutSecs = 0; QueueMetrics metrics = rm.getResourceScheduler().getRootQueueMetrics(); ClusterMetrics clusterMetrics = ClusterMetrics.getMetrics(); boolean isAllMetricAssertionDone = false; String message = null; while (timeoutSecs++ < 5) { try { // verify queue metrics assertMetric("appsSubmitted", appsSubmitted, metrics.getAppsSubmitted()); assertMetric("appsPending", appsPending, metrics.getAppsPending()); assertMetric("containersPending", containersPending, metrics.getPendingContainers()); assertMetric("availableMB", availableMB, metrics.getAvailableMB()); assertMetric("activeApplications", activeApplications, metrics.getActiveApps()); // verify node metric assertMetric("activeNodes", activeNodes, clusterMetrics.getNumActiveNMs()); isAllMetricAssertionDone = true; break; } catch (AssertionError e) { message = e.getMessage(); System.out.println("Waiting for metrics assertion to complete"); Thread.sleep(1000); } } assertTrue(isAllMetricAssertionDone, message); } private void assertMetric(String metricName, long expected, long actual) { assertEquals(expected, actual, "Incorrect value for metric " + metricName); } @SuppressWarnings("rawtypes") class MyCountingDispatcher extends AbstractService implements Dispatcher { private int eventHandlerCount; private volatile boolean stopped = false; public MyCountingDispatcher() { super("MyCountingDispatcher"); this.eventHandlerCount = 0; } @Override public EventHandler<Event> getEventHandler() { return null; } @Override public void register(Class<? extends Enum> eventType, EventHandler handler) { this.eventHandlerCount ++; } public int getEventHandlerCount() { return this.eventHandlerCount; } @Override protected void serviceStop() throws Exception { this.stopped = true; super.serviceStop(); } public boolean isStopped() { return this.stopped; } } class FailFastDispatcher extends DrainDispatcher { int eventreceived = 0; @SuppressWarnings("rawtypes") @Override protected void dispatch(Event event) { if (event.getType() == RMFatalEventType.TRANSITION_TO_ACTIVE_FAILED) { eventreceived++; } else { super.dispatch(event); } } public int getEventCount() { return eventreceived; } } }
apache/ozhera
36,718
ozhera-operator/ozhera-operator-service/src/main/java/org/apache/ozhera/operator/service/HeraBootstrapInitService.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.ozhera.operator.service; import com.google.common.base.Preconditions; import com.google.gson.Gson; import com.mysql.cj.jdbc.Driver; import com.xiaomi.youpin.docean.anno.Service; import io.fabric8.kubernetes.api.model.*; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentList; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.MixedOperation; import io.fabric8.kubernetes.client.dsl.Resource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringSubstitutor; import org.apache.ibatis.jdbc.ScriptRunner; import org.apache.ozhera.operator.bo.*; import org.apache.ozhera.operator.common.FileUtils; import org.apache.ozhera.operator.common.HoConstant; import org.apache.ozhera.operator.common.K8sUtilBean; import org.apache.ozhera.operator.common.ResourceTypeEnum; import org.apache.ozhera.operator.dto.DeployStateDTO; import org.apache.ozhera.operator.dto.HeraOperatorDefineDTO; import org.apache.ozhera.operator.dto.PodStateDTO; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; /** * Initialize the mone family bucket namespace. * * @date 2022-06-17 */ @Service @Slf4j public class HeraBootstrapInitService { private Gson gson = new Gson(); @javax.annotation.Resource private KubernetesClient kubernetesClient; @javax.annotation.Resource(name = "deploymentClient") private MixedOperation<Deployment, DeploymentList, Resource<Deployment>> deploymentClient; @javax.annotation.Resource private K8sUtilBean k8sUtilBean; private volatile HeraOperatorDefineDTO heraOperatorDefine = new HeraOperatorDefineDTO(); private ReentrantLock lock = new ReentrantLock(); public void init() { try { HeraSpec heraSpec = new HeraSpec(); HeraObjectMeta heraMeta = new HeraObjectMeta(); heraMeta.setName(HoConstant.HERA_CR_NAME); heraMeta.setNamespace(HoConstant.HERA_NAMESPACE); List<HeraResource> resourceList = new ArrayList<>(); heraSpec.setResourceList(resourceList); HeraResource mysql = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/mysql/ozhera_mysql.yaml") .resourceType(ResourceTypeEnum.MYSQL.getTypeName()) .resourceName("hera-mysql") .remark("local pv, Make sure the disk directory has been created in advance.") .build(); mysql.setDefaultYaml(); List<Map<String, String>> mysqlConnectionMapList = new ArrayList<>(); mysqlConnectionMapList.add(kvMap(HoConstant.KEY_DATASOURCE_URL, "mone-db-all:3306", "mysql address,host:port")); mysqlConnectionMapList.add(kvMap(HoConstant.KEY_DATASOURCE_USERNAME, "root", "user name")); mysqlConnectionMapList.add(kvMap(HoConstant.KEY_DATASOURCE_PASSWORD, "Mone_123456", "password")); mysql.setConnectionMapList(mysqlConnectionMapList); resourceList.add(mysql); HeraResource redis = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/redis/ozhera_redis.yaml") .resourceType(ResourceTypeEnum.REDIS.getTypeName()) .resourceName("hera-redis") .remark("local redis.") .build(); redis.setDefaultYaml(); List<Map<String, String>> redisConnectionMapList = new ArrayList<>(); redisConnectionMapList.add(kvMap(HoConstant.KEY_REDIS_URL, "redis-service:6379", "redis address, host:port")); redisConnectionMapList.add(kvMap(HoConstant.KEY_REDIS_PASSWORD, "", "redis pwd, optional", "0")); redis.setConnectionMapList(redisConnectionMapList); resourceList.add(redis); HeraResource es = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/es/ozhera_es.yaml") .resourceType(ResourceTypeEnum.ES.getTypeName()) .resourceName("hera-es") .remark("local es") .build(); es.setDefaultYaml(); List<Map<String, String>> esConnectionMapList = new ArrayList<>(); esConnectionMapList.add(kvMap(HoConstant.KEY_ES_URL, "elasticsearch:9200", "es address, host:port")); esConnectionMapList.add(kvMap(HoConstant.KEY_ES_USERNAME, "", "es user name, optional", "0")); esConnectionMapList.add(kvMap(HoConstant.KEY_ES_PASSWORD, "", "es password, optional", "0")); es.setConnectionMapList(esConnectionMapList); resourceList.add(es); HeraResource rocketMQ = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/rocketmq/ozhera_rocketmq.yaml") .resourceType(ResourceTypeEnum.ROCKETMQ.getTypeName()) .resourceName("hera-rocketMQ") .remark("local rocketMQ") .build(); rocketMQ.setDefaultYaml(); List<Map<String, String>> rocketMQConnectionMapList = new ArrayList<>(); rocketMQConnectionMapList.add(kvMap(HoConstant.KEY_ROCKETMQ_NAMESERVER, "rocketmq-name-server-service:9876", "rocketMQ address,host:port")); rocketMQConnectionMapList.add(kvMap(HoConstant.KEY_ROCKETMQ_AK, "", "rocketMQ accessKey,optional", "0")); rocketMQConnectionMapList.add(kvMap(HoConstant.KEY_ROCKETMQ_SK, "", "rocketMQ secretKey,optional", "0")); rocketMQ.setConnectionMapList(rocketMQConnectionMapList); resourceList.add(rocketMQ); HeraResource nacos = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/nacos/ozhera_nacos.yml") .resourceType(ResourceTypeEnum.Nacos.getTypeName()) .resourceName("hera-nacos") .remark("load nacos") .defaultExtendConfigPath(new String[]{ "/ozhera_init/nacos/config/hera_app_config_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/hera_log_manager_open_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/hera_trace_config_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/log_stream_dataId_open_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/mi_tpc_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/mi_tpc_login_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/mimonitor_open_config_#_DEFAULT_GROUP.properties", "/ozhera_init/nacos/config/prometheus_agent_open_config_#_DEFAULT_GROUP.properties"}) .build(); nacos.setDefaultYaml(); nacos.setDefaultExtendConfig(); List<Map<String, String>> connectionMapList = new ArrayList<>(); connectionMapList.add(kvMap(HoConstant.KEY_NACOS_ADDRESS, "nacos:80", "nacos address, host:ip")); connectionMapList.add(kvMap(HoConstant.KEY_NACOS_USERNAME, "nacos", "nacos user name, optional", "0")); connectionMapList.add(kvMap(HoConstant.KEY_NACOS_PASSWORD, "nacos", "nacos password, optional", "0")); nacos.setConnectionMapList(connectionMapList); resourceList.add(nacos); HeraResource tpcLoginFe = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/tpc-login-fe/ozhera_tpc_login_fe.yml") .resourceType(ResourceTypeEnum.HERA_FE.getTypeName()) .resourceName("hera-tpc-login-fe") .remark("load tpc-login-fe") .build(); tpcLoginFe.setDefaultYaml(); List<Map<String, String>> tpcLoginFeConnectionMapList = new ArrayList<>(); tpcLoginFe.setConnectionMapList(tpcLoginFeConnectionMapList); resourceList.add(tpcLoginFe); HeraResource grafana = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/grafana/ozhera_grafana.yaml") .resourceType(ResourceTypeEnum.GRAFANA.getTypeName()) .resourceName("hera-grafana") .remark("local pv, Make sure the disk directory has been created in advance.") .build(); grafana.setDefaultYaml(); List<Map<String, String>> grafanaConnectionMapList = new ArrayList<>(); grafana.setConnectionMapList(grafanaConnectionMapList); resourceList.add(grafana); HeraResource prometheus = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/prometheus/ozhera_prometheus.yaml") .resourceType(ResourceTypeEnum.PROMETHEUS.getTypeName()) .resourceName("hera-prometheus") .remark("local pv, Make sure the disk directory has been created in advance.") .build(); prometheus.setDefaultYaml(); List<Map<String, String>> prometheusConnectionMapList = new ArrayList<>(); prometheus.setConnectionMapList(prometheusConnectionMapList); resourceList.add(prometheus); HeraResource heraFe = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/hera-fe/ozhera_fe.yml") .resourceType(ResourceTypeEnum.HERA_FE.getTypeName()) .resourceName("hera-fe") .remark("load hera-fe") .build(); heraFe.setDefaultYaml(); List<Map<String, String>> heraFeConnectionMapList = new ArrayList<>(); heraFe.setConnectionMapList(heraFeConnectionMapList); resourceList.add(heraFe); HeraResource alertManager = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/alertManager/ozhera_alertmanager.yaml") .resourceType(ResourceTypeEnum.ALERT_MANAGER.getTypeName()) .resourceName("hera-alertmanager") .remark("local pv, Make sure the disk directory has been created in advance.") .build(); alertManager.setDefaultYaml(); resourceList.add(alertManager); HeraResource tpcLogin = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/tpc-login/ozhera_tpc_login.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-tpc-login") .remark("load tpc-login") .build(); tpcLogin.setDefaultYaml(); resourceList.add(tpcLogin); HeraResource traceEtlEs = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/trace-etl-es/ozhera_trace_etl_es.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("trace-etl-es") .remark("load trace-etl-es") .build(); traceEtlEs.setDefaultYaml(); resourceList.add(traceEtlEs); HeraResource cadvisor = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/cadvisor/ozhera_cadvisor.yaml") .resourceType(ResourceTypeEnum.CADVISOR.getTypeName()) .resourceName("hera-cadvisor") .remark("local pv, Make sure the disk directory has been created in advance.") .build(); cadvisor.setDefaultYaml(); List<Map<String, String>> cadvisorConnectionMapList = new ArrayList<>(); cadvisor.setConnectionMapList(cadvisorConnectionMapList); resourceList.add(cadvisor); HeraResource node_exporter = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/node-exporter/ozhera_node-exporter.yaml") .resourceType(ResourceTypeEnum.NODE_EXPORTER.getTypeName()) .resourceName("hera-node-exporter") .remark("local pv, Make sure the disk directory has been created in advance.") .build(); node_exporter.setDefaultYaml(); List<Map<String, String>> node_exporterConnectionMapList = new ArrayList<>(); node_exporter.setConnectionMapList(node_exporterConnectionMapList); resourceList.add(node_exporter); HeraResource heraApp = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/hera-app/ozhera_app.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-app") .remark("load hera-app") .build(); heraApp.setDefaultYaml(); resourceList.add(heraApp); HeraResource logManager = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/log-manager/ozhera_log_manager.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-log-manager") .remark("load log-manager") .build(); logManager.setDefaultYaml(); resourceList.add(logManager); HeraResource logAgentServer = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/log-agent-server/ozhera_log_agent-server.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-log-agent-server") .remark("load log-agent-server") .build(); logAgentServer.setDefaultYaml(); resourceList.add(logAgentServer); HeraResource logStream = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/log-stream/ozhera_log_stream.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-log-stream") .remark("load log-stream") .build(); logStream.setDefaultYaml(); resourceList.add(logStream); HeraResource mimonitor = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/mimonitor/ozhera_mimonitor.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-mimonitor") .remark("load mimonitor") .build(); mimonitor.setDefaultYaml(); resourceList.add(mimonitor); HeraResource tpc = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/tpc/ozhera_tpc.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-tpc") .remark("load tpc") .build(); tpc.setDefaultYaml(); resourceList.add(tpc); HeraResource tpcFe = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/tpc-fe/ozhera_tpc_fe.yml") .resourceType(ResourceTypeEnum.HERA_FE.getTypeName()) .resourceName("hera-tpc-fe") .remark("load tpc-fe") .build(); tpcFe.setDefaultYaml(); resourceList.add(tpcFe); HeraResource traceEtlManager = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/trace-etl-manager/ozhera_trace_etl_manager.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-trace_etl_manager") .remark("load trace-etl-manager") .build(); traceEtlManager.setDefaultYaml(); resourceList.add(traceEtlManager); HeraResource traceEtlServer = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/trace-etl-server/ozhera_trace_etl_server.yml") .resourceType(ResourceTypeEnum.HERA_APP.getTypeName()) .resourceName("hera-trace-etl-server") .remark("load trace-etl-server") .build(); traceEtlServer.setDefaultYaml(); resourceList.add(traceEtlServer); HeraResource heraWebhook = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/webhook/ozhera_webhook_server.yaml") .resourceType(ResourceTypeEnum.HERA_WEBHOOK.getTypeName()) .resourceName("hera-webhook") .remark("load hera-webhook") .build(); heraWebhook.setDefaultYaml(); resourceList.add(heraWebhook); HeraResource demoServer = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/demo/ozhera_demo_server.yml") .resourceType(ResourceTypeEnum.OTHER.getTypeName()) .resourceName("hera-demo-server") .remark("load hera-demo-server") .build(); demoServer.setDefaultYaml(); resourceList.add(demoServer); HeraResource demoClient = HeraResource.builder() .needCreate(true) .required(true) .defaultYamlPath("/ozhera_init/demo/ozhera_demo_client.yml") .resourceType(ResourceTypeEnum.OTHER.getTypeName()) .resourceName("hera-demo-client") .remark("load hera-demo-client") .build(); demoClient.setDefaultYaml(); resourceList.add(demoClient); //todo other resource heraOperatorDefine.setHeraSpec(heraSpec); heraOperatorDefine.setHeraMeta(heraMeta); log.warn("##heraOperatorDefine load success##"); } catch (Exception e) { log.error("HeraOperatorController init error:", e); throw new RuntimeException("HeraOperatorController init error"); } } public HeraOperatorDefineDTO getResource() { return heraOperatorDefine; } public HeraOperatorDefineDTO updateResource(HeraOperatorDefineDTO heraOperatorDefine) { lock.lock(); try { preCheck(heraOperatorDefine); replacePlaceholder(heraOperatorDefine); this.heraOperatorDefine = heraOperatorDefine; return this.heraOperatorDefine; }finally { lock.unlock(); } } private void replacePlaceholder(HeraOperatorDefineDTO heraOperatorDefine) { HeraSpec heraSpec = heraOperatorDefine.getHeraSpec(); Map<String, String> params = new HashMap<>(); for (HeraResource heraResource : heraSpec.getResourceList()) { if (null != heraResource.getConnectionMapList()) { for (Map<String, String> m : heraResource.getConnectionMapList()) { params.put(m.get("key"), m.get("value")); } } if (ResourceTypeEnum.Nacos.getTypeName().equals(heraResource.getResourceType())) { List<PropConf> propList = heraResource.getPropList(); if (null != propList) { StringSubstitutor sub = new StringSubstitutor(params); for (PropConf propConf : propList) { String properties = propConf.getValue(); String replacedString = sub.replace(properties); propConf.setValue(replacedString); } } } } } private void preCheck(HeraOperatorDefineDTO heraOperatorDefine) { com.google.common.base.Preconditions.checkArgument(null != heraOperatorDefine.getHeraMeta(), "heraMeta can not be null"); com.google.common.base.Preconditions.checkArgument(null != heraOperatorDefine.getHeraMeta().getName()); com.google.common.base.Preconditions.checkArgument(null != heraOperatorDefine.getHeraMeta().getNamespace()); com.google.common.base.Preconditions.checkArgument(null != heraOperatorDefine.getHeraSpec()); com.google.common.base.Preconditions.checkArgument(null != heraOperatorDefine.getHeraSpec().getResourceList()); List<HeraResource> resourceList = heraOperatorDefine.getHeraSpec().getResourceList(); Set<String> resourceNameSet = new HashSet<>(); for (HeraResource hr : resourceList) { String resourceName = hr.getResourceName(); com.google.common.base.Preconditions.checkArgument(StringUtils.isNotBlank(resourceName)); if (resourceNameSet.contains(resourceName)) { throw new IllegalArgumentException(String.format("resourceName:%s must be unique", resourceName)); } resourceNameSet.add(resourceName); if (null != hr.getNeedCreate() && hr.getNeedCreate()) { Preconditions.checkArgument(StringUtils.isNotBlank(hr.getYamlStr()), String.format("resource:%s yaml content can not be empty", resourceName)); } } } public List<DeployStateDTO> crState() { List<DeployStateDTO> result = new ArrayList<>(); String namespace = heraOperatorDefine.getHeraMeta().getNamespace(); DeploymentList deploymentList = deploymentClient.inNamespace(namespace).list(); List<Deployment> list = deploymentList.getItems(); if (CollectionUtils.isEmpty(list)) { new ArrayList<>(); } for (Deployment deployment : list) { DeployStateDTO deployStateDTO = new DeployStateDTO(); boolean ready = true; String deploymentName = deployment.getMetadata().getName(); ; Integer replicas = deployment.getStatus().getReplicas(); Integer readyReplicas = deployment.getStatus().getReadyReplicas(); if (replicas != readyReplicas) { ready = false; } deployStateDTO.setReady(ready); deployStateDTO.setDeploymentName(deploymentName); deployStateDTO.setReadyState((null == readyReplicas ? 0 : readyReplicas) + "/" + replicas); deployStateDTO.setAge(deployment.getMetadata().getCreationTimestamp()); result.add(deployStateDTO); } return result; } public List<PodStateDTO> crState1() { List<PodStateDTO> podStateDTOList = new ArrayList<>(); String namespace = heraOperatorDefine.getHeraMeta().getNamespace(); PodList podList = kubernetesClient.pods().inNamespace(namespace).list(); for (Pod pod : podList.getItems()) { List<ContainerStatus> containerStatusList = pod.getStatus().getContainerStatuses(); if (CollectionUtils.isEmpty(containerStatusList)) { continue; } containerStatusList.stream().forEach(c -> { PodStateDTO podStateDTO = new PodStateDTO(); podStateDTO.setPodName(pod.getMetadata().getName()); podStateDTO.setNamespace(pod.getMetadata().getNamespace()); podStateDTO.setImage(c.getImage()); podStateDTO.setContainerID(c.getContainerID()); podStateDTO.setReady(c.getReady()); podStateDTO.setStarted(c.getStarted()); podStateDTO.setLastState(c.getLastState()); podStateDTO.setState(c.getState()); podStateDTOList.add(podStateDTO); }); } log.warn("hera operator status:{}", gson.toJson(podStateDTOList)); return podStateDTOList; } public boolean crExists(String namespace) { MixedOperation<HeraBootstrap, KubernetesResourceList<HeraBootstrap>, Resource<HeraBootstrap>> heraMixedOperation = kubernetesClient.resources(HeraBootstrap.class); List<HeraBootstrap> crList = heraMixedOperation.list().getItems(); return CollectionUtils.isNotEmpty(crList); } public HeraStatus createOrReplaceCr() { HeraBootstrap heraBootstrap = new HeraBootstrap(); HeraStatus heraStatus = new HeraStatus(); ObjectMeta objectMeta = new ObjectMeta(); String namespace = heraOperatorDefine.getHeraMeta().getNamespace(); MixedOperation<HeraBootstrap, KubernetesResourceList<HeraBootstrap>, Resource<HeraBootstrap>> heraMixedOperation = kubernetesClient.resources(HeraBootstrap.class); HeraBootstrap result; List<HeraBootstrap> crList = heraMixedOperation.list().getItems(); if (CollectionUtils.isEmpty(crList)) { objectMeta.setNamespace(namespace); objectMeta.setName(heraOperatorDefine.getHeraMeta().getName()); heraBootstrap.setSpec(heraOperatorDefine.getHeraSpec()); heraBootstrap.setStatus(heraStatus); heraBootstrap.setMetadata(objectMeta); result = heraMixedOperation.inNamespace(namespace).create(heraBootstrap); } else { HeraBootstrap exists = crList.get(0); exists.setSpec(heraOperatorDefine.getHeraSpec()); exists.setStatus(heraStatus); result = heraMixedOperation.inNamespace(namespace).replace(exists); } log.warn("hera operator result:{}", gson.toJson(result)); return result.getStatus(); } public Boolean deleteCr() { HeraBootstrap heraBootstrap = new HeraBootstrap(); HeraStatus heraStatus = new HeraStatus(); ObjectMeta objectMeta = new ObjectMeta(); String namespace = heraOperatorDefine.getHeraMeta().getNamespace(); objectMeta.setNamespace(namespace); objectMeta.setName(heraOperatorDefine.getHeraMeta().getName()); heraBootstrap.setSpec(heraOperatorDefine.getHeraSpec()); heraBootstrap.setStatus(heraStatus); heraBootstrap.setMetadata(objectMeta); MixedOperation<HeraBootstrap, KubernetesResourceList<HeraBootstrap>, Resource<HeraBootstrap>> heraMixedOperation = kubernetesClient.resources(HeraBootstrap.class); Boolean result = heraMixedOperation.inNamespace(namespace).delete(heraBootstrap); log.warn("hera operator delete result:{}", result); return result; } public void deleteService(List<String> serviceNameList, String namespace, String serviceType) { List<io.fabric8.kubernetes.api.model.Service> serviceList = listService(serviceNameList, namespace, serviceType); if (CollectionUtils.isNotEmpty(serviceList)) { kubernetesClient.services().inNamespace(namespace).delete(serviceList); } } public List<io.fabric8.kubernetes.api.model.Service> createAndListService(List<String> serviceNameList, String namespace, String yamlPath, String serviceType) throws InterruptedException { // Filter service by name List<io.fabric8.kubernetes.api.model.Service> serviceList = listService(serviceNameList, namespace); if (CollectionUtils.isEmpty(serviceList)) { String yaml = FileUtils.readResourceFile(yamlPath); k8sUtilBean.applyYaml(yaml, namespace, "add"); } TimeUnit.SECONDS.sleep(2); // Filter service by name + type. return listService(serviceNameList, namespace, serviceType); } public boolean checkLbServiceFailed(List<io.fabric8.kubernetes.api.model.Service> serviceList, String serviceType) { if (CollectionUtils.isEmpty(serviceList)) { return true; } Map<String, String> ipPortMap = getServiceIpPort(serviceList, serviceType); if (ipPortMap.size() == serviceList.size()) { return false; } for (io.fabric8.kubernetes.api.model.Service s : serviceList) { String timestamp = s.getMetadata().getCreationTimestamp(); Long seconds = diffSeconds(timestamp); // 37 seconds have not yet been determined as a failed service creation. if (seconds > 37) { log.warn("serviceType:{} create failed : cost too many time:{}s", serviceType, seconds); return true; } } return false; } private long diffSeconds(String timestamp) { Instant instant = Instant.parse(timestamp); ZonedDateTime utcDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")); ZonedDateTime beijingDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai")); ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai")); long diffSeconds = currentDateTime.toEpochSecond() - beijingDateTime.toEpochSecond(); return diffSeconds; } private List<io.fabric8.kubernetes.api.model.Service> listService(List<String> serviceNameList, String namespace) { ServiceList serviceList = kubernetesClient.services().inNamespace(namespace).list(); return serviceList.getItems().stream() .filter(s -> serviceNameList.contains(s.getMetadata().getName())) .collect(Collectors.toList()); } private List<io.fabric8.kubernetes.api.model.Service> listService(List<String> serviceNameList, String namespace, String serviceType) { ServiceList serviceList = kubernetesClient.services().inNamespace(namespace).list(); return serviceList.getItems().stream() .filter(s -> serviceNameList.contains(s.getMetadata().getName())) .filter(s -> serviceType.equalsIgnoreCase(s.getSpec().getType())) .collect(Collectors.toList()); } public Map<String, String> getServiceIpPort(List<io.fabric8.kubernetes.api.model.Service> serviceList, String serviceType) { Map<String, String> ipPortMap = new HashMap<>(); String nodePortIP = null; if ("NodePort".equals(serviceType)) { List<Node> nodeList = kubernetesClient.nodes().list().getItems(); Optional<NodeAddress> nodeAddress = nodeList.get(0).getStatus().getAddresses().stream() .filter(address -> "InternalIP".equals(address.getType())).findAny(); if (!nodeAddress.isPresent()) { throw new RuntimeException("cluster node have no internalIP"); } nodePortIP = nodeAddress.get().getAddress(); if (StringUtils.isBlank(nodePortIP)) { throw new RuntimeException("cluster node get null [NodePort] IP"); } } for (io.fabric8.kubernetes.api.model.Service service : serviceList) { String serviceName = service.getMetadata().getName(); ServiceSpec serviceSpec = service.getSpec(); String type = serviceSpec.getType(); if ("NodePort".equals(type)) { Integer nodePort = serviceSpec.getPorts().get(0).getNodePort(); ipPortMap.put(serviceName, nodePortIP + ":" + nodePort); } else if ("LoadBalancer".equals(type)) { LoadBalancerStatus lsStatus = service.getStatus().getLoadBalancer(); List<LoadBalancerIngress> lbIngress = lsStatus.getIngress(); if (CollectionUtils.isNotEmpty(lbIngress)) { //todo The port is temporarily hardcoded. ipPortMap.put(serviceName, lbIngress.get(0).getIp() + ":80"); } } } return ipPortMap; } public String getServiceType(List<io.fabric8.kubernetes.api.model.Service> serviceList) { for (io.fabric8.kubernetes.api.model.Service service : serviceList) { ServiceSpec serviceSpec = service.getSpec(); String type = serviceSpec.getType(); return type; } return ""; } private Map<String, String> kvMap(String key, String value, String remark) { return this.kvMap(key, value, remark, "1"); } private Map<String, String> kvMap(String key, String value, String remark, String required) { Map<String, String> map = new HashMap<>(); map.put("key", key); map.put("value", value); map.put("remark", remark); map.put("required", required); return map; } public void executeSqlScript(File[] sqlFiles, String url, String userName, String pwd) { Connection con = null; try { DriverManager.registerDriver(new Driver()); //Getting the connection con = DriverManager.getConnection(url, userName, pwd); System.out.println("Connection established......"); for (File sqlFile : sqlFiles) { //Initialize the script runner ScriptRunner sr = new ScriptRunner(con); //Creating a reader object Reader reader = new BufferedReader(new FileReader(sqlFile)); //Running the script sr.runScript(reader); reader.close(); } } catch (Exception e) { log.error("sql execute error", e); } finally { if (null != con) { try { con.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
googleapis/google-cloud-java
36,636
java-biglake/proto-google-cloud-biglake-v1/src/main/java/com/google/cloud/bigquery/biglake/v1/ListCatalogsResponse.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/bigquery/biglake/v1/metastore.proto // Protobuf Java Version: 3.25.8 package com.google.cloud.bigquery.biglake.v1; /** * * * <pre> * Response message for the ListCatalogs method. * </pre> * * Protobuf type {@code google.cloud.bigquery.biglake.v1.ListCatalogsResponse} */ public final class ListCatalogsResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.biglake.v1.ListCatalogsResponse) ListCatalogsResponseOrBuilder { private static final long serialVersionUID = 0L; // Use ListCatalogsResponse.newBuilder() to construct. private ListCatalogsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ListCatalogsResponse() { catalogs_ = java.util.Collections.emptyList(); nextPageToken_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ListCatalogsResponse(); } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_ListCatalogsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_ListCatalogsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.class, com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.Builder.class); } public static final int CATALOGS_FIELD_NUMBER = 1; @SuppressWarnings("serial") private java.util.List<com.google.cloud.bigquery.biglake.v1.Catalog> catalogs_; /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ @java.lang.Override public java.util.List<com.google.cloud.bigquery.biglake.v1.Catalog> getCatalogsList() { return catalogs_; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ @java.lang.Override public java.util.List<? extends com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder> getCatalogsOrBuilderList() { return catalogs_; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ @java.lang.Override public int getCatalogsCount() { return catalogs_.size(); } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ @java.lang.Override public com.google.cloud.bigquery.biglake.v1.Catalog getCatalogs(int index) { return catalogs_.get(index); } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ @java.lang.Override public com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder getCatalogsOrBuilder(int index) { return catalogs_.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 < catalogs_.size(); i++) { output.writeMessage(1, catalogs_.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 < catalogs_.size(); i++) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, catalogs_.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.bigquery.biglake.v1.ListCatalogsResponse)) { return super.equals(obj); } com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse other = (com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse) obj; if (!getCatalogsList().equals(other.getCatalogsList())) 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 (getCatalogsCount() > 0) { hash = (37 * hash) + CATALOGS_FIELD_NUMBER; hash = (53 * hash) + getCatalogsList().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.bigquery.biglake.v1.ListCatalogsResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse 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.bigquery.biglake.v1.ListCatalogsResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse 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.bigquery.biglake.v1.ListCatalogsResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse 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.bigquery.biglake.v1.ListCatalogsResponse parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse 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.bigquery.biglake.v1.ListCatalogsResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse 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.bigquery.biglake.v1.ListCatalogsResponse 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 ListCatalogs method. * </pre> * * Protobuf type {@code google.cloud.bigquery.biglake.v1.ListCatalogsResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.biglake.v1.ListCatalogsResponse) com.google.cloud.bigquery.biglake.v1.ListCatalogsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_ListCatalogsResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_ListCatalogsResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.class, com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.Builder.class); } // Construct using com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); bitField0_ = 0; if (catalogsBuilder_ == null) { catalogs_ = java.util.Collections.emptyList(); } else { catalogs_ = null; catalogsBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); nextPageToken_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.biglake.v1.MetastoreProto .internal_static_google_cloud_bigquery_biglake_v1_ListCatalogsResponse_descriptor; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse getDefaultInstanceForType() { return com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse build() { com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse buildPartial() { com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse result = new com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse(this); buildPartialRepeatedFields(result); if (bitField0_ != 0) { buildPartial0(result); } onBuilt(); return result; } private void buildPartialRepeatedFields( com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse result) { if (catalogsBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { catalogs_ = java.util.Collections.unmodifiableList(catalogs_); bitField0_ = (bitField0_ & ~0x00000001); } result.catalogs_ = catalogs_; } else { result.catalogs_ = catalogsBuilder_.build(); } } private void buildPartial0(com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse 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.bigquery.biglake.v1.ListCatalogsResponse) { return mergeFrom((com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse other) { if (other == com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse.getDefaultInstance()) return this; if (catalogsBuilder_ == null) { if (!other.catalogs_.isEmpty()) { if (catalogs_.isEmpty()) { catalogs_ = other.catalogs_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureCatalogsIsMutable(); catalogs_.addAll(other.catalogs_); } onChanged(); } } else { if (!other.catalogs_.isEmpty()) { if (catalogsBuilder_.isEmpty()) { catalogsBuilder_.dispose(); catalogsBuilder_ = null; catalogs_ = other.catalogs_; bitField0_ = (bitField0_ & ~0x00000001); catalogsBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getCatalogsFieldBuilder() : null; } else { catalogsBuilder_.addAllMessages(other.catalogs_); } } } 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.bigquery.biglake.v1.Catalog m = input.readMessage( com.google.cloud.bigquery.biglake.v1.Catalog.parser(), extensionRegistry); if (catalogsBuilder_ == null) { ensureCatalogsIsMutable(); catalogs_.add(m); } else { catalogsBuilder_.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.bigquery.biglake.v1.Catalog> catalogs_ = java.util.Collections.emptyList(); private void ensureCatalogsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { catalogs_ = new java.util.ArrayList<com.google.cloud.bigquery.biglake.v1.Catalog>(catalogs_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.biglake.v1.Catalog, com.google.cloud.bigquery.biglake.v1.Catalog.Builder, com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder> catalogsBuilder_; /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public java.util.List<com.google.cloud.bigquery.biglake.v1.Catalog> getCatalogsList() { if (catalogsBuilder_ == null) { return java.util.Collections.unmodifiableList(catalogs_); } else { return catalogsBuilder_.getMessageList(); } } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public int getCatalogsCount() { if (catalogsBuilder_ == null) { return catalogs_.size(); } else { return catalogsBuilder_.getCount(); } } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public com.google.cloud.bigquery.biglake.v1.Catalog getCatalogs(int index) { if (catalogsBuilder_ == null) { return catalogs_.get(index); } else { return catalogsBuilder_.getMessage(index); } } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder setCatalogs(int index, com.google.cloud.bigquery.biglake.v1.Catalog value) { if (catalogsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCatalogsIsMutable(); catalogs_.set(index, value); onChanged(); } else { catalogsBuilder_.setMessage(index, value); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder setCatalogs( int index, com.google.cloud.bigquery.biglake.v1.Catalog.Builder builderForValue) { if (catalogsBuilder_ == null) { ensureCatalogsIsMutable(); catalogs_.set(index, builderForValue.build()); onChanged(); } else { catalogsBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder addCatalogs(com.google.cloud.bigquery.biglake.v1.Catalog value) { if (catalogsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCatalogsIsMutable(); catalogs_.add(value); onChanged(); } else { catalogsBuilder_.addMessage(value); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder addCatalogs(int index, com.google.cloud.bigquery.biglake.v1.Catalog value) { if (catalogsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureCatalogsIsMutable(); catalogs_.add(index, value); onChanged(); } else { catalogsBuilder_.addMessage(index, value); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder addCatalogs( com.google.cloud.bigquery.biglake.v1.Catalog.Builder builderForValue) { if (catalogsBuilder_ == null) { ensureCatalogsIsMutable(); catalogs_.add(builderForValue.build()); onChanged(); } else { catalogsBuilder_.addMessage(builderForValue.build()); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder addCatalogs( int index, com.google.cloud.bigquery.biglake.v1.Catalog.Builder builderForValue) { if (catalogsBuilder_ == null) { ensureCatalogsIsMutable(); catalogs_.add(index, builderForValue.build()); onChanged(); } else { catalogsBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder addAllCatalogs( java.lang.Iterable<? extends com.google.cloud.bigquery.biglake.v1.Catalog> values) { if (catalogsBuilder_ == null) { ensureCatalogsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, catalogs_); onChanged(); } else { catalogsBuilder_.addAllMessages(values); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder clearCatalogs() { if (catalogsBuilder_ == null) { catalogs_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { catalogsBuilder_.clear(); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public Builder removeCatalogs(int index) { if (catalogsBuilder_ == null) { ensureCatalogsIsMutable(); catalogs_.remove(index); onChanged(); } else { catalogsBuilder_.remove(index); } return this; } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public com.google.cloud.bigquery.biglake.v1.Catalog.Builder getCatalogsBuilder(int index) { return getCatalogsFieldBuilder().getBuilder(index); } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder getCatalogsOrBuilder(int index) { if (catalogsBuilder_ == null) { return catalogs_.get(index); } else { return catalogsBuilder_.getMessageOrBuilder(index); } } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public java.util.List<? extends com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder> getCatalogsOrBuilderList() { if (catalogsBuilder_ != null) { return catalogsBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(catalogs_); } } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public com.google.cloud.bigquery.biglake.v1.Catalog.Builder addCatalogsBuilder() { return getCatalogsFieldBuilder() .addBuilder(com.google.cloud.bigquery.biglake.v1.Catalog.getDefaultInstance()); } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public com.google.cloud.bigquery.biglake.v1.Catalog.Builder addCatalogsBuilder(int index) { return getCatalogsFieldBuilder() .addBuilder(index, com.google.cloud.bigquery.biglake.v1.Catalog.getDefaultInstance()); } /** * * * <pre> * The catalogs from the specified project. * </pre> * * <code>repeated .google.cloud.bigquery.biglake.v1.Catalog catalogs = 1;</code> */ public java.util.List<com.google.cloud.bigquery.biglake.v1.Catalog.Builder> getCatalogsBuilderList() { return getCatalogsFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.biglake.v1.Catalog, com.google.cloud.bigquery.biglake.v1.Catalog.Builder, com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder> getCatalogsFieldBuilder() { if (catalogsBuilder_ == null) { catalogsBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< com.google.cloud.bigquery.biglake.v1.Catalog, com.google.cloud.bigquery.biglake.v1.Catalog.Builder, com.google.cloud.bigquery.biglake.v1.CatalogOrBuilder>( catalogs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); catalogs_ = null; } return catalogsBuilder_; } 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.bigquery.biglake.v1.ListCatalogsResponse) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.biglake.v1.ListCatalogsResponse) private static final com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse(); } public static com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ListCatalogsResponse> PARSER = new com.google.protobuf.AbstractParser<ListCatalogsResponse>() { @java.lang.Override public ListCatalogsResponse 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<ListCatalogsResponse> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ListCatalogsResponse> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.biglake.v1.ListCatalogsResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
googleapis/google-cloud-java
36,921
java-dialogflow-cx/google-cloud-dialogflow-cx/src/main/java/com/google/cloud/dialogflow/cx/v3/stub/EntityTypesStubSettings.java
/* * Copyright 2025 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.dialogflow.cx.v3.stub; import static com.google.cloud.dialogflow.cx.v3.EntityTypesClient.ListEntityTypesPagedResponse; import static com.google.cloud.dialogflow.cx.v3.EntityTypesClient.ListLocationsPagedResponse; import com.google.api.core.ApiFunction; import com.google.api.core.ApiFuture; import com.google.api.core.BetaApi; import com.google.api.core.ObsoleteApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.grpc.ProtoOperationTransformers; import com.google.api.gax.httpjson.GaxHttpJsonProperties; import com.google.api.gax.httpjson.HttpJsonTransportChannel; import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider; import com.google.api.gax.longrunning.OperationSnapshot; import com.google.api.gax.longrunning.OperationTimedPollAlgorithm; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiCallContext; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.OperationCallSettings; import com.google.api.gax.rpc.PageContext; import com.google.api.gax.rpc.PagedCallSettings; import com.google.api.gax.rpc.PagedListDescriptor; import com.google.api.gax.rpc.PagedListResponseFactory; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.dialogflow.cx.v3.CreateEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3.DeleteEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3.EntityType; import com.google.cloud.dialogflow.cx.v3.ExportEntityTypesMetadata; import com.google.cloud.dialogflow.cx.v3.ExportEntityTypesRequest; import com.google.cloud.dialogflow.cx.v3.ExportEntityTypesResponse; import com.google.cloud.dialogflow.cx.v3.GetEntityTypeRequest; import com.google.cloud.dialogflow.cx.v3.ImportEntityTypesMetadata; import com.google.cloud.dialogflow.cx.v3.ImportEntityTypesRequest; import com.google.cloud.dialogflow.cx.v3.ImportEntityTypesResponse; import com.google.cloud.dialogflow.cx.v3.ListEntityTypesRequest; import com.google.cloud.dialogflow.cx.v3.ListEntityTypesResponse; import com.google.cloud.dialogflow.cx.v3.UpdateEntityTypeRequest; 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.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.longrunning.Operation; import com.google.protobuf.Empty; import java.io.IOException; import java.time.Duration; import java.util.List; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link EntityTypesStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li>The default service address (dialogflow.googleapis.com) and default port (443) are used. * <li>Credentials are acquired automatically through Application Default Credentials. * <li>Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the * [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings) * of getEntityType: * * <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 * EntityTypesStubSettings.Builder entityTypesSettingsBuilder = * EntityTypesStubSettings.newBuilder(); * entityTypesSettingsBuilder * .getEntityTypeSettings() * .setRetrySettings( * entityTypesSettingsBuilder * .getEntityTypeSettings() * .getRetrySettings() * .toBuilder() * .setInitialRetryDelayDuration(Duration.ofSeconds(1)) * .setInitialRpcTimeoutDuration(Duration.ofSeconds(5)) * .setMaxAttempts(5) * .setMaxRetryDelayDuration(Duration.ofSeconds(30)) * .setMaxRpcTimeoutDuration(Duration.ofSeconds(60)) * .setRetryDelayMultiplier(1.3) * .setRpcTimeoutMultiplier(1.5) * .setTotalTimeoutDuration(Duration.ofSeconds(300)) * .build()); * EntityTypesStubSettings entityTypesSettings = entityTypesSettingsBuilder.build(); * }</pre> * * Please refer to the [Client Side Retry * Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for * additional support in setting retries. * * <p>To configure the RetrySettings of a Long Running Operation method, create an * OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to * configure the RetrySettings for exportEntityTypes: * * <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 * EntityTypesStubSettings.Builder entityTypesSettingsBuilder = * EntityTypesStubSettings.newBuilder(); * TimedRetryAlgorithm timedRetryAlgorithm = * OperationalTimedPollAlgorithm.create( * RetrySettings.newBuilder() * .setInitialRetryDelayDuration(Duration.ofMillis(500)) * .setRetryDelayMultiplier(1.5) * .setMaxRetryDelayDuration(Duration.ofMillis(5000)) * .setTotalTimeoutDuration(Duration.ofHours(24)) * .build()); * entityTypesSettingsBuilder * .createClusterOperationSettings() * .setPollingAlgorithm(timedRetryAlgorithm) * .build(); * }</pre> */ @Generated("by gapic-generator-java") public class EntityTypesStubSettings extends StubSettings<EntityTypesStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder() .add("https://www.googleapis.com/auth/cloud-platform") .add("https://www.googleapis.com/auth/dialogflow") .build(); private final UnaryCallSettings<GetEntityTypeRequest, EntityType> getEntityTypeSettings; private final UnaryCallSettings<CreateEntityTypeRequest, EntityType> createEntityTypeSettings; private final UnaryCallSettings<UpdateEntityTypeRequest, EntityType> updateEntityTypeSettings; private final UnaryCallSettings<DeleteEntityTypeRequest, Empty> deleteEntityTypeSettings; private final PagedCallSettings< ListEntityTypesRequest, ListEntityTypesResponse, ListEntityTypesPagedResponse> listEntityTypesSettings; private final UnaryCallSettings<ExportEntityTypesRequest, Operation> exportEntityTypesSettings; private final OperationCallSettings< ExportEntityTypesRequest, ExportEntityTypesResponse, ExportEntityTypesMetadata> exportEntityTypesOperationSettings; private final UnaryCallSettings<ImportEntityTypesRequest, Operation> importEntityTypesSettings; private final OperationCallSettings< ImportEntityTypesRequest, ImportEntityTypesResponse, ImportEntityTypesMetadata> importEntityTypesOperationSettings; private final PagedCallSettings< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings; private final UnaryCallSettings<GetLocationRequest, Location> getLocationSettings; private static final PagedListDescriptor< ListEntityTypesRequest, ListEntityTypesResponse, EntityType> LIST_ENTITY_TYPES_PAGE_STR_DESC = new PagedListDescriptor<ListEntityTypesRequest, ListEntityTypesResponse, EntityType>() { @Override public String emptyToken() { return ""; } @Override public ListEntityTypesRequest injectToken( ListEntityTypesRequest payload, String token) { return ListEntityTypesRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListEntityTypesRequest injectPageSize( ListEntityTypesRequest payload, int pageSize) { return ListEntityTypesRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListEntityTypesRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListEntityTypesResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<EntityType> extractResources(ListEntityTypesResponse payload) { return payload.getEntityTypesList(); } }; private static final PagedListDescriptor<ListLocationsRequest, ListLocationsResponse, Location> LIST_LOCATIONS_PAGE_STR_DESC = new PagedListDescriptor<ListLocationsRequest, ListLocationsResponse, Location>() { @Override public String emptyToken() { return ""; } @Override public ListLocationsRequest injectToken(ListLocationsRequest payload, String token) { return ListLocationsRequest.newBuilder(payload).setPageToken(token).build(); } @Override public ListLocationsRequest injectPageSize(ListLocationsRequest payload, int pageSize) { return ListLocationsRequest.newBuilder(payload).setPageSize(pageSize).build(); } @Override public Integer extractPageSize(ListLocationsRequest payload) { return payload.getPageSize(); } @Override public String extractNextToken(ListLocationsResponse payload) { return payload.getNextPageToken(); } @Override public Iterable<Location> extractResources(ListLocationsResponse payload) { return payload.getLocationsList(); } }; private static final PagedListResponseFactory< ListEntityTypesRequest, ListEntityTypesResponse, ListEntityTypesPagedResponse> LIST_ENTITY_TYPES_PAGE_STR_FACT = new PagedListResponseFactory< ListEntityTypesRequest, ListEntityTypesResponse, ListEntityTypesPagedResponse>() { @Override public ApiFuture<ListEntityTypesPagedResponse> getFuturePagedResponse( UnaryCallable<ListEntityTypesRequest, ListEntityTypesResponse> callable, ListEntityTypesRequest request, ApiCallContext context, ApiFuture<ListEntityTypesResponse> futureResponse) { PageContext<ListEntityTypesRequest, ListEntityTypesResponse, EntityType> pageContext = PageContext.create(callable, LIST_ENTITY_TYPES_PAGE_STR_DESC, request, context); return ListEntityTypesPagedResponse.createAsync(pageContext, futureResponse); } }; private static final PagedListResponseFactory< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> LIST_LOCATIONS_PAGE_STR_FACT = new PagedListResponseFactory< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>() { @Override public ApiFuture<ListLocationsPagedResponse> getFuturePagedResponse( UnaryCallable<ListLocationsRequest, ListLocationsResponse> callable, ListLocationsRequest request, ApiCallContext context, ApiFuture<ListLocationsResponse> futureResponse) { PageContext<ListLocationsRequest, ListLocationsResponse, Location> pageContext = PageContext.create(callable, LIST_LOCATIONS_PAGE_STR_DESC, request, context); return ListLocationsPagedResponse.createAsync(pageContext, futureResponse); } }; /** Returns the object with the settings used for calls to getEntityType. */ public UnaryCallSettings<GetEntityTypeRequest, EntityType> getEntityTypeSettings() { return getEntityTypeSettings; } /** Returns the object with the settings used for calls to createEntityType. */ public UnaryCallSettings<CreateEntityTypeRequest, EntityType> createEntityTypeSettings() { return createEntityTypeSettings; } /** Returns the object with the settings used for calls to updateEntityType. */ public UnaryCallSettings<UpdateEntityTypeRequest, EntityType> updateEntityTypeSettings() { return updateEntityTypeSettings; } /** Returns the object with the settings used for calls to deleteEntityType. */ public UnaryCallSettings<DeleteEntityTypeRequest, Empty> deleteEntityTypeSettings() { return deleteEntityTypeSettings; } /** Returns the object with the settings used for calls to listEntityTypes. */ public PagedCallSettings< ListEntityTypesRequest, ListEntityTypesResponse, ListEntityTypesPagedResponse> listEntityTypesSettings() { return listEntityTypesSettings; } /** Returns the object with the settings used for calls to exportEntityTypes. */ public UnaryCallSettings<ExportEntityTypesRequest, Operation> exportEntityTypesSettings() { return exportEntityTypesSettings; } /** Returns the object with the settings used for calls to exportEntityTypes. */ public OperationCallSettings< ExportEntityTypesRequest, ExportEntityTypesResponse, ExportEntityTypesMetadata> exportEntityTypesOperationSettings() { return exportEntityTypesOperationSettings; } /** Returns the object with the settings used for calls to importEntityTypes. */ public UnaryCallSettings<ImportEntityTypesRequest, Operation> importEntityTypesSettings() { return importEntityTypesSettings; } /** Returns the object with the settings used for calls to importEntityTypes. */ public OperationCallSettings< ImportEntityTypesRequest, ImportEntityTypesResponse, ImportEntityTypesMetadata> importEntityTypesOperationSettings() { return importEntityTypesOperationSettings; } /** Returns the object with the settings used for calls to listLocations. */ public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return listLocationsSettings; } /** Returns the object with the settings used for calls to getLocation. */ public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() { return getLocationSettings; } public EntityTypesStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcEntityTypesStub.create(this); } if (getTransportChannelProvider() .getTransportName() .equals(HttpJsonTransportChannel.getHttpJsonTransportName())) { return HttpJsonEntityTypesStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns the default service name. */ @Override public String getServiceName() { return "dialogflow"; } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ @ObsoleteApi("Use getEndpoint() instead") public static String getDefaultEndpoint() { return "dialogflow.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "dialogflow.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder() .setScopesToApply(DEFAULT_SERVICE_SCOPES) .setUseJwtAccessWithScope(true); } /** Returns a builder for the default gRPC ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } /** Returns a builder for the default REST ChannelProvider for this service. */ @BetaApi public static InstantiatingHttpJsonChannelProvider.Builder defaultHttpJsonTransportProviderBuilder() { return InstantiatingHttpJsonChannelProvider.newBuilder(); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(EntityTypesStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(EntityTypesStubSettings.class)) .setTransportToken( GaxHttpJsonProperties.getHttpJsonTokenName(), GaxHttpJsonProperties.getHttpJsonVersion()); } public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return EntityTypesStubSettings.defaultGrpcApiClientHeaderProviderBuilder(); } /** Returns a new gRPC builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new REST builder for this class. */ public static Builder newHttpJsonBuilder() { return Builder.createHttpJsonDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected EntityTypesStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); getEntityTypeSettings = settingsBuilder.getEntityTypeSettings().build(); createEntityTypeSettings = settingsBuilder.createEntityTypeSettings().build(); updateEntityTypeSettings = settingsBuilder.updateEntityTypeSettings().build(); deleteEntityTypeSettings = settingsBuilder.deleteEntityTypeSettings().build(); listEntityTypesSettings = settingsBuilder.listEntityTypesSettings().build(); exportEntityTypesSettings = settingsBuilder.exportEntityTypesSettings().build(); exportEntityTypesOperationSettings = settingsBuilder.exportEntityTypesOperationSettings().build(); importEntityTypesSettings = settingsBuilder.importEntityTypesSettings().build(); importEntityTypesOperationSettings = settingsBuilder.importEntityTypesOperationSettings().build(); listLocationsSettings = settingsBuilder.listLocationsSettings().build(); getLocationSettings = settingsBuilder.getLocationSettings().build(); } /** Builder for EntityTypesStubSettings. */ public static class Builder extends StubSettings.Builder<EntityTypesStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder<GetEntityTypeRequest, EntityType> getEntityTypeSettings; private final UnaryCallSettings.Builder<CreateEntityTypeRequest, EntityType> createEntityTypeSettings; private final UnaryCallSettings.Builder<UpdateEntityTypeRequest, EntityType> updateEntityTypeSettings; private final UnaryCallSettings.Builder<DeleteEntityTypeRequest, Empty> deleteEntityTypeSettings; private final PagedCallSettings.Builder< ListEntityTypesRequest, ListEntityTypesResponse, ListEntityTypesPagedResponse> listEntityTypesSettings; private final UnaryCallSettings.Builder<ExportEntityTypesRequest, Operation> exportEntityTypesSettings; private final OperationCallSettings.Builder< ExportEntityTypesRequest, ExportEntityTypesResponse, ExportEntityTypesMetadata> exportEntityTypesOperationSettings; private final UnaryCallSettings.Builder<ImportEntityTypesRequest, Operation> importEntityTypesSettings; private final OperationCallSettings.Builder< ImportEntityTypesRequest, ImportEntityTypesResponse, ImportEntityTypesMetadata> importEntityTypesOperationSettings; private final PagedCallSettings.Builder< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings; private final UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "retry_policy_0_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE))); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(100L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelayDuration(Duration.ofMillis(60000L)) .setInitialRpcTimeoutDuration(Duration.ofMillis(60000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ofMillis(60000L)) .setTotalTimeoutDuration(Duration.ofMillis(60000L)) .build(); definitions.put("retry_policy_0_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); getEntityTypeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); createEntityTypeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); updateEntityTypeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); deleteEntityTypeSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); listEntityTypesSettings = PagedCallSettings.newBuilder(LIST_ENTITY_TYPES_PAGE_STR_FACT); exportEntityTypesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); exportEntityTypesOperationSettings = OperationCallSettings.newBuilder(); importEntityTypesSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); importEntityTypesOperationSettings = OperationCallSettings.newBuilder(); listLocationsSettings = PagedCallSettings.newBuilder(LIST_LOCATIONS_PAGE_STR_FACT); getLocationSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( getEntityTypeSettings, createEntityTypeSettings, updateEntityTypeSettings, deleteEntityTypeSettings, listEntityTypesSettings, exportEntityTypesSettings, importEntityTypesSettings, listLocationsSettings, getLocationSettings); initDefaults(this); } protected Builder(EntityTypesStubSettings settings) { super(settings); getEntityTypeSettings = settings.getEntityTypeSettings.toBuilder(); createEntityTypeSettings = settings.createEntityTypeSettings.toBuilder(); updateEntityTypeSettings = settings.updateEntityTypeSettings.toBuilder(); deleteEntityTypeSettings = settings.deleteEntityTypeSettings.toBuilder(); listEntityTypesSettings = settings.listEntityTypesSettings.toBuilder(); exportEntityTypesSettings = settings.exportEntityTypesSettings.toBuilder(); exportEntityTypesOperationSettings = settings.exportEntityTypesOperationSettings.toBuilder(); importEntityTypesSettings = settings.importEntityTypesSettings.toBuilder(); importEntityTypesOperationSettings = settings.importEntityTypesOperationSettings.toBuilder(); listLocationsSettings = settings.listLocationsSettings.toBuilder(); getLocationSettings = settings.getLocationSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of( getEntityTypeSettings, createEntityTypeSettings, updateEntityTypeSettings, deleteEntityTypeSettings, listEntityTypesSettings, exportEntityTypesSettings, importEntityTypesSettings, listLocationsSettings, getLocationSettings); } private static Builder createDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder createHttpJsonDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultHttpJsonTransportProviderBuilder().build()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultHttpJsonApiClientHeaderProviderBuilder().build()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .getEntityTypeSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .createEntityTypeSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .updateEntityTypeSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .deleteEntityTypeSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .listEntityTypesSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .exportEntityTypesSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .importEntityTypesSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .listLocationsSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .getLocationSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); builder .exportEntityTypesOperationSettings() .setInitialCallSettings( UnaryCallSettings .<ExportEntityTypesRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create( ExportEntityTypesResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create( ExportEntityTypesMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(45000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(300000L)) .build())); builder .importEntityTypesOperationSettings() .setInitialCallSettings( UnaryCallSettings .<ImportEntityTypesRequest, OperationSnapshot>newUnaryCallSettingsBuilder() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")) .build()) .setResponseTransformer( ProtoOperationTransformers.ResponseTransformer.create( ImportEntityTypesResponse.class)) .setMetadataTransformer( ProtoOperationTransformers.MetadataTransformer.create( ImportEntityTypesMetadata.class)) .setPollingAlgorithm( OperationTimedPollAlgorithm.create( RetrySettings.newBuilder() .setInitialRetryDelayDuration(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.5) .setMaxRetryDelayDuration(Duration.ofMillis(45000L)) .setInitialRpcTimeoutDuration(Duration.ZERO) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeoutDuration(Duration.ZERO) .setTotalTimeoutDuration(Duration.ofMillis(300000L)) .build())); return builder; } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to getEntityType. */ public UnaryCallSettings.Builder<GetEntityTypeRequest, EntityType> getEntityTypeSettings() { return getEntityTypeSettings; } /** Returns the builder for the settings used for calls to createEntityType. */ public UnaryCallSettings.Builder<CreateEntityTypeRequest, EntityType> createEntityTypeSettings() { return createEntityTypeSettings; } /** Returns the builder for the settings used for calls to updateEntityType. */ public UnaryCallSettings.Builder<UpdateEntityTypeRequest, EntityType> updateEntityTypeSettings() { return updateEntityTypeSettings; } /** Returns the builder for the settings used for calls to deleteEntityType. */ public UnaryCallSettings.Builder<DeleteEntityTypeRequest, Empty> deleteEntityTypeSettings() { return deleteEntityTypeSettings; } /** Returns the builder for the settings used for calls to listEntityTypes. */ public PagedCallSettings.Builder< ListEntityTypesRequest, ListEntityTypesResponse, ListEntityTypesPagedResponse> listEntityTypesSettings() { return listEntityTypesSettings; } /** Returns the builder for the settings used for calls to exportEntityTypes. */ public UnaryCallSettings.Builder<ExportEntityTypesRequest, Operation> exportEntityTypesSettings() { return exportEntityTypesSettings; } /** Returns the builder for the settings used for calls to exportEntityTypes. */ public OperationCallSettings.Builder< ExportEntityTypesRequest, ExportEntityTypesResponse, ExportEntityTypesMetadata> exportEntityTypesOperationSettings() { return exportEntityTypesOperationSettings; } /** Returns the builder for the settings used for calls to importEntityTypes. */ public UnaryCallSettings.Builder<ImportEntityTypesRequest, Operation> importEntityTypesSettings() { return importEntityTypesSettings; } /** Returns the builder for the settings used for calls to importEntityTypes. */ public OperationCallSettings.Builder< ImportEntityTypesRequest, ImportEntityTypesResponse, ImportEntityTypesMetadata> importEntityTypesOperationSettings() { return importEntityTypesOperationSettings; } /** Returns the builder for the settings used for calls to listLocations. */ public PagedCallSettings.Builder< ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse> listLocationsSettings() { return listLocationsSettings; } /** Returns the builder for the settings used for calls to getLocation. */ public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() { return getLocationSettings; } @Override public EntityTypesStubSettings build() throws IOException { return new EntityTypesStubSettings(this); } } }
google/conscrypt
37,607
testing/src/main/java/org/conscrypt/java/security/DefaultKeys.java
/* * Copyright (C) 2009 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.java.security; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import org.conscrypt.TestUtils; public class DefaultKeys { private static final byte[] RSA_private = new byte[] { (byte) 0x30, (byte) 0x82, (byte) 0x02, (byte) 0x75, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x0D, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x82, (byte) 0x02, (byte) 0x5F, (byte) 0x30, (byte) 0x82, (byte) 0x02, (byte) 0x5B, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0x99, (byte) 0xA5, (byte) 0x96, (byte) 0x72, (byte) 0xAE, (byte) 0xBB, (byte) 0x59, (byte) 0x36, (byte) 0xA8, (byte) 0x12, (byte) 0x17, (byte) 0x05, (byte) 0x4C, (byte) 0x63, (byte) 0x9E, (byte) 0xB8, (byte) 0x85, (byte) 0xD4, (byte) 0x2D, (byte) 0x71, (byte) 0xD7, (byte) 0x29, (byte) 0xB9, (byte) 0x05, (byte) 0x0F, (byte) 0xB4, (byte) 0x57, (byte) 0xFB, (byte) 0xD3, (byte) 0x95, (byte) 0x5C, (byte) 0x21, (byte) 0xEC, (byte) 0xB5, (byte) 0xEB, (byte) 0x67, (byte) 0xA2, (byte) 0x4F, (byte) 0xC1, (byte) 0x93, (byte) 0xEF, (byte) 0x96, (byte) 0x41, (byte) 0x05, (byte) 0x3D, (byte) 0xC5, (byte) 0x3E, (byte) 0x04, (byte) 0x4D, (byte) 0xC6, (byte) 0xCF, (byte) 0x32, (byte) 0x7C, (byte) 0x1F, (byte) 0x66, (byte) 0xA3, (byte) 0xC5, (byte) 0x27, (byte) 0x79, (byte) 0xEC, (byte) 0x2E, (byte) 0x67, (byte) 0xFA, (byte) 0x19, (byte) 0x5B, (byte) 0xE3, (byte) 0xB1, (byte) 0x69, (byte) 0xDA, (byte) 0x63, (byte) 0xBC, (byte) 0xDA, (byte) 0xD3, (byte) 0xBB, (byte) 0xAD, (byte) 0x8C, (byte) 0x38, (byte) 0x7B, (byte) 0x4A, (byte) 0x9C, (byte) 0xD4, (byte) 0x4D, (byte) 0xD2, (byte) 0x33, (byte) 0xB7, (byte) 0x4E, (byte) 0x04, (byte) 0xB6, (byte) 0xDF, (byte) 0x62, (byte) 0x55, (byte) 0x48, (byte) 0x5C, (byte) 0x94, (byte) 0x02, (byte) 0xF7, (byte) 0x84, (byte) 0xE6, (byte) 0x9B, (byte) 0x57, (byte) 0xFF, (byte) 0x17, (byte) 0x2A, (byte) 0xA1, (byte) 0x74, (byte) 0x8D, (byte) 0x07, (byte) 0xD8, (byte) 0xCE, (byte) 0xF7, (byte) 0x0B, (byte) 0x59, (byte) 0xFB, (byte) 0x13, (byte) 0x6E, (byte) 0xF1, (byte) 0xC3, (byte) 0xAB, (byte) 0x3E, (byte) 0x72, (byte) 0x1B, (byte) 0x62, (byte) 0x09, (byte) 0xE8, (byte) 0xD8, (byte) 0x41, (byte) 0x69, (byte) 0xE1, (byte) 0x02, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x81, (byte) 0x80, (byte) 0x57, (byte) 0xD6, (byte) 0x1C, (byte) 0x2E, (byte) 0x2F, (byte) 0xCA, (byte) 0x16, (byte) 0xF4, (byte) 0x72, (byte) 0x1C, (byte) 0xF5, (byte) 0x60, (byte) 0x28, (byte) 0x0D, (byte) 0x83, (byte) 0x7D, (byte) 0x85, (byte) 0xB4, (byte) 0x88, (byte) 0xCE, (byte) 0x5D, (byte) 0xED, (byte) 0x12, (byte) 0x42, (byte) 0xDC, (byte) 0x79, (byte) 0x83, (byte) 0x1B, (byte) 0x0A, (byte) 0x18, (byte) 0x86, (byte) 0xF5, (byte) 0x35, (byte) 0xF7, (byte) 0xC2, (byte) 0x3E, (byte) 0x1A, (byte) 0xC2, (byte) 0x71, (byte) 0xAD, (byte) 0xFA, (byte) 0xF7, (byte) 0xF0, (byte) 0xEF, (byte) 0xE8, (byte) 0x22, (byte) 0x4C, (byte) 0x93, (byte) 0xF5, (byte) 0x4A, (byte) 0xC4, (byte) 0xC4, (byte) 0xDD, (byte) 0xC4, (byte) 0xAD, (byte) 0xCE, (byte) 0xCE, (byte) 0x35, (byte) 0x05, (byte) 0x34, (byte) 0x8A, (byte) 0x4B, (byte) 0x12, (byte) 0xE4, (byte) 0x69, (byte) 0xE6, (byte) 0xDA, (byte) 0x07, (byte) 0x1A, (byte) 0x77, (byte) 0x5C, (byte) 0xA7, (byte) 0x21, (byte) 0x41, (byte) 0x89, (byte) 0x8C, (byte) 0x95, (byte) 0x6A, (byte) 0x5D, (byte) 0x9C, (byte) 0x3C, (byte) 0xAE, (byte) 0xC3, (byte) 0xE4, (byte) 0x64, (byte) 0x54, (byte) 0xDA, (byte) 0xFB, (byte) 0xBA, (byte) 0xA6, (byte) 0xE5, (byte) 0x8A, (byte) 0x7F, (byte) 0xFA, (byte) 0x1A, (byte) 0x3F, (byte) 0x9B, (byte) 0xAB, (byte) 0xDA, (byte) 0x3D, (byte) 0x3B, (byte) 0x43, (byte) 0xF0, (byte) 0x0C, (byte) 0x06, (byte) 0x57, (byte) 0x43, (byte) 0x45, (byte) 0xEE, (byte) 0x8C, (byte) 0x27, (byte) 0x05, (byte) 0xAF, (byte) 0xCD, (byte) 0x5A, (byte) 0x47, (byte) 0xB9, (byte) 0xEA, (byte) 0xD9, (byte) 0xAA, (byte) 0x66, (byte) 0xDB, (byte) 0xE3, (byte) 0xDC, (byte) 0x54, (byte) 0x47, (byte) 0x60, (byte) 0x01, (byte) 0x02, (byte) 0x41, (byte) 0x00, (byte) 0xED, (byte) 0xE9, (byte) 0xBD, (byte) 0xD5, (byte) 0x02, (byte) 0x6D, (byte) 0x44, (byte) 0x0E, (byte) 0x3F, (byte) 0x74, (byte) 0x0C, (byte) 0x45, (byte) 0x54, (byte) 0x88, (byte) 0xFE, (byte) 0x5C, (byte) 0xFC, (byte) 0xF2, (byte) 0x31, (byte) 0x7B, (byte) 0xAF, (byte) 0x15, (byte) 0x77, (byte) 0x7A, (byte) 0xDC, (byte) 0xC6, (byte) 0x9E, (byte) 0x7E, (byte) 0xC1, (byte) 0xCA, (byte) 0x84, (byte) 0xC7, (byte) 0x4B, (byte) 0xC4, (byte) 0x41, (byte) 0xE1, (byte) 0x85, (byte) 0xE4, (byte) 0x5A, (byte) 0xA7, (byte) 0x3D, (byte) 0x54, (byte) 0x87, (byte) 0x0D, (byte) 0x7A, (byte) 0xC5, (byte) 0x47, (byte) 0x5C, (byte) 0xF2, (byte) 0xAD, (byte) 0x14, (byte) 0x4D, (byte) 0x63, (byte) 0xB0, (byte) 0xDC, (byte) 0x34, (byte) 0xB5, (byte) 0xDA, (byte) 0x17, (byte) 0x0D, (byte) 0x4E, (byte) 0x2B, (byte) 0x9E, (byte) 0x81, (byte) 0x02, (byte) 0x41, (byte) 0x00, (byte) 0xA5, (byte) 0x53, (byte) 0xDB, (byte) 0xD8, (byte) 0x28, (byte) 0x57, (byte) 0x65, (byte) 0x2B, (byte) 0xFA, (byte) 0xF2, (byte) 0x21, (byte) 0xB8, (byte) 0x60, (byte) 0xAE, (byte) 0x43, (byte) 0x4B, (byte) 0x51, (byte) 0x85, (byte) 0xCB, (byte) 0xDA, (byte) 0x89, (byte) 0x5A, (byte) 0x7D, (byte) 0x05, (byte) 0xDA, (byte) 0xFC, (byte) 0xAF, (byte) 0x46, (byte) 0x86, (byte) 0xBC, (byte) 0x3F, (byte) 0xD1, (byte) 0xEA, (byte) 0xA4, (byte) 0x56, (byte) 0xA3, (byte) 0xE6, (byte) 0xD4, (byte) 0xA2, (byte) 0x08, (byte) 0x93, (byte) 0x63, (byte) 0x21, (byte) 0x0E, (byte) 0xC5, (byte) 0x3C, (byte) 0x97, (byte) 0x7E, (byte) 0x71, (byte) 0x0B, (byte) 0x79, (byte) 0xF8, (byte) 0x60, (byte) 0x73, (byte) 0xD1, (byte) 0xF9, (byte) 0xD4, (byte) 0x66, (byte) 0x29, (byte) 0x7D, (byte) 0xDC, (byte) 0x22, (byte) 0xDB, (byte) 0x61, (byte) 0x02, (byte) 0x40, (byte) 0x5D, (byte) 0x3D, (byte) 0xEF, (byte) 0x85, (byte) 0x4D, (byte) 0x27, (byte) 0x2F, (byte) 0xB5, (byte) 0xF9, (byte) 0xCE, (byte) 0x6C, (byte) 0x84, (byte) 0xBB, (byte) 0x85, (byte) 0xD9, (byte) 0x52, (byte) 0xEE, (byte) 0x5B, (byte) 0xA9, (byte) 0x63, (byte) 0x15, (byte) 0x12, (byte) 0x6F, (byte) 0xBA, (byte) 0x3A, (byte) 0x4E, (byte) 0xA9, (byte) 0x8D, (byte) 0x7A, (byte) 0x3B, (byte) 0xF9, (byte) 0xDF, (byte) 0xF5, (byte) 0xE4, (byte) 0xDC, (byte) 0x01, (byte) 0x1C, (byte) 0x2D, (byte) 0x8C, (byte) 0x0D, (byte) 0xE1, (byte) 0x6E, (byte) 0x80, (byte) 0x63, (byte) 0x9B, (byte) 0x0B, (byte) 0x38, (byte) 0x55, (byte) 0xC8, (byte) 0x52, (byte) 0x67, (byte) 0x13, (byte) 0x91, (byte) 0x8F, (byte) 0x9E, (byte) 0x2E, (byte) 0x16, (byte) 0x5B, (byte) 0x7C, (byte) 0x0F, (byte) 0x5D, (byte) 0xE4, (byte) 0xA0, (byte) 0x81, (byte) 0x02, (byte) 0x40, (byte) 0x20, (byte) 0x12, (byte) 0x11, (byte) 0x5E, (byte) 0x70, (byte) 0x0C, (byte) 0xEC, (byte) 0x02, (byte) 0x49, (byte) 0x0E, (byte) 0xB9, (byte) 0x3D, (byte) 0xD3, (byte) 0xFB, (byte) 0x59, (byte) 0xF0, (byte) 0x7D, (byte) 0x62, (byte) 0xEF, (byte) 0xF5, (byte) 0x77, (byte) 0x99, (byte) 0x87, (byte) 0x11, (byte) 0x20, (byte) 0xB6, (byte) 0xCD, (byte) 0xA5, (byte) 0x67, (byte) 0xB3, (byte) 0x92, (byte) 0xC9, (byte) 0xBC, (byte) 0xB3, (byte) 0x9E, (byte) 0x5E, (byte) 0xF3, (byte) 0x03, (byte) 0x22, (byte) 0x5F, (byte) 0x79, (byte) 0x7F, (byte) 0xCC, (byte) 0x44, (byte) 0xDA, (byte) 0x3B, (byte) 0xF3, (byte) 0xC3, (byte) 0x42, (byte) 0x58, (byte) 0x90, (byte) 0x93, (byte) 0x7E, (byte) 0xDA, (byte) 0x58, (byte) 0xCC, (byte) 0x16, (byte) 0xC8, (byte) 0xAE, (byte) 0x99, (byte) 0xCC, (byte) 0x9F, (byte) 0x32, (byte) 0x61, (byte) 0x02, (byte) 0x40, (byte) 0x02, (byte) 0x29, (byte) 0xDB, (byte) 0x00, (byte) 0x0F, (byte) 0x0A, (byte) 0x17, (byte) 0x33, (byte) 0x7E, (byte) 0xC5, (byte) 0xEC, (byte) 0x21, (byte) 0x47, (byte) 0x65, (byte) 0xDC, (byte) 0xE5, (byte) 0xC2, (byte) 0x0D, (byte) 0x42, (byte) 0x28, (byte) 0xE1, (byte) 0x17, (byte) 0x1A, (byte) 0x00, (byte) 0xBD, (byte) 0xBE, (byte) 0x1C, (byte) 0x7D, (byte) 0xCA, (byte) 0x93, (byte) 0x67, (byte) 0x8F, (byte) 0x28, (byte) 0xB7, (byte) 0x60, (byte) 0x8E, (byte) 0xF0, (byte) 0x5D, (byte) 0xCD, (byte) 0xFA, (byte) 0xDD, (byte) 0x6B, (byte) 0x72, (byte) 0xF7, (byte) 0x48, (byte) 0xD9, (byte) 0x3C, (byte) 0x40, (byte) 0x7C, (byte) 0xB0, (byte) 0xD7, (byte) 0x58, (byte) 0xC2, (byte) 0x53, (byte) 0xAD, (byte) 0x04, (byte) 0xF6, (byte) 0x0B, (byte) 0x35, (byte) 0x51, (byte) 0x45, (byte) 0xB9, (byte) 0x4F, (byte) 0x49 }; private static final byte[] RSA_public = new byte[] { (byte) 0x30, (byte) 0x81, (byte) 0x9F, (byte) 0x30, (byte) 0x0D, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x03, (byte) 0x81, (byte) 0x8D, (byte) 0x00, (byte) 0x30, (byte) 0x81, (byte) 0x89, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0x99, (byte) 0xA5, (byte) 0x96, (byte) 0x72, (byte) 0xAE, (byte) 0xBB, (byte) 0x59, (byte) 0x36, (byte) 0xA8, (byte) 0x12, (byte) 0x17, (byte) 0x05, (byte) 0x4C, (byte) 0x63, (byte) 0x9E, (byte) 0xB8, (byte) 0x85, (byte) 0xD4, (byte) 0x2D, (byte) 0x71, (byte) 0xD7, (byte) 0x29, (byte) 0xB9, (byte) 0x05, (byte) 0x0F, (byte) 0xB4, (byte) 0x57, (byte) 0xFB, (byte) 0xD3, (byte) 0x95, (byte) 0x5C, (byte) 0x21, (byte) 0xEC, (byte) 0xB5, (byte) 0xEB, (byte) 0x67, (byte) 0xA2, (byte) 0x4F, (byte) 0xC1, (byte) 0x93, (byte) 0xEF, (byte) 0x96, (byte) 0x41, (byte) 0x05, (byte) 0x3D, (byte) 0xC5, (byte) 0x3E, (byte) 0x04, (byte) 0x4D, (byte) 0xC6, (byte) 0xCF, (byte) 0x32, (byte) 0x7C, (byte) 0x1F, (byte) 0x66, (byte) 0xA3, (byte) 0xC5, (byte) 0x27, (byte) 0x79, (byte) 0xEC, (byte) 0x2E, (byte) 0x67, (byte) 0xFA, (byte) 0x19, (byte) 0x5B, (byte) 0xE3, (byte) 0xB1, (byte) 0x69, (byte) 0xDA, (byte) 0x63, (byte) 0xBC, (byte) 0xDA, (byte) 0xD3, (byte) 0xBB, (byte) 0xAD, (byte) 0x8C, (byte) 0x38, (byte) 0x7B, (byte) 0x4A, (byte) 0x9C, (byte) 0xD4, (byte) 0x4D, (byte) 0xD2, (byte) 0x33, (byte) 0xB7, (byte) 0x4E, (byte) 0x04, (byte) 0xB6, (byte) 0xDF, (byte) 0x62, (byte) 0x55, (byte) 0x48, (byte) 0x5C, (byte) 0x94, (byte) 0x02, (byte) 0xF7, (byte) 0x84, (byte) 0xE6, (byte) 0x9B, (byte) 0x57, (byte) 0xFF, (byte) 0x17, (byte) 0x2A, (byte) 0xA1, (byte) 0x74, (byte) 0x8D, (byte) 0x07, (byte) 0xD8, (byte) 0xCE, (byte) 0xF7, (byte) 0x0B, (byte) 0x59, (byte) 0xFB, (byte) 0x13, (byte) 0x6E, (byte) 0xF1, (byte) 0xC3, (byte) 0xAB, (byte) 0x3E, (byte) 0x72, (byte) 0x1B, (byte) 0x62, (byte) 0x09, (byte) 0xE8, (byte) 0xD8, (byte) 0x41, (byte) 0x69, (byte) 0xE1, (byte) 0x02, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01 }; private static final byte[] DSA_private = new byte[] { (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x4B, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x2C, (byte) 0x06, (byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x38, (byte) 0x04, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1F, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, (byte) 0x12, (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, (byte) 0x00, (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, (byte) 0x8D, (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, (byte) 0x1D, (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, (byte) 0x10, (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, (byte) 0x91, (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, (byte) 0x48, (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0x97, (byte) 0x60, (byte) 0x50, (byte) 0x8F, (byte) 0x15, (byte) 0x23, (byte) 0x0B, (byte) 0xCC, (byte) 0xB2, (byte) 0x92, (byte) 0xB9, (byte) 0x82, (byte) 0xA2, (byte) 0xEB, (byte) 0x84, (byte) 0x0B, (byte) 0xF0, (byte) 0x58, (byte) 0x1C, (byte) 0xF5, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, (byte) 0x2A, (byte) 0x04, (byte) 0x16, (byte) 0x02, (byte) 0x14, (byte) 0x0E, (byte) 0x90, (byte) 0xB7, (byte) 0x92, (byte) 0x01, (byte) 0x98, (byte) 0xCD, (byte) 0x85, (byte) 0x87, (byte) 0x77, (byte) 0x2F, (byte) 0xB4, (byte) 0x31, (byte) 0xFD, (byte) 0xDE, (byte) 0xFA, (byte) 0x08, (byte) 0x6D, (byte) 0x0C, (byte) 0xE3 }; private static final byte[] DSA_public = new byte[] { (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0xB8, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x2C, (byte) 0x06, (byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x38, (byte) 0x04, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1F, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, (byte) 0x12, (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, (byte) 0x00, (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, (byte) 0x8D, (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, (byte) 0x1D, (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, (byte) 0x10, (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, (byte) 0x91, (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, (byte) 0x48, (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0x97, (byte) 0x60, (byte) 0x50, (byte) 0x8F, (byte) 0x15, (byte) 0x23, (byte) 0x0B, (byte) 0xCC, (byte) 0xB2, (byte) 0x92, (byte) 0xB9, (byte) 0x82, (byte) 0xA2, (byte) 0xEB, (byte) 0x84, (byte) 0x0B, (byte) 0xF0, (byte) 0x58, (byte) 0x1C, (byte) 0xF5, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, (byte) 0x2A, (byte) 0x03, (byte) 0x81, (byte) 0x85, (byte) 0x00, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0x98, (byte) 0x33, (byte) 0x90, (byte) 0x14, (byte) 0x79, (byte) 0xC7, (byte) 0xC8, (byte) 0x57, (byte) 0xE1, (byte) 0x82, (byte) 0x53, (byte) 0x5B, (byte) 0x6E, (byte) 0x01, (byte) 0x07, (byte) 0x1E, (byte) 0xA5, (byte) 0x98, (byte) 0xC4, (byte) 0x57, (byte) 0x5D, (byte) 0x23, (byte) 0xAB, (byte) 0x72, (byte) 0x9A, (byte) 0xB3, (byte) 0x2F, (byte) 0x39, (byte) 0xCB, (byte) 0xC5, (byte) 0xD0, (byte) 0x97, (byte) 0xD5, (byte) 0x62, (byte) 0x8C, (byte) 0xD9, (byte) 0xE6, (byte) 0xE2, (byte) 0x05, (byte) 0xC6, (byte) 0x05, (byte) 0x71, (byte) 0x16, (byte) 0xE3, (byte) 0xE8, (byte) 0x04, (byte) 0xE8, (byte) 0x46, (byte) 0x12, (byte) 0x0C, (byte) 0xF8, (byte) 0xFC, (byte) 0x8E, (byte) 0x15, (byte) 0x26, (byte) 0x32, (byte) 0xF7, (byte) 0x8C, (byte) 0x04, (byte) 0x3B, (byte) 0x53, (byte) 0x68, (byte) 0x9A, (byte) 0xA3, (byte) 0xB7, (byte) 0x4D, (byte) 0x13, (byte) 0x40, (byte) 0x0F, (byte) 0xBE, (byte) 0x03, (byte) 0x87, (byte) 0xD8, (byte) 0xF1, (byte) 0xFE, (byte) 0x4B, (byte) 0xF5, (byte) 0x44, (byte) 0x19, (byte) 0x29, (byte) 0xBB, (byte) 0x0D, (byte) 0x0C, (byte) 0x52, (byte) 0xC6, (byte) 0x84, (byte) 0x33, (byte) 0x62, (byte) 0x73, (byte) 0x5D, (byte) 0x03, (byte) 0xFF, (byte) 0x6F, (byte) 0x0A, (byte) 0x5A, (byte) 0xF3, (byte) 0x9E, (byte) 0x52, (byte) 0xF2, (byte) 0xC2, (byte) 0xC8, (byte) 0x00, (byte) 0x52, (byte) 0xC7, (byte) 0x75, (byte) 0xA4, (byte) 0xFD, (byte) 0x71, (byte) 0x2D, (byte) 0x7B, (byte) 0x7A, (byte) 0x31, (byte) 0x27, (byte) 0x6E, (byte) 0xAC, (byte) 0xB6, (byte) 0x40, (byte) 0x14, (byte) 0x4E, (byte) 0xB4, (byte) 0xBB, (byte) 0xB1, (byte) 0x51, (byte) 0x63, (byte) 0x29, (byte) 0x81, (byte) 0x06, (byte) 0xF9 }; private static final byte[] DH_private = new byte[] { (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0xA8, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1B, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, (byte) 0x01, (byte) 0x03, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x0C, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, (byte) 0x12, (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, (byte) 0x00, (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, (byte) 0x8D, (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, (byte) 0x1D, (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, (byte) 0x10, (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, (byte) 0x91, (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, (byte) 0x48, (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, (byte) 0x2A, (byte) 0x02, (byte) 0x02, (byte) 0x03, (byte) 0xFE, (byte) 0x04, (byte) 0x81, (byte) 0x83, (byte) 0x02, (byte) 0x81, (byte) 0x80, (byte) 0x35, (byte) 0xFE, (byte) 0x44, (byte) 0x0A, (byte) 0xA3, (byte) 0xA0, (byte) 0xCB, (byte) 0x52, (byte) 0xC2, (byte) 0x32, (byte) 0xCA, (byte) 0x38, (byte) 0x1F, (byte) 0x18, (byte) 0xEB, (byte) 0x27, (byte) 0x6E, (byte) 0x77, (byte) 0x25, (byte) 0x40, (byte) 0x1F, (byte) 0x64, (byte) 0x5D, (byte) 0x4B, (byte) 0x59, (byte) 0x41, (byte) 0xB6, (byte) 0xCB, (byte) 0xDF, (byte) 0x73, (byte) 0xE0, (byte) 0x01, (byte) 0x5A, (byte) 0x79, (byte) 0x0D, (byte) 0x8D, (byte) 0x08, (byte) 0xE6, (byte) 0x7F, (byte) 0x86, (byte) 0x58, (byte) 0xCF, (byte) 0x7F, (byte) 0x4B, (byte) 0x2E, (byte) 0xDB, (byte) 0x4C, (byte) 0xDF, (byte) 0x75, (byte) 0xB5, (byte) 0x16, (byte) 0xC4, (byte) 0xA9, (byte) 0x49, (byte) 0xEE, (byte) 0x00, (byte) 0x56, (byte) 0xA0, (byte) 0x60, (byte) 0x08, (byte) 0x8E, (byte) 0x0D, (byte) 0xC7, (byte) 0xC9, (byte) 0x45, (byte) 0x0C, (byte) 0x5D, (byte) 0xB7, (byte) 0x4C, (byte) 0xC4, (byte) 0x7E, (byte) 0xAB, (byte) 0x1F, (byte) 0xEA, (byte) 0xCF, (byte) 0x08, (byte) 0x6D, (byte) 0x05, (byte) 0xA1, (byte) 0x7F, (byte) 0x63, (byte) 0x6F, (byte) 0xB3, (byte) 0x91, (byte) 0xA3, (byte) 0xE1, (byte) 0xB0, (byte) 0x36, (byte) 0x02, (byte) 0x3F, (byte) 0x55, (byte) 0x71, (byte) 0x38, (byte) 0x37, (byte) 0x9A, (byte) 0x19, (byte) 0xA3, (byte) 0xAF, (byte) 0xC8, (byte) 0xD5, (byte) 0x22, (byte) 0xDD, (byte) 0x00, (byte) 0x81, (byte) 0x19, (byte) 0xB6, (byte) 0x3C, (byte) 0x5F, (byte) 0xD9, (byte) 0xDF, (byte) 0xFD, (byte) 0x58, (byte) 0xB1, (byte) 0xE6, (byte) 0xD1, (byte) 0xD2, (byte) 0x58, (byte) 0xEF, (byte) 0x44, (byte) 0x6E, (byte) 0x66, (byte) 0x92, (byte) 0x1E, (byte) 0x30, (byte) 0x0B, (byte) 0x90, (byte) 0x8E, (byte) 0x29 }; private static final byte[] DH_public = new byte[] { (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0xA7, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1B, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, (byte) 0x01, (byte) 0x03, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x0C, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, (byte) 0x12, (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, (byte) 0x00, (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, (byte) 0x8D, (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, (byte) 0x1D, (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, (byte) 0x10, (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, (byte) 0x91, (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, (byte) 0x48, (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, (byte) 0x2A, (byte) 0x02, (byte) 0x02, (byte) 0x03, (byte) 0xFE, (byte) 0x03, (byte) 0x81, (byte) 0x85, (byte) 0x00, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xD4, (byte) 0xC2, (byte) 0xC2, (byte) 0x84, (byte) 0xEB, (byte) 0xEC, (byte) 0xB6, (byte) 0xF1, (byte) 0x29, (byte) 0x2B, (byte) 0xAB, (byte) 0x8F, (byte) 0xC1, (byte) 0x48, (byte) 0x4C, (byte) 0x47, (byte) 0xCE, (byte) 0x0B, (byte) 0x97, (byte) 0x4C, (byte) 0xFC, (byte) 0x27, (byte) 0x10, (byte) 0x0A, (byte) 0x5F, (byte) 0x3E, (byte) 0xE6, (byte) 0xF9, (byte) 0x9B, (byte) 0x15, (byte) 0xDF, (byte) 0x83, (byte) 0x01, (byte) 0xFA, (byte) 0x69, (byte) 0x57, (byte) 0xEC, (byte) 0x6B, (byte) 0x68, (byte) 0xC7, (byte) 0x96, (byte) 0x33, (byte) 0x98, (byte) 0xA4, (byte) 0xB0, (byte) 0xA3, (byte) 0x18, (byte) 0x01, (byte) 0x66, (byte) 0x7A, (byte) 0x4A, (byte) 0xF3, (byte) 0x3C, (byte) 0xD9, (byte) 0x2A, (byte) 0x48, (byte) 0xFD, (byte) 0x3A, (byte) 0x31, (byte) 0xFC, (byte) 0x97, (byte) 0x52, (byte) 0x36, (byte) 0x20, (byte) 0x0E, (byte) 0x69, (byte) 0xB6, (byte) 0x32, (byte) 0x8B, (byte) 0x4E, (byte) 0xDA, (byte) 0x8B, (byte) 0x04, (byte) 0x88, (byte) 0xF8, (byte) 0x30, (byte) 0xA9, (byte) 0x65, (byte) 0x68, (byte) 0x47, (byte) 0xBB, (byte) 0xA1, (byte) 0xF6, (byte) 0xD6, (byte) 0x18, (byte) 0x11, (byte) 0x48, (byte) 0x8D, (byte) 0x8F, (byte) 0x4B, (byte) 0xC1, (byte) 0xE1, (byte) 0xA4, (byte) 0x43, (byte) 0x83, (byte) 0x1F, (byte) 0x6B, (byte) 0x6D, (byte) 0xEE, (byte) 0xA7, (byte) 0xA3, (byte) 0x5F, (byte) 0xD2, (byte) 0x95, (byte) 0x09, (byte) 0xD4, (byte) 0xEA, (byte) 0x85, (byte) 0x0C, (byte) 0xA5, (byte) 0xC9, (byte) 0x93, (byte) 0xCE, (byte) 0xC1, (byte) 0x1D, (byte) 0x30, (byte) 0x73, (byte) 0xA3, (byte) 0xE1, (byte) 0x69, (byte) 0xA8, (byte) 0x11, (byte) 0x98, (byte) 0x78, (byte) 0xF3, (byte) 0xF9, (byte) 0x8F, (byte) 0x04 }; private static final byte[] EC_private = TestUtils.decodeBase64( "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgXbi5zGvh/MoXidykzJKs1yEbrN99" + "/A3bQy1bMNQR/c2hRANCAAQqgfCMR3JAG/JhR386L6bTmo7XTd1B0oHCPaqPP5+YLzL5wY" + "AbDExaCdzXEljDvrupjn1HfqjZNCVAc0j13QIM"); private static final byte[] EC_public = TestUtils.decodeBase64( "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKoHwjEdyQBvyYUd/Oi+m05qO103dQdKBwj2qjz+f" + "mC8y+cGAGwxMWgnc1xJYw767qY59R36o2TQlQHNI9d0CDA=="); private static final byte[] X25519_private = new byte[] { (byte) 0x30, (byte) 0x2e, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x05, (byte) 0x06, (byte) 0x03, (byte) 0x2b, (byte) 0x65, (byte) 0x6e, (byte) 0x04, (byte) 0x22, (byte) 0x04, (byte) 0x20, (byte) 0xa5, (byte) 0x46, (byte) 0xe3, (byte) 0x6b, (byte) 0xf0, (byte) 0x52, (byte) 0x7c, (byte) 0x9d, (byte) 0x3b, (byte) 0x16, (byte) 0x15, (byte) 0x4b, (byte) 0x82, (byte) 0x46, (byte) 0x5e, (byte) 0xdd, (byte) 0x62, (byte) 0x14, (byte) 0x4c, (byte) 0x0a, (byte) 0xc1, (byte) 0xfc, (byte) 0x5a, (byte) 0x18, (byte) 0x50, (byte) 0x6a, (byte) 0x22, (byte) 0x44, (byte) 0xba, (byte) 0x44, (byte) 0x9a, (byte) 0xc4, }; private static final byte[] X25519_public = new byte[] { (byte) 0x30, (byte) 0x2a, (byte) 0x30, (byte) 0x05, (byte) 0x06, (byte) 0x03, (byte) 0x2b, (byte) 0x65, (byte) 0x6e, (byte) 0x03, (byte) 0x21, (byte) 0x00, (byte) 0xe6, (byte) 0xdb, (byte) 0x68, (byte) 0x67, (byte) 0x58, (byte) 0x30, (byte) 0x30, (byte) 0xdb, (byte) 0x35, (byte) 0x94, (byte) 0xc1, (byte) 0xa4, (byte) 0x24, (byte) 0xb1, (byte) 0x5f, (byte) 0x7c, (byte) 0x72, (byte) 0x66, (byte) 0x24, (byte) 0xec, (byte) 0x26, (byte) 0xb3, (byte) 0x35, (byte) 0x3b, (byte) 0x10, (byte) 0xa9, (byte) 0x03, (byte) 0xa6, (byte) 0xd0, (byte) 0xab, (byte) 0x1c, (byte) 0x4c, }; private static final HashMap<String, KeySpec> keys = new HashMap<String, KeySpec>(); static { keys.put("DH_public", new X509EncodedKeySpec(DH_public)); keys.put("DH_private", new PKCS8EncodedKeySpec(DH_private)); keys.put("DSA_public", new X509EncodedKeySpec(DSA_public)); keys.put("DSA_private", new PKCS8EncodedKeySpec(DSA_private)); keys.put("RSA_public", new X509EncodedKeySpec(RSA_public)); keys.put("RSA_private", new PKCS8EncodedKeySpec(RSA_private)); keys.put("EC_public", new X509EncodedKeySpec(EC_public)); keys.put("EC_private", new PKCS8EncodedKeySpec(EC_private)); keys.put("XDH_public", new X509EncodedKeySpec(X25519_public)); keys.put("XDH_private", new PKCS8EncodedKeySpec(X25519_private)); } public static PrivateKey getPrivateKey(String algorithmName) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory factory = KeyFactory.getInstance(algorithmName); return factory.generatePrivate(keys.get(algorithmName + "_private")); } public static PublicKey getPublicKey(String algorithmName) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory factory = KeyFactory.getInstance(algorithmName); return factory.generatePublic(keys.get(algorithmName + "_public")); } }
google/j2cl
36,154
transpiler/javatests/com/google/j2cl/ported/java6/CompilerTest.java
/* * Copyright 2017 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 * * 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.j2cl.ported.java6; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.EventListener; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Miscellaneous tests of the Java to JavaScript compiler. */ @RunWith(JUnit4.class) @SuppressWarnings({ "unused", "BoxedPrimitiveConstructor", "ShortCircuitBoolean", "IdentityBinaryExpression", "LoopConditionChecker", "StaticQualifiedUsingExpression", "ClassCanBeStatic", "MethodCanBeStatic", "ConstantField", "MissingDefault", "MultipleTopLevelClasses", "unchecked", "rawtypes" }) public class CompilerTest { interface MyMap { Object get(String key); } interface Silly {} interface SillyComparable<T extends Silly> extends Comparable<T> { @Override int compareTo(T obj); } private abstract static class AbstractSuper { public static String foo() { if (FALSE) { // prevent inlining return foo(); } return "AbstractSuper"; } } private abstract static class Apple implements Fruit {} private abstract static class Bm2BaseEvent {} private abstract static class Bm2ComponentEvent extends Bm2BaseEvent {} private static class Bm2KeyNav<E extends Bm2ComponentEvent> implements Bm2Listener<E> { @Override public int handleEvent(Bm2ComponentEvent ce) { return 5; } } private interface Bm2Listener<E extends Bm2BaseEvent> extends EventListener { int handleEvent(E be); } /** Used in {@link #testSwitchOnEnumTypedThis()}. */ private static enum ChangeDirection { NEGATIVE, POSITIVE; public String getText() { switch (this) { case POSITIVE: return "POSITIVE"; case NEGATIVE: return "NEGATIVE"; default: throw new IllegalArgumentException("Unhandled change direction: " + this); } } } private static class ConcreteSub extends AbstractSuper { public static String foo() { if (FALSE) { // prevent inlining return foo(); } return "ConcreteSub"; } } private static interface Fruit {} private static class Fuji extends Apple {} private static class Granny extends Apple {} private static class NonSideEffectCauser { public static final String NOT_A_COMPILE_TIME_CONSTANT = null; } private static class SideEffectCauser { private static Object instance = new Object(); static { CompilerTest.sideEffectChecker++; } public static Object causeClinitSideEffect() { return instance; } } private static class SideEffectCauser2 { static { CompilerTest.sideEffectChecker++; } public static Object causeClinitSideEffect() { return null; } } private static class SideEffectCauser3 { static { CompilerTest.sideEffectChecker++; } public static void causeClinitSideEffect() {} } private static class SideEffectCauser4 { public static String causeClinitSideEffectOnRead = "foo"; static { CompilerTest.sideEffectChecker++; } } private static class SideEffectCauser5 { public static String causeClinitSideEffectOnRead = "bar"; static { CompilerTest.sideEffectChecker++; } } private static class SideEffectCauser6 extends SideEffectCauser6Super { public static String causeClinitSideEffectOnRead = "bar"; } private static class SideEffectCauser6Super { static { CompilerTest.sideEffectChecker++; } } /** Ensures that a superclass's clinit is run before supercall arguments are evaluated. */ private static class SideEffectCauser7 extends SideEffectCauser7Super { public SideEffectCauser7() { super(SideEffectCauser7Super.SHOULD_BE_TRUE); } } private static class SideEffectCauser7Super { public static boolean SHOULD_BE_TRUE = false; static { SHOULD_BE_TRUE = true; } public SideEffectCauser7Super(boolean shouldBeTrue) { if (shouldBeTrue) { CompilerTest.sideEffectChecker++; } } } /** Used in test {@link #testPrivateOverride()}. */ private static class TpoChild extends TpoParent { @Override public int foo() { return callSuper(); } private int callSuper() { return super.foo(); } } /** Used in test {@link #testPrivateOverride()}. */ private static class TpoGrandparent { public int foo() { return 0; } } /** Used in test {@link #testPrivateOverride()}. */ private static class TpoParent extends TpoGrandparent { @Override public int foo() { // This should call the callSuper in TpoJsniParent, not the one // in TpoJsniChild return callSuper(); } private int callSuper() { return super.foo(); } } private static final class UninstantiableType { public Object field; public int intField; private UninstantiableType() {} public int returnInt() { return intField; } public Object returnNull() { return null; } } private static volatile boolean FALSE = false; private static int sideEffectChecker; private static volatile int THREE = 3; private static volatile boolean TRUE = true; private static volatile boolean volatileBoolean; private static volatile int volatileInt; private static volatile long volatileLong; private static String barShouldInline() { return "bar"; } private static void foo(String string) {} private static void foo(Throwable throwable) {} private Integer boxedInteger = 0; @Test public void testArrayAccessSideEffect() { int index = 1; int[] array = null; try { // index should be set before exception is thrown array[index = 2]++; fail("null reference expected"); } catch (Exception e) { // expected } assertEquals(2, index); } @Test public void testArrayStore() { Object[][] oaa; oaa = new Object[4][4]; oaa[0][0] = "foo"; assertEquals(oaa[0][0], "foo"); oaa = new Object[4][]; oaa[0] = new Object[4]; oaa[0][0] = "bar"; assertEquals(oaa[0][0], "bar"); Apple[] apple = TRUE ? new Granny[3] : new Apple[3]; Apple g = TRUE ? (Apple) new Granny() : (Apple) new Fuji(); Apple a = apple[0] = g; assertEquals(g, a); byte[] bytes = new byte[10]; bytes[0] = (byte) '1'; assertEquals(49, bytes[0]); Object[] disguisedApple = apple; expectArrayStoreException(disguisedApple, "Hello"); expectArrayStoreException(disguisedApple, true); expectArrayStoreException(disguisedApple, 42.0); } private void expectArrayStoreException(Object[] array, Object o) { try { array[0] = o; fail("Expected ArrayStoreException"); } catch (ArrayStoreException expected) { } } @Test public void testUnboxedArrays() { Double[] doubleArray = new Double[1]; doubleArray[0] = 42.0; expectArrayStoreException(doubleArray, true); expectArrayStoreException(doubleArray, "Hello"); expectArrayStoreException(doubleArray, new Integer(23)); Boolean[] booleanArray = new Boolean[1]; booleanArray[0] = true; expectArrayStoreException(booleanArray, 42.0); expectArrayStoreException(booleanArray, "Hello"); expectArrayStoreException(booleanArray, new Integer(23)); String[] stringArray = new String[1]; stringArray[0] = "Hello"; expectArrayStoreException(stringArray, 42.0); expectArrayStoreException(stringArray, true); expectArrayStoreException(stringArray, new Integer(23)); } /** * Issue 3064: when the implementation of an interface comes from a superclass, it can be * necessary to add a bridge method that overrides the interface method and calls the inherited * method. */ @Test public void testBridgeMethods1() { abstract class AbstractFoo { public int compareTo(AbstractFoo o) { return 0; } } class MyFoo extends AbstractFoo implements Comparable<AbstractFoo> {} /* * This subclass adds an extra curve ball: only one bridge method should be * created, in class MyFoo. MyFooSub should not get its own but instead use * the inherited one. Otherwise, two final methods with identical signatures * would override each other. */ class MyFooSub extends MyFoo {} Comparable<AbstractFoo> comparable1 = new MyFooSub(); assertEquals(0, comparable1.compareTo(new MyFoo())); Comparable<AbstractFoo> comparable2 = new MyFoo(); assertEquals(0, comparable2.compareTo(new MyFooSub())); } /** Issue 3304. Doing superclasses first is tricky when the superclass is a raw type. */ @Test public void testBridgeMethods2() { Bm2KeyNav<?> obs = new Bm2KeyNav() {}; assertEquals(5, obs.handleEvent(null)); } /** When adding a bridge method, be sure to handle transitive overrides relationships. */ @Test public void testBridgeMethods3() { class AbstractFoo implements Silly { public int compareTo(AbstractFoo obj) { if (FALSE) { return compareTo(obj); } return 0; } } class MyFoo extends AbstractFoo implements SillyComparable<AbstractFoo> {} assertEquals(0, new MyFoo().compareTo(new MyFoo())); } /** * Issue 3517. Sometimes JDT adds a bridge method when a subclass's method differs only by return * type. In some versions of GWT, this has resulted in a bridge method overriding its own target, * and eventually TypeTightener producing an infinite recursion. */ @Test public void testBridgeMethods4() { abstract class MyMapAbstract<V> implements MyMap { @Override public String get(String key) { return null; } } final class MyMapImpl<V> extends MyMapAbstract<V> {} MyMapImpl<String> mmap = new MyMapImpl<String>(); assertNull(mmap.get("foo")); } @Test public void testCastOptimizer() { Granny g = new Granny(); Apple a = g; Fruit f = g; a = (Apple) f; g = (Granny) a; g = (Granny) f; } @Test public void testClassLiterals() { if (Object.class.getName().startsWith("Class$")) { // If class metadata is disabled return; } assertEquals("void", void.class.toString()); assertEquals("int", int.class.toString()); assertEquals("class java.lang.String", String.class.toString()); assertEquals("class com.google.j2cl.ported.java6.CompilerTest", CompilerTest.class.toString()); assertEquals( "class com.google.j2cl.ported.java6.CompilerTest$UninstantiableType", UninstantiableType.class.toString()); assertEquals( "interface com.google.j2cl.ported.java6.CompilerTest$Fruit", Fruit.class.toString()); assertEquals("class [I", int[].class.toString()); assertEquals("class [Ljava.lang.String;", String[].class.toString()); assertEquals( "class [Lcom.google.j2cl.ported.java6.CompilerTest;", CompilerTest[].class.toString()); assertEquals( "class [Lcom.google.j2cl.ported.java6.CompilerTest$UninstantiableType;", UninstantiableType[].class.toString()); assertEquals( "class [Lcom.google.j2cl.ported.java6.CompilerTest$Fruit;", Fruit[].class.toString()); } @Test public void testClinitSideEffectInlining() { sideEffectChecker = 0; SideEffectCauser.causeClinitSideEffect(); assertEquals(1, sideEffectChecker); SideEffectCauser2.causeClinitSideEffect(); assertEquals(2, sideEffectChecker); SideEffectCauser3.causeClinitSideEffect(); assertEquals(3, sideEffectChecker); String foo = SideEffectCauser4.causeClinitSideEffectOnRead; assertEquals(4, sideEffectChecker); foo = SideEffectCauser6.causeClinitSideEffectOnRead; assertEquals(5, sideEffectChecker); new SideEffectCauser7(); assertEquals(6, sideEffectChecker); String checkRescued = NonSideEffectCauser.NOT_A_COMPILE_TIME_CONSTANT; assertEquals(null, checkRescued); } private static boolean testClassInitialized = false; private static class TestClass { static { testClassInitialized = true; } public static int staticField = 32; } @Test public void testClinitOverInstance() { assertEquals(32, getTest().staticField); assertTrue(testClassInitialized); } private TestClass getTest() { assertFalse(testClassInitialized); return null; } @Test public void testConditionals() { assertTrue(TRUE ? TRUE : FALSE); assertFalse(FALSE ? TRUE : FALSE); assertFalse(TRUE ? FALSE : TRUE); assertTrue(FALSE ? FALSE : TRUE); assertTrue(true ? TRUE : FALSE); assertFalse(false ? TRUE : FALSE); assertFalse(true ? FALSE : TRUE); assertTrue(false ? FALSE : TRUE); assertTrue(TRUE ? true : FALSE); assertFalse(FALSE ? true : FALSE); assertFalse(TRUE ? false : TRUE); assertTrue(FALSE ? false : TRUE); assertTrue(TRUE ? TRUE : false); assertFalse(FALSE ? TRUE : false); assertFalse(TRUE ? FALSE : true); assertTrue(FALSE ? FALSE : true); } /** * Test for issue 7045. * * <p>Background. GWT does not explicitly model block scopes but allows names across different * blocks to be repeated and are represented as different local variables with the same name. * * <p>The GenerateJavaScriptAST assumes that locals with the same name can be coalesced. This * assumption only holds if no optimization introduces a local variable reference in a blockscope * that is using a different local of the same name. * * <p>The dataflow optimizer does not respect this assumption when doing copy propagation. */ @Test public void testDataflowDuplicateNamesError() { StringBuilder topScope; { StringBuilder localScopeDuplicatedVar = new StringBuilder(); localScopeDuplicatedVar.append("initial text"); topScope = localScopeDuplicatedVar; } { // It's important that this StringBuilder have the same name as the one above. StringBuilder localScopeDuplicatedVar = new StringBuilder(); localScopeDuplicatedVar.append("different text"); } { // The value of main should be "initial text" at this point, but if this code // is run as compiled JavaScript then it will be "different text". (before the issue was // fixed). // The copy propagation optimization in the DataflowOptimizer replaces the reference to // topScope by localScopeDuplicatedVar (from the previous block). // When the JavaScript output is produces these two variables are coalesced. // Although unlikely an error like this can occur due to the way temporary variables are // generated via the TempLocalVisitor. assertEquals("initial text", topScope.toString()); } } private int functionWithClashingParameters(int i0) { int c = 0; for (int i = 0; i < 5; i++) { c++; } for (int i = 0; i < 6; i++) { c++; } // Assumes that GenerateJavaScriptAST will rename one of the "i" variables to i0. return i0; } /** Test for issue 8870. */ @Test public void testParameterVariableClash() { assertEquals(1, functionWithClashingParameters(1)); } /** Test for issue 8877. */ @Test public void testOptimizeInstanceOf() { class A { int counter = 0; Object get() { if (counter >= 0) { counter++; } return "aString"; } } A anA = new A(); assertFalse(anA.get() instanceof Integer); assertEquals(1, anA.counter); } @Test public void testDeadCode() { while (returnFalse()) { break; } do { break; } while (false); do { break; } while (returnFalse()); for (; returnFalse(); ) {} boolean check = false; for (check = true; returnFalse(); fail()) { fail(); } assertTrue(check); if (returnFalse()) { fail(); } else { } if (!returnFalse()) { } else { fail(); } // For these following tests, make sure that side effects in conditions // get propagated, even if they cause introduction of dead code. // boolean b = false; if ((b = true) ? true : true) {} assertTrue(b); boolean c = true; int val = 0; for (val = 1; c = false; ++val) {} assertFalse(c); boolean d = true; while (d = false) {} assertFalse(d); boolean e = true; if (true | (e = false)) {} assertFalse(e); } /** Test that code considered unreachable by the JDT does not crash the GWT compiler. */ @Test public void testDeadCode2() { class SillyList {} final SillyList outerLocalVariable = new SillyList(); new SillyList() { private void pretendToUse(SillyList x) {} void blah() { if (true) { throw new RuntimeException(); } /* * This code is unreachable, and so outerLocalVariable is never actually * read by reachable code. */ pretendToUse(outerLocalVariable); } }; } @Test public void testDeadTypes() { if (false) { new Object() {}.toString(); class Foo { void a() {} } new Foo().a(); } } /** Make sure that the compiler does not crash itself on user code that divides by zero. */ @SuppressWarnings({"divzero", "ConstantOverflow"}) @Test public void testDivByZero() { assertTrue(Double.isNaN(0.0 / 0.0)); try { assertEquals(0, 0 / 0); fail("expected an ArithmeticException"); } catch (ArithmeticException expected) { } try { volatileLong = 0L / 0; fail("expected an ArithmeticException"); } catch (ArithmeticException expected) { } assertTrue(Double.isNaN(0.0 % 0.0)); try { assertTrue(Double.isNaN(0 % 0)); fail("expected an ArithmeticException"); } catch (ArithmeticException expected) { } try { volatileLong = 0L % 0; fail("expected an ArithmeticException"); } catch (ArithmeticException expected) { } } @Test public void testEmptyBlockStatements() { boolean b = false; while (b) {} do {} while (b); for (; b; ) {} for (; ; ) { break; } if (b) {} if (b) { } else { b = false; } if (b) { } else { } } @SuppressWarnings("empty") @Test public void testEmptyStatements() { boolean b = false; while (b) ; do ; while (b); for (; b; ) ; for (int i = 0; i < 10; ++i) ; for (int i : new int[10]) ; for (Integer i : new ArrayList<Integer>()) ; for (; ; ) break; if (b) ; if (b) ; else b = false; if (b) ; else ; } @Test public void testEmptyTryBlock() { int x = 0; try { } finally { x = 1; } assertEquals(1, x); } @Test public void testCatchBlockWithKeyword() { try { throw new RuntimeException(); } catch (Exception var) { assertFalse(var.toString().isEmpty()); } } /** Ensure that only final fields are initializers when cstrs run, see issue 380. */ @Test public void testFieldInitializationOrder() { ArrayList<String> seenValues = new ArrayList<String>(); new FieldInitOrderChild(seenValues); assertEquals("i1=1,i2=0,i3=null,i4=null,i5=1,i6=1,i7=1", seenValues.get(0)); assertEquals("i1=1,i2=1,i3=1,i4=2,i5=1,i6=2,i7=2", seenValues.get(1)); } @Test public void testForStatement() { { int i; for (i = 0; i < 10; ++i) {} assertEquals(i, 10); } { int i; int c; for (i = 0, c = 10; i < c; ++i) {} assertEquals(i, 10); assertEquals(c, 10); } { int j = 0; for (int i = 0; i < 10; ++i) { ++j; } assertEquals(j, 10); } { int j = 0; for (int i = 0, c = 10; i < c; ++i) { ++j; } assertEquals(j, 10); } } /** Issue #615: Internal Compiler Error. */ @Test public void testImplicitNull() { boolean b; String test = ((((b = true) ? null : null) + " ") + b); assertTrue(b); assertEquals("null true", test); } /** * Issue 2886: inlining should cope with local variables that do not have an explicit declaration * node. */ @Test public void testInliningBoxedIncrement() { // should not actually inline, because it has a temp variable incrementBoxedInteger(); assertEquals((Integer) 1, boxedInteger); } @Test public void testJavaScriptReservedWords() { boolean delete = TRUE; for (int in = 0; in < 10; ++in) { assertTrue(in < 10); assertTrue(delete); } } @Test public void testLabels() { int i = 0; int j = 0; outer: for (i = 0; i < 1; ++i) { inner: for (j = 0; j < 1; ++j) { break outer; } fail(); } assertEquals(0, i); assertEquals(0, j); outer: for (i = 0; i < 1; ++i) { inner: for (j = 0; j < 1; ++j) { continue outer; } fail(); } assertEquals(1, i); assertEquals(0, j); outer: for (i = 0; i < 1; ++i) { inner: for (j = 0; j < 1; ++j) { break inner; } } assertEquals(1, i); assertEquals(0, j); outer: for (i = 0; i < 1; ++i) { inner: for (j = 0; j < 1; ++j) { continue inner; } } assertEquals(1, i); assertEquals(1, j); /* * Issue 2069: a default with a break should not be stripped unless the * break has no label. */ outer: while (true) { switch (THREE) { case 0: case 1: break; default: break outer; } fail("should not be reached"); } /* * Issue 2770: labeled breaks in a switch statement with no default case * should not be pruned. */ outer: while (true) { switch (THREE) { case 0: case 1: case 2: case 3: break outer; case 4: case 5: break; } } } private static final class RefObject<T> { T argvalue; RefObject(T refarg) { argvalue = refarg; } } /** * Test for issue 6471. * * <p>Cast normally can not appear on the left hand side of an assignment (they are not allowed in * Java source). However they might be present in the Java AST as a result of generics and * erasure; hence they need to be handled in the proper places. */ @Test public void testLhsCastString() { RefObject<String> prefix = new RefObject<String>("Hello"); // Due to erasure, prefix.argvalue is of type Object hence // the compiler "inserts" a cast transforming it into // ((String) prefix.argvalue) += ", goodbye!" // This way a lhs can be a cast (which is illegal in Java source code). prefix.argvalue += ", goodbye!"; assertEquals("Hello, goodbye!", prefix.argvalue); } @Test public void testLhsCastInt() { RefObject<Integer> prefix = new RefObject<Integer>(41); // Due to erasure, prefix.argvalue is of type Object hence // the compiler "inserts" a cast transforming it into // ((Integer) prefix.argvalue) ++ // This way a lhs can be a cast (which is illegal in Java source code). prefix.argvalue++; assertEquals(new Integer(42), prefix.argvalue); } @Test public void testLhsCastNested() { RefObject<Integer> prefix = new RefObject<Integer>(41); // Due to erasure, prefix.argvalue is of type Object hence // the compiler "inserts" a cast transforming it into // ((Integer) prefix.argvalue) ++ // This way a lhs can be a cast (which is illegal in Java source code). Math.max(prefix.argvalue++, 40); assertEquals(new Integer(42), prefix.argvalue); } @Test public void testLocalClasses() { class Foo { public Foo(int j) { assertEquals(1, j); }; } final int i = 1; new Foo(i) { { assertEquals(1, i); } }; assertEquals(1, i); } // TODO(B/36863860): Uncomment test when bug is fixed. // @Test public void testCaptureEvaluationOrder() { class Foo { public Foo(int j) { assertEquals(1, j); }; } final int i; new Foo(i = 1) { { assertEquals(1, i); } }; assertEquals(1, i); } @Test public void testLocalRefs() { final String foo = TRUE ? "foo" : "bar"; final String bar = TRUE ? "bar" : "foo"; String result = new Object() { private String a = foo; { a = foo; } @Override public String toString() { return new Object() { private static final String constantString = "wallawalla"; private String ai = foo; { ai = foo; } @SuppressWarnings("ReturnValueIgnored") @Override public String toString() { // this line used to cause ICE due to no synthetic path to bar bar.valueOf(false); assertEquals("wallawalla", constantString); return foo + a + ai; } }.toString() + a; } }.toString(); assertEquals(result, "foofoofoofoo"); } /** test for issue 7824. */ @Test public void testMethodNamedSameAsClass() { MethodNamedSameAsClass obj = new MethodNamedSameAsClass(); obj.MethodNamedSameAsClass(); } @Test public void testNotOptimizations() { assertFalse(!true); assertTrue(!false); assertTrue(!(TRUE == FALSE)); assertFalse(!(TRUE != FALSE)); assertFalse(!(3 < 4)); assertFalse(!(3 <= 4)); assertTrue(!(3 > 4)); assertTrue(!(3 >= 4)); assertTrue(!(4 < 3)); assertTrue(!(4 <= 3)); assertFalse(!(4 > 3)); assertFalse(!(4 >= 3)); assertTrue(!!TRUE); assertFalse(!!FALSE); double nan = Math.random() == 0 ? Double.NaN : Double.NaN; assertFalse(nan == (0.0 / 0.0)); assertTrue(!(nan > 0)); assertTrue(!(nan < 0)); assertFalse(!!(nan > 0)); } @Test public void testNullFlow() { UninstantiableType f = null; try { f.returnNull().getClass(); fail(); } catch (NullPointerException expected) { } try { UninstantiableType[] fa = null; fa[4] = null; fail(); } catch (NullPointerException expected) { } } @Test public void testNullFlowArray() { UninstantiableType[] uta = new UninstantiableType[10]; assertEquals(uta.length, 10); assertEquals(uta[0], null); uta[1] = null; assertEquals(uta[1], null); } @Test public void testNullFlowOverloads() { foo((Throwable) null); foo((String) null); } @Test public void testNullFlowVsClassCastPrecedence() { assertThrows(ClassCastException.class, () -> ((UninstantiableType) new Object()).returnNull()); } @Test public void testOuterSuperThisRefs() { new B(); } /** * Test that calling a private instance method does not accidentally call another private method * that appears to override it. Private methods don't truly override each other. */ @Test public void testPrivateOverride() { assertEquals(0, new TpoChild().foo()); } @Test public void testReturnStatementInCtor() { class Foo { int i; Foo(int i) { this.i = i; if (i == 0) { return; } else if (i == 1) { return; } return; } } assertEquals(new Foo(0).i, 0); assertEquals(new Foo(1).i, 1); assertEquals(new Foo(2).i, 2); } @Test public void testStaticMethodResolution() { // Issue 2922 assertEquals("AbstractSuper", AbstractSuper.foo()); } @Test public void testStringOptimizations() { assertEquals("Herro, AJAX", "Hello, AJAX".replace('l', 'r')); assertEquals('J', "Hello, AJAX".charAt(8)); assertEquals(11, "Hello, AJAX".length()); assertFalse("Hello, AJAX".equals("me")); assertTrue("Hello, AJAX".equals("Hello, AJAX")); assertTrue("Hello, AJAX".equalsIgnoreCase("HELLO, ajax")); assertEquals("hello, ajax", "Hello, AJAX".toLowerCase(Locale.ROOT)); assertEquals("foobar", "foo" + barShouldInline()); assertEquals("1bar", 1 + barShouldInline()); assertEquals("fbar", 'f' + barShouldInline()); assertEquals("truebar", true + barShouldInline()); assertEquals("3.5bar", 3.5 + barShouldInline()); assertEquals("3.5bar", 3.5f + barShouldInline()); assertEquals("27bar", 27L + barShouldInline()); assertEquals("nullbar", null + barShouldInline()); } @Test public void testSubclassStaticInnerAndClinitOrdering() { new CheckSubclassStaticInnerAndClinitOrdering(); } @Test public void testSwitchOnEnumTypedThis() { assertEquals("POSITIVE", ChangeDirection.POSITIVE.getText()); assertEquals("NEGATIVE", ChangeDirection.NEGATIVE.getText()); } @Test public void testSwitchStatement() { switch (0) { case 0: // Once caused an ICE. int test; break; } } /** Tests cases where the compiler will convert to a simple if or block. */ @Test public void testSwitchStatementConversions() { int i = 1; switch (i) { case 1: i = 2; } assertEquals(2, i); switch (i) { case 1: i = 3; } assertEquals(2, i); switch (i) { default: i = 3; } assertEquals(3, i); } @Test public void testSwitchStatementEmpty() { switch (0) { } } @Test public void testSwitchStatementFallthroughs() { int i = 1; switch (i) { case 1: i = 2; // fallthrough case 2: break; case 3: fail("Shouldn't get here"); } assertEquals(2, i); switch (i) { case 1: break; case 2: i = 3; break; case 3: break; case 4: fail("Shouldn't get here"); break; } assertEquals(3, i); } @Test public void testSwitchStatementWithUsefulDefault() { switch (1) { case 1: case 2: case 3: { break; } case 4: case 5: case 6: default: fail("Shouldn't get here"); break; } } @Test public void testSwitchStatementWithUselessCases() { switch (1) { case 1: case 2: case 3: { break; } case 4: case 5: case 6: default: break; } } @Test public void testSwitchStatementWontRemoveExpression() { class Foo { boolean setFlag; int setFlag() { setFlag = true; return 3; } } Foo foo = new Foo(); switch (foo.setFlag()) { case 3: break; } // Make sure that compiler didn't optimize away the switch statement's // expression assertTrue(foo.setFlag); } @Test public void testUnaryPlus() { int x; int y = -7; x = +y; assertEquals(-7, x); } private void incrementBoxedInteger() { // the following will need a temporary variable created boxedInteger++; } private static boolean returnFalse() { return false; } class A { public abstract class AA {} } class B extends A { { new AA() {}; } } private static void assertTrue(boolean b) { assertThat(b).isTrue(); } private static void assertFalse(boolean b) { assertThat(b).isFalse(); } private static <U, V> void assertEquals(U expected, V value) { assertThat(value).isEqualTo(expected); } private static <U, V> void assertEquals(String message, U expected, V value) { assertWithMessage(message).that(value).isEqualTo(expected); } private static <U, V> void assertSame(String message, U expected, V value) { assertWithMessage(message).that(value).isSameInstanceAs(expected); } private static <U, V> void assertSame(U expected, V value) { assertThat(value).isSameInstanceAs(expected); } private static <U> void assertNotNull(U value) { assertThat(value).isNotNull(); } private static <U> void assertNull(U value) { assertThat(value).isNull(); } private static <U, V> void assertNotSame(String message, U expected, V value) { assertWithMessage(message).that(value).isNotSameInstanceAs(expected); } private static <U, V> void assertNotSame(U expected, V value) { assertThat(value).isNotSameInstanceAs(expected); } } // This construct used to cause an ICE class CheckSubclassStaticInnerAndClinitOrdering extends Outer.StaticInner { private static class Foo {} private static final Foo FOO = new Foo(); public CheckSubclassStaticInnerAndClinitOrdering() { this(FOO); } public CheckSubclassStaticInnerAndClinitOrdering(Foo foo) { // This used to be null due to clinit ordering issues assertThat(foo).isNotNull(); } } class Outer { public static class StaticInner {} } /** * A superclass that invokes a method in its cstr, so that subclasses can see their state before * their own cstr has run. * * <p>See {@link CompilerTest#testFieldInitializationOrder()}. */ class FieldInitOrderBase { FieldInitOrderBase(ArrayList<String> seenValues, int x) { method(seenValues, x); } void method(ArrayList<String> seenValues, int x) {} } /** * A subclass that overrides {@link #method(ArrayList, int)} to see what the values of its own * fields are from within the superclass's cstr (before our own cstr has run). * * <p>See {@link CompilerTest#testFieldInitializationOrder()}. */ @SuppressWarnings("BoxedPrimitiveConstructor") class FieldInitOrderChild extends FieldInitOrderBase { private final int i1 = 1; private int i2 = 1; private Integer i3 = new Integer(1); private Integer i4; private static final int i5 = 1; private static int i6 = 1; private static Integer i7 = new Integer(1); FieldInitOrderChild(ArrayList<String> seenValues) { // the superclass calls method(), which will record the pre-cstr value of our fields super(seenValues, 2); recordValues(seenValues); } // invoked by the super classes before our cstr has run @Override void method(ArrayList<String> seenValues, int x) { recordValues(seenValues); // i1 is final i2 = x; i3 = new Integer(x); i4 = new Integer(x); // i5 is final i6 = 2; i7 = new Integer(x); } private void recordValues(ArrayList<String> seenValues) { // i3, i4 and i7 would be directly converted into strings hence show undefined instead of null. // String operations should take care of corner cases where a string is null or undefined // see issue 8257. seenValues.add( "i1=" + i1 + ",i2=" + i2 + ",i3=" + (i3 == null ? null : i3) + ",i4=" + (i4 == null ? null : i4) + ",i5=" + i5 + ",i6=" + i6 + ",i7=" + (i7 == null ? null : i7)); } } class MethodNamedSameAsClass { public void MethodNamedSameAsClass() {} }